diff --git a/server/src/routes/health.ts b/server/src/routes/health.ts index d088514bd0c..b5ce0f0fcfb 100644 --- a/server/src/routes/health.ts +++ b/server/src/routes/health.ts @@ -399,7 +399,7 @@ export function healthRoutes( : null; const databaseBackup = opts.databaseBackupHealth - ? inspectDatabaseBackupHealth(opts.databaseBackupHealth) + ? await inspectDatabaseBackupHealth(opts.databaseBackupHealth) : undefined; const warnings = databaseBackup?.warnings.length ? databaseBackup.warnings : undefined; const nativeRecovery = exposeFullDetails diff --git a/server/src/services/database-backup-health.test.ts b/server/src/services/database-backup-health.test.ts new file mode 100644 index 00000000000..2e4daa6b02b --- /dev/null +++ b/server/src/services/database-backup-health.test.ts @@ -0,0 +1,102 @@ +import * as fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { inspectDatabaseBackupHealth } from "./database-backup-health.js"; + +vi.mock("node:fs/promises", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, readdir: vi.fn(actual.readdir), stat: vi.fn(actual.stat) }; +}); + +const NOW = new Date("2026-09-30T12:00:00Z"); +let directory: string; +const inspect = () => inspectDatabaseBackupHealth({ enabled: true, backupDir: directory, maxAgeHours: 24, now: NOW }); + +async function backup(name: string, ageHours: number) { + const file = path.join(directory, name); + await fs.writeFile(file, "backup"); + const date = new Date(NOW.getTime() - ageHours * 3_600_000); + await fs.utimes(file, date, date); + return file; +} + +beforeEach(async () => { vi.resetAllMocks(); directory = await fs.mkdtemp(path.join(os.tmpdir(), "backup-health-")); }); +afterEach(async () => { vi.restoreAllMocks(); await fs.rm(directory, { recursive: true, force: true }); }); + +describe("database backup health", () => { + it("selects the newest backup by modification time", async () => { + await backup("a.sql.gz", 1); + await backup("z.sql.gz", 2); + expect(await inspect()).toMatchObject({ status: "ok", latestBackup: { name: "a.sql.gz", ageHours: 1, sizeBytes: 6 }, warnings: [] }); + }); + + it("reports an old backup as stale", async () => { + await backup("old.sql.gz", 25); + expect((await inspect()).warnings[0].code).toBe("database_backup_stale"); + }); + + it("reports a missing directory as missing, without a check failure", async () => { + await fs.rm(directory, { recursive: true }); + expect((await inspect()).warnings.map((warning) => warning.code)).toEqual(["database_backup_missing"]); + }); + + it("reports the first line of a failure marker", async () => { + await backup("recent.sql.gz", 1); + await fs.writeFile(path.join(directory, "db-backup-to-s3.failure"), "Backup upload failed\nprivate diagnostic\n"); + expect((await inspect()).lastFailure?.message).toBe("Backup upload failed"); + }); + + it("reports an unreadable directory as a failed check", async () => { + vi.mocked(fs.readdir).mockRejectedValueOnce(Object.assign(new Error("permission denied"), { code: "EACCES" })); + expect((await inspect()).warnings.map((warning) => warning.code)).toEqual(["database_backup_check_failed"]); + }); + + it("ignores a backup removed by retention after the directory listing", async () => { + await backup("removed.sql.gz", 1); + vi.mocked(fs.stat).mockRejectedValueOnce(Object.assign(new Error("removed"), { code: "ENOENT" })); + expect((await inspect()).warnings.map((warning) => warning.code)).toEqual(["database_backup_missing"]); + }); + + it("bounds metadata reads while scanning retained backups", async () => { + for (let index = 0; index < 12; index++) await backup(`${index}.sql.gz`, index + 1); + const actual = await vi.importActual("node:fs/promises"); + let active = 0; + let peak = 0; + vi.mocked(fs.stat).mockImplementation((async (...args: Parameters) => { + const isArchive = String(args[0]).endsWith(".sql.gz"); + if (isArchive) { + active++; + peak = Math.max(peak, active); + } + try { + await new Promise((resolve) => setTimeout(resolve, 1)); + return await actual.stat(...args); + } finally { + if (isArchive) active--; + } + }) as typeof fs.stat); + expect((await inspect()).latestBackup?.name).toBe("0.sql.gz"); + // Count archive I/O only; parallel marker reads must not make a fully + // sequential archive scan satisfy the lower bound. + const archiveReads = vi.mocked(fs.stat).mock.calls.filter(([file]) => String(file).endsWith(".sql.gz")); + expect(archiveReads).toHaveLength(12); + expect(peak).toBeGreaterThan(1); + expect(peak).toBeLessThanOrEqual(4); + }); + + it("lets a timer run while the filesystem observation is pending", async () => { + let release!: () => void; + const held = new Promise((resolve) => { release = () => resolve([]); }); + vi.mocked(fs.readdir).mockImplementationOnce(() => held as unknown as ReturnType); + let finished = false; + const pending = inspect().then((result) => { finished = true; return result; }); + try { + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(finished).toBe(false); + } finally { + release(); + } + expect((await pending).warnings[0].code).toBe("database_backup_missing"); + }); +}); diff --git a/server/src/services/database-backup-health.ts b/server/src/services/database-backup-health.ts index efb076db35a..95aa31f1ef3 100644 --- a/server/src/services/database-backup-health.ts +++ b/server/src/services/database-backup-health.ts @@ -1,4 +1,5 @@ -import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { readdir, readFile, stat } from "node:fs/promises"; +import type { Stats } from "node:fs"; import { basename, join, resolve } from "node:path"; export type DatabaseBackupHealthWarningCode = @@ -54,20 +55,28 @@ function alertFileCandidates(opts: InspectDatabaseBackupHealthOptions) { ].filter((value): value is string => Boolean(value)))]; } -function readLastFailure(alertFiles: string[]) { - const failures = alertFiles - .filter((alertFile) => existsSync(alertFile)) - .map((alertFile) => { - const stat = statSync(alertFile); - const message = readFileSync(alertFile, "utf8").trim().split(/\r?\n/)[0] || +function isMissing(error: unknown): boolean { + return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT"; +} + +async function readLastFailure(alertFiles: string[]) { + const failures = (await Promise.all(alertFiles.map(async (alertFile) => { + try { + const metadata = await stat(alertFile); + const message = (await readFile(alertFile, "utf8")).trim().split(/\r?\n/)[0] || "Database backup failure marker is present."; return { path: alertFile, - mtime: new Date(stat.mtimeMs).toISOString(), - mtimeMs: stat.mtimeMs, + mtime: new Date(metadata.mtimeMs).toISOString(), + mtimeMs: metadata.mtimeMs, message, }; - }) + } catch (error) { + if (isMissing(error)) return null; + throw error; + } + }))) + .filter((failure) => failure !== null) .sort((left, right) => right.mtimeMs - left.mtimeMs); const latest = failures[0]; if (!latest) return null; @@ -78,19 +87,35 @@ function readLastFailure(alertFiles: string[]) { }; } -function findLatestBackup(backupDir: string, nowMs: number) { - if (!existsSync(backupDir)) return null; - - const candidates = readdirSync(backupDir) - .filter((name) => name.endsWith(".sql.gz")) - .map((name) => { +async function findLatestBackup(backupDir: string, nowMs: number) { + let names: string[]; + try { + names = await readdir(backupDir); + } catch (error) { + if (isMissing(error)) return null; + throw error; + } + let latest: { fullPath: string; stat: Stats } | null = null; + // Keep bounded parallelism so a retained history neither floods the + // filesystem thread pool nor waits for every metadata read sequentially. + const archives = names.filter((name) => name.endsWith(".sql.gz")); + for (let index = 0; index < archives.length; index += 4) { + const batch = await Promise.all(archives.slice(index, index + 4).map(async (name) => { const fullPath = join(backupDir, name); - const stat = statSync(fullPath); - return { fullPath, name, stat }; - }) - .sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs); - - const latest = candidates[0]; + try { + return { fullPath, stat: await stat(fullPath) }; + } catch (error) { + // Retention can remove a listed backup while its metadata is read. + if (isMissing(error)) return null; + throw error; + } + })); + for (const candidate of batch) { + if (candidate && (!latest || candidate.stat.mtimeMs > latest.stat.mtimeMs)) { + latest = candidate; + } + } + } if (!latest) return null; return { @@ -102,9 +127,9 @@ function findLatestBackup(backupDir: string, nowMs: number) { }; } -export function inspectDatabaseBackupHealth( +export async function inspectDatabaseBackupHealth( opts: InspectDatabaseBackupHealthOptions, -): DatabaseBackupHealthStatus { +): Promise { const warnings: DatabaseBackupHealthWarning[] = []; const now = opts.now ?? new Date(); const maxAgeHours = Math.max(1, opts.maxAgeHours); @@ -113,8 +138,8 @@ export function inspectDatabaseBackupHealth( let lastFailure: DatabaseBackupHealthStatus["lastFailure"] = null; try { - latestBackup = findLatestBackup(opts.backupDir, now.getTime()); - lastFailure = readLastFailure(alertFileCandidates(opts)); + latestBackup = await findLatestBackup(opts.backupDir, now.getTime()); + lastFailure = await readLastFailure(alertFileCandidates(opts)); if (!latestBackup) { warnings.push({