Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - The supervisor lock is a native SQLite handle held for the runner's lifetime.
2import * as NodeSqlite from "node:sqlite";
3
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7import * as Schema from "effect/Schema";
8
9export class DevRunnerStateDirInUseError extends Schema.TaggedError<DevRunnerStateDirInUseError>()(
10 "DevRunnerStateDirInUseError",
11 { stateDir: Schema.String, owner: Schema.String },
12) {
13 override get message(): string {
14 return `Another dev runner already uses ${this.stateDir} (${this.owner}). Stop it, or pass --home-dir to use a separate T3 home.`;
15 }
16}
17
18export class DevRunnerLockError extends Schema.TaggedError<DevRunnerLockError>()(
19 "DevRunnerLockError",
20 { stateDir: Schema.String, cause: Schema.Defect() },
21) {
22 override get message(): string {
23 return `Could not lock ${this.stateDir} for this dev runner.`;
24 }
25}
26
27const isSqliteBusy = (cause: unknown) =>
28 cause instanceof Error &&
29 (("errcode" in cause && cause.errcode === 5) ||
30 ("code" in cause && cause.code === "SQLITE_BUSY"));
31
32/**
33 * One dev runner per state directory: its server restarts on every file change,
34 * and the server's own ownership lock would hand the directory to whichever
35 * runner restarts first. The OS releases this lock when the runner exits.
36 */
37export const acquireDevRunnerLock = Effect.fn("dev-runner.acquireDevRunnerLock")(function* (
38 stateDir: string,
39 owner: string,
40) {
41 const fs = yield* FileSystem.FileSystem;
42 const path = yield* Path.Path;
43 const ownerPath = path.join(stateDir, "dev-runner-owner.txt");
44 yield* fs
45 .makeDirectory(stateDir, { recursive: true })
46 .pipe(Effect.mapError((cause) => new DevRunnerLockError({ stateDir, cause })));
47 const opened = yield* Effect.acquireRelease(
48 Effect.try({
49 try: () => {
50 const db = new NodeSqlite.DatabaseSync(path.join(stateDir, "dev-runner.sqlite"));
51 try {
52 db.exec("BEGIN EXCLUSIVE;");
53 return { db, busy: false };
54 } catch (cause) {
55 db.close();
56 if (isSqliteBusy(cause)) return { db: undefined, busy: true };
57 throw cause;
58 }
59 },
60 catch: (cause) => new DevRunnerLockError({ stateDir, cause }),
61 }),
62 ({ db }) => Effect.sync(() => db?.close()),
63 );
64 if (opened.busy) {
65 const recorded = yield* fs.readFileString(ownerPath).pipe(Effect.orElseSucceed(() => ""));
66 return yield* new DevRunnerStateDirInUseError({
67 stateDir,
68 owner: recorded.trim() || "owner unknown",
69 });
70 }
71 yield* fs
72 .writeFileString(ownerPath, owner)
73 .pipe(Effect.mapError((cause) => new DevRunnerLockError({ stateDir, cause })));
74});