Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- The standalone launcher uses Node built-ins only.
2import * as NodeSqlite from "node:sqlite";
3import * as NodeFSP from "node:fs/promises";
4import * as NodePath from "node:path";
5
6function openWalReader(databasePath: string) {
7 let source: NodeSqlite.DatabaseSync | undefined;
8 try {
9 source = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
10 source.exec("PRAGMA busy_timeout = 5000; BEGIN");
11 source.prepare("SELECT name FROM sqlite_schema LIMIT 1").get();
12 if (source.prepare("PRAGMA journal_mode").get()?.journal_mode === "wal") return source;
13 } catch {
14 // Fall back to the stopped copy.
15 }
16 source?.close();
17 return undefined;
18}
19
20/**
21 * Pin WAL frames with a read transaction until shutdown, then overlay the final
22 * WAL on the online snapshot so rollback keeps writes made during the copy.
23 */
24export async function prepareServiceDatabaseBackup(databasePath: string, stagingDir: string) {
25 const source = openWalReader(databasePath);
26 if (source === undefined) return undefined;
27 try {
28 await NodeFSP.rm(stagingDir, { recursive: true, force: true });
29 await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 });
30 const destination = NodePath.join(stagingDir, "database");
31 await NodeSqlite.backup(source, destination, { rate: 256 });
32 // Enable WAL before installing it; do not open the destination again before restore.
33 const snapshot = new NodeSqlite.DatabaseSync(destination);
34 try {
35 snapshot.exec("PRAGMA journal_mode = WAL");
36 } finally {
37 snapshot.close();
38 }
39 const file = await NodeFSP.open(destination, "r+");
40 try {
41 await file.sync();
42 } finally {
43 await file.close();
44 }
45 return {
46 async finish() {
47 try {
48 await NodeFSP.copyFile(`${databasePath}-wal`, NodePath.join(stagingDir, "database-wal"));
49 const wal = await NodeFSP.open(NodePath.join(stagingDir, "database-wal"), "r+");
50 try {
51 await wal.sync();
52 } finally {
53 await wal.close();
54 }
55 } catch (cause) {
56 if (!(cause instanceof Error && "code" in cause && cause.code === "ENOENT")) throw cause;
57 }
58 },
59 close() {
60 source.close();
61 },
62 };
63 } catch (cause) {
64 source.close();
65 await NodeFSP.rm(stagingDir, { recursive: true, force: true });
66 throw cause;
67 }
68}