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

serverOwnershipLock.ts

76 lines3.0 KB

1// @effect-diagnostics nodeBuiltinImport:off
2// @effect-diagnostics preferSchemaOverJson:off - The standalone launcher cannot depend on Effect.
3// Shared with the standalone service launcher. Keep imports limited to native modules.
4import * as NodeFSP from "node:fs/promises";
5import * as NodePath from "node:path";
6​
7/** Never unlink this file. SQLite releases its OS lock when the holder exits. */
8export async function acquireServerOwnershipLock(
9 directory: string,
10 options?: { readonly guardLegacyOwner?: boolean },
11) {
12 await NodeFSP.mkdir(directory, { recursive: true });
13 const stateDir = await NodeFSP.realpath(directory);
14 const lockPath = NodePath.join(stateDir, "server-owner.sqlite");
15 let db: { exec: (sql: string) => unknown; close: () => void };
16 if (process.versions.bun) {
17 // Keep Bun's runtime-only module out of the Node build's module resolver.
18 const moduleName = "bun:sqlite";
19 const sqlite: { Database: new (filename: string) => typeof db } = await import(moduleName);
20 db = new sqlite.Database(lockPath);
21 } else {
22 db = new (await import("node:sqlite")).DatabaseSync(lockPath);
23 }
24 try {
25 db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;");
26 if (options?.guardLegacyOwner) {
27 let runtimeState: unknown;
28 try {
29 runtimeState = JSON.parse(
30 await NodeFSP.readFile(NodePath.join(stateDir, "server-runtime.json"), "utf8"),
31 );
32 } catch (cause) {
33 if (!(cause instanceof Error && "code" in cause && cause.code === "ENOENT")) throw cause;
34 }
35 if (runtimeState !== undefined) {
36 // Unknown descriptors and live legacy PIDs must fail closed before a
37 // launcher copies data. PID reuse can cause a conservative refusal;
38 // no process is ever stopped based on this record.
39 if (
40 typeof runtimeState !== "object" ||
41 runtimeState === null ||
42 !("version" in runtimeState) ||
43 runtimeState.version !== 1 ||
44 !("pid" in runtimeState) ||
45 typeof runtimeState.pid !== "number" ||
46 !Number.isInteger(runtimeState.pid) ||
47 ("ownerId" in runtimeState && typeof runtimeState.ownerId !== "string")
48 ) {
49 throw new Error(`Cannot inspect server ownership at ${stateDir}.`);
50 }
51 if (!("ownerId" in runtimeState) && runtimeState.pid > 0) {
52 let alive = true;
53 try {
54 process.kill(runtimeState.pid, 0);
55 } catch (cause) {
56 if (cause instanceof Error && "code" in cause && cause.code === "ESRCH") {
57 alive = false;
58 } else if (!(cause instanceof Error && "code" in cause && cause.code === "EPERM")) {
59 throw cause;
60 }
61 }
62 if (alive) {
63 throw Object.assign(
64 new Error(`A legacy server may still own ${stateDir}. Stop it before updating.`),
65 { code: "T3_STATE_DIR_OWNED" },
66 );
67 }
68 }
69 }
70 }
71 } catch (cause) {
72 db.close();
73 throw cause;
74 }
75 return { stateDir, close: () => db.close() };