fix(server): service updates no longer stop the server when the database backup cannot fit #14520
Closedsaphid(GitHub profile, opens in a new tab)wants to merge 10 commits into
main fromrefs/pull/14520/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/serviceLauncher.ts lines 142 to 142OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -108,0 +122,21 @@122+ ? ["-c", source, destination]123+ : platform === "linux"124+ ? ["--reflink=auto", source, destination]125+ : undefined;126+ if (args === undefined) return NodeFSP.copyFile(source, destination);127+ return new Promise((resolve, reject) => {128+ NodeChildProcess.execFile("cp", args, (error) => {129+ if (error === null) resolve();130+ else NodeFSP.copyFile(source, destination).then(resolve, reject);131+ });132+ });133+}134+135+const GIB = 1024 ** 3;136+/** Clones share blocks, but the live database diverges from them once it writes again. */137+const CLONED_BACKUP_MIN_HEADROOM_BYTES = GIB;138+139+async function databaseSizeBytes(dbPath: string): Promise<number> {140+ let total = 0;141+ for (const suffix of DB_FILE_SUFFIXES) {142+ const stat = await NodeFSP.stat(`${dbPath}${suffix}`).catch(() => undefined);apps/server/src/serviceLauncher.ts line 210OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -108,0 +190,21 @@190+ return stats.bavail * stats.bsize;191+};192+193+/**194+ * Returns a client-visible reason when the pre-update database backup cannot195+ * fit, or undefined when it can. Runs before the server is stopped so a full196+ * disk refuses the update instead of causing an outage and a cold restart.197+ * The clone probe writes 32 MiB of its own, so it only runs when a full copy198+ * does not fit but a clone's headroom does.199+ */200+export async function databaseBackupBlocker(201+ baseDir: string,202+ dbPath: string,203+ readFreeBytes: ReadFreeBytes = readFreeBytesFromFilesystem,204+): Promise<string | undefined> {205+ const backupRoot = NodePath.join(baseDir, "runtime", "db-backup");206+ await NodeFSP.mkdir(backupRoot, { recursive: true, mode: 0o700 });207+ const [size, free] = await Promise.all([databaseSizeBytes(dbPath), readFreeBytes(backupRoot)]);208+ const fullCopyBytes = size * 1.05;209+ if (free >= fullCopyBytes) return undefined;210+ const clonedBytes = Math.max(CLONED_BACKUP_MIN_HEADROOM_BYTES, size * 0.02);@@ -509,3 +627,6 @@509627 await reject("The requested target runtime is missing or incomplete.");510628 return;511629 }630+ // A check that cannot run refuses the update too: the alternative is631+ // stopping the server without knowing whether the backup fits.632+ const backupBlocker = await databaseBackupBlocker(
juliusmarminge added labelsmacroscope-review
- apps/server/src/serviceLauncher.ts line 142OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -108,0 +122,21 @@122+ ? ["-c", source, destination]123+ : platform === "linux"124+ ? ["--reflink=auto", source, destination]125+ : undefined;126+ if (args === undefined) return NodeFSP.copyFile(source, destination);127+ return new Promise((resolve, reject) => {128+ NodeChildProcess.execFile("cp", args, (error) => {129+ if (error === null) resolve();130+ else NodeFSP.copyFile(source, destination).then(resolve, reject);131+ });132+ });133+}134+135+const GIB = 1024 ** 3;136+/** Clones share blocks, but the live database diverges from them once it writes again. */137+const CLONED_BACKUP_MIN_HEADROOM_BYTES = GIB;138+139+async function databaseSizeBytes(dbPath: string): Promise<number> {140+ let total = 0;141+ for (const suffix of DB_FILE_SUFFIXES) {142+ const stat = await NodeFSP.stat(`${dbPath}${suffix}`).catch(() => undefined);apps/server/src/serviceLauncher.ts line 171OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -108,0 +151,21 @@151+ * Whether copying into the backup directory clones instead of duplicating,152+ * measured with the real copy function: a clone of a fresh 32 MiB file153+ * consumes almost no free space, a copy consumes all of it. Errs toward "no"154+ * when other disk activity muddies the reading, and when the database and the155+ * backup directory are on different filesystems, where nothing can clone.156+ */157+async function backupCanClone(158+ backupRoot: string,159+ dbPath: string,160+ readFreeBytes: (directory: string) => Promise<number>,161+): Promise<boolean> {162+ const [dbDirectory, backupDirectory] = await Promise.all([163+ NodeFSP.stat(NodePath.dirname(dbPath)),164+ NodeFSP.stat(backupRoot),165+ ]);166+ if (dbDirectory.dev !== backupDirectory.dev) return false;167+ const id = NodeCrypto.randomUUID();168+ const probeSource = NodePath.join(NodePath.dirname(dbPath), `.clone-probe-${id}`);169+ const probeTarget = NodePath.join(backupRoot, `.clone-probe-${id}`);170+ try {171+ await NodeFSP.writeFile(probeSource, NodeCrypto.randomBytes(CLONE_PROBE_BYTES));apps/server/src/serviceLauncher.ts line 177OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -108,0 +157,21 @@157+async function backupCanClone(158+ backupRoot: string,159+ dbPath: string,160+ readFreeBytes: (directory: string) => Promise<number>,161+): Promise<boolean> {162+ const [dbDirectory, backupDirectory] = await Promise.all([163+ NodeFSP.stat(NodePath.dirname(dbPath)),164+ NodeFSP.stat(backupRoot),165+ ]);166+ if (dbDirectory.dev !== backupDirectory.dev) return false;167+ const id = NodeCrypto.randomUUID();168+ const probeSource = NodePath.join(NodePath.dirname(dbPath), `.clone-probe-${id}`);169+ const probeTarget = NodePath.join(backupRoot, `.clone-probe-${id}`);170+ try {171+ await NodeFSP.writeFile(probeSource, NodeCrypto.randomBytes(CLONE_PROBE_BYTES));172+ await syncFile(probeSource);173+ const before = await readFreeBytes(backupRoot);174+ await copyDatabaseFile(probeSource, probeTarget);175+ await syncFile(probeTarget);176+ const after = await readFreeBytes(backupRoot);177+ return before - after < CLONE_PROBE_BYTES / 4;
- @@ -509,3 +647,14 @@509647 await reject("The requested target runtime is missing or incomplete.");510648 return;511649 }650+ // A check that cannot run refuses the update too: the alternative is651+ // stopping the server without knowing whether the backup fits.652+ const backupBlocker = await databaseBackupBlocker(653+ this.#baseDir,654+ message.dbPath,655+ this.#backupSpaceProbe,656+ ).catch(657+ (error: unknown) =>658+ `Could not check that the database backup fits before updating: ${error instanceof Error ? error.message : String(error)}. The server was not stopped.`,659+ );660+ if (backupBlocker !== undefined) {
- apps/server/src/serviceLauncher.ts line 178OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -108,0 +158,21 @@158+ NodeChildProcess.execFile("cp", args, (error) => resolve(error === null));159+ });160+}161+162+/**163+ * Whether `copyDatabaseFile` will clone the database into the backup164+ * directory rather than copy it.165+ * - macOS: `cp -c` clones within one APFS volume and silently copies166+ * anywhere else, so both directories must share a device whose filesystem167+ * type matches the system volume's, which is always APFS.168+ * - Linux: clone each existing database file with `cp --reflink=always`,169+ * which fails instead of copying when a file cannot be reflinked (another170+ * filesystem, or a btrfs file marked No_COW), then discard the clones.171+ * - Elsewhere: never.172+ */173+async function backupCanClone(dbPath: string, backupRoot: string): Promise<boolean> {174+ // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.175+ const platform = process.platform;176+ if (platform === "darwin") {177+ const [dbDirectory, backupDirectory, backupFs, systemFs] = await Promise.all([178+ NodeFSP.stat(NodePath.dirname(dbPath)),
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed