@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 106 lines 4.1 KB
Raw
1 import * as NodeWorkerThreads from "node:worker_threads";
2
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Path from "effect/Path";
6 import * as Schema from "effect/Schema";
7
8 export 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 }
15 }
16
17 const isV2DatabaseImportError = Schema.is(V2DatabaseImportError);
18
19 const isProcessAlive = (pid: number): boolean => {
20 if (!Number.isInteger(pid) || pid <= 0) return false;
21 try {
22 process.kill(pid, 0);
23 return true;
24 } catch (error) {
25 return error instanceof Error && "code" in error && error.code === "EPERM";
26 }
27 };
28
29 // V1 files predate auto_vacuum, and a page backup would keep that. VACUUM INTO compacts the copy and
30 // enables incremental mode, so the server can return freed pages; the worker keeps it off the event loop.
31 const snapshotWorkerSource = `
32 const { workerData } = require("node:worker_threads");
33 const { DatabaseSync } = require("node:sqlite");
34 const database = new DatabaseSync(workerData.sourcePath, { readOnly: true });
35 try {
36 database.exec("PRAGMA auto_vacuum = INCREMENTAL");
37 database.prepare("VACUUM INTO ?").run(workerData.snapshotPath);
38 } finally {
39 database.close();
40 }
41 `;
42
43 // Legacy names have no PID; newer copies stay while their process is alive.
44 const removeAbandonedCopies = Effect.fn("removeAbandonedCopies")(function* (directory: string) {
45 const fs = yield* FileSystem.FileSystem;
46 const path = yield* Path.Path;
47 const entries = yield* fs.readDirectory(directory).pipe(
48 Effect.catchIf(
49 (error) => error.reason._tag === "NotFound",
50 () => Effect.succeed([]),
51 ),
52 );
53 for (const entry of entries) {
54 const copy = /^\.v2-import-(?:(\d+)-)?[A-Za-z0-9]{6}$/.exec(entry);
55 if (copy === null || (copy[1] !== undefined && isProcessAlive(Number(copy[1])))) continue;
56 yield* fs.remove(path.join(directory, entry), { recursive: true });
57 }
58 });
59
60 /** Its copied legacy tables remain the source for lazy transcript import. */
61 export const initializeV2Database = Effect.fn("initializeV2Database")(function* (
62 destinationPath: string,
63 ) {
64 const fs = yield* FileSystem.FileSystem;
65 const path = yield* Path.Path;
66 const directory = path.dirname(destinationPath);
67 const sourcePath = path.join(directory, "state.sqlite");
68 yield* removeAbandonedCopies(directory).pipe(Effect.ignore({ log: true }));
69 yield* Effect.gen(function* () {
70 if (yield* fs.exists(destinationPath)) return;
71 if (!(yield* fs.exists(sourcePath))) return;
72 const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
73 directory,
74 prefix: `.v2-import-${process.pid}-`,
75 });
76 const snapshotPath = path.join(temporaryDirectory, "snapshot.sqlite");
77 yield* Effect.callback<void, V2DatabaseImportError>((resume) => {
78 const fail = (cause: unknown) =>
79 resume(Effect.fail(new V2DatabaseImportError({ sourcePath, destinationPath, cause })));
80 const worker = new NodeWorkerThreads.Worker(snapshotWorkerSource, {
81 eval: true,
82 workerData: { sourcePath, snapshotPath },
83 });
84 worker.once("error", fail);
85 worker.once("exit", (code) =>
86 code === 0 ? resume(Effect.void) : fail(new Error(`Snapshot worker exited with ${code}`)),
87 );
88 // Interruption waits for the worker to exit before the scope removes its directory.
89 return Effect.promise(() => worker.terminate());
90 });
91 // Publish only a complete snapshot, without replacing an existing V2 database.
92 yield* fs.link(snapshotPath, destinationPath).pipe(
93 Effect.catchIf(
94 (error) => error.reason._tag === "AlreadyExists",
95 (_error) => Effect.void,
96 ),
97 );
98 }).pipe(
99 Effect.scoped,
100 Effect.mapError((cause) =>
101 isV2DatabaseImportError(cause)
102 ? cause
103 : new V2DatabaseImportError({ sourcePath, destinationPath, cause }),
104 ),
105 );
106 });