Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

initializeV2Database.ts

80 lines3.0 KB

1import * as NodeSqlite from "node:sqlite";
2​
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6import * as Schema from "effect/Schema";
7​
8export class V2DatabaseImportError extends Schema.TaggedError<V2DatabaseImportError>()(
9 "V2DatabaseImportError",
10 { sourcePath: Schema.String, destinationPath: Schema.String, cause: Schema.Defect() },
11) {
12 override get message() {
13 return `Could not copy the V1 database at ${this.sourcePath} to ${this.destinationPath}. The V1 database has not been migrated.`;
14 }
16​
17const isProcessAlive = (pid: number): boolean => {
18 if (!Number.isInteger(pid) || pid <= 0) return false;
19 try {
20 process.kill(pid, 0);
21 return true;
22 } catch (error) {
23 return error instanceof Error && "code" in error && error.code === "EPERM";
24 }
25};
26​
27// Legacy names have no PID; newer copies stay while their process is alive.
28const removeAbandonedCopies = Effect.fn("removeAbandonedCopies")(function* (directory: string) {
29 const fs = yield* FileSystem.FileSystem;
30 const path = yield* Path.Path;
31 const entries = yield* fs.readDirectory(directory).pipe(
32 Effect.catchIf(
33 (error) => error.reason._tag === "NotFound",
34 () => Effect.succeed([]),
35 ),
36 );
37 for (const entry of entries) {
38 const copy = /^\.v2-import-(?:(\d+)-)?[A-Za-z0-9]{6}$/.exec(entry);
39 if (copy === null || (copy[1] !== undefined && isProcessAlive(Number(copy[1])))) continue;
40 yield* fs.remove(path.join(directory, entry), { recursive: true });
41 }
42});
43​
44/** Its copied legacy tables remain the source for lazy transcript import. */
45export const initializeV2Database = Effect.fn("initializeV2Database")(function* (
46 destinationPath: string,
47) {
48 const fs = yield* FileSystem.FileSystem;
49 const path = yield* Path.Path;
50 const directory = path.dirname(destinationPath);
51 const sourcePath = path.join(directory, "state.sqlite");
52 yield* removeAbandonedCopies(directory).pipe(Effect.ignore({ log: true }));
53 yield* Effect.gen(function* () {
54 if (yield* fs.exists(destinationPath)) return;
55 if (!(yield* fs.exists(sourcePath))) return;
56 const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
57 directory,
58 prefix: `.v2-import-${process.pid}-`,
59 });
60 const snapshotPath = path.join(temporaryDirectory, "snapshot.sqlite");
61 yield* Effect.tryPromise(async () => {
62 const database = new NodeSqlite.DatabaseSync(sourcePath, { readOnly: true });
63 try {
64 await NodeSqlite.backup(database, snapshotPath);
65 } finally {
66 database.close();
67 }
68 });
69 // Publish only a complete snapshot, without replacing an existing V2 database.
70 yield* fs.link(snapshotPath, destinationPath).pipe(
71 Effect.catchIf(
72 (error) => error.reason._tag === "AlreadyExists",
73 (_error) => Effect.void,
74 ),
75 );
76 }).pipe(
77 Effect.scoped,
78 Effect.mapError((cause) => new V2DatabaseImportError({ sourcePath, destinationPath, cause })),
79 );
80});