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

serverSingleton.ts

339 lines11.8 KB

1/**
2 * One server per data directory.
3 *
4 * The server already relies on SQLite for cross-platform filesystem locking.
5 * A dedicated lock database holds one write transaction for the process
6 * lifetime: a crash releases the OS lock automatically, while another process
7 * receives SQLITE_BUSY before it can open T3's real persistence or bind HTTP.
8 *
9 * `server.lock` is display-only metadata for the refusal message. It never
10 * decides ownership; deleting it cannot release the SQLite lock.
11 *
12 * A pre-lock server has no lock database, so the first upgraded process also
13 * checks `server-runtime.json` and refuses while that recorded pid is live.
14 * That compatibility check starts only after the old binary publishes its
15 * runtime state; an unmodified old binary cannot participate in a lock that
16 * did not exist when it shipped.
17 */
18import * as Data from "effect/Data";
19import * as Crypto from "effect/Crypto";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as FileSystem from "effect/FileSystem";
23import * as Option from "effect/Option";
24import * as Path from "effect/Path";
25import * as Schema from "effect/Schema";
26​
27import { writeFileStringAtomically } from "./atomicWrite.ts";
28import { readPersistedServerRuntimeState } from "./serverRuntimeState.ts";
29​
30export const SERVER_LOCK_FILENAME = "server.lock";
31export const SERVER_LOCK_DATABASE_FILENAME = "server-lock.sqlite";
32export const SERVER_RUNTIME_STATE_FILENAME = "server-runtime.json";
33​
34export const ServerLockHolder = Schema.Struct({
35 version: Schema.Literal(1),
36 ownerId: Schema.String,
37 pid: Schema.Int,
38 startedAt: Schema.String,
39 /** Absent until the server binds; ownership is already held in SQLite. */
40 port: Schema.optional(Schema.Int),
41});
42export type ServerLockHolder = typeof ServerLockHolder.Type;
43​
44const ServerLockHolderFromJson = Schema.fromJsonString(ServerLockHolder);
45const decodeHolder = Schema.decodeUnknownOption(ServerLockHolderFromJson);
46const encodeHolder = Schema.encodeSync(ServerLockHolderFromJson);
47​
48export class ServerAlreadyRunningError extends Schema.TaggedErrorClass<ServerAlreadyRunningError>()(
49 "ServerAlreadyRunningError",
50 {
51 stateDir: Schema.String,
52 lockPath: Schema.String,
53 holderPid: Schema.optional(Schema.Int),
54 holderPort: Schema.optional(Schema.Int),
55 holderStartedAt: Schema.optional(Schema.String),
56 legacyRuntimeStatePath: Schema.optional(Schema.String),
57 },
58) {
59 override get message(): string {
60 const holder =
61 this.holderPid === undefined
62 ? "another live T3 Code server"
63 : this.holderPort === undefined
64 ? `pid ${this.holderPid}`
65 : `pid ${this.holderPid}, listening on port ${this.holderPort}`;
66 const common = [
67 "Another T3 Code server is already using this data directory.",
68 "",
69 ` data directory: ${this.stateDir}`,
70 ` held by: ${holder}`,
71 ...(this.holderStartedAt === undefined ? [] : [` since: ${this.holderStartedAt}`]),
72 "",
73 "Two servers sharing one data directory overwrite each other's state.sqlite",
74 "and settings.json. Connect to the running server, stop it cleanly, or use",
75 "a different --base-dir.",
76 ];
77 if (this.legacyRuntimeStatePath !== undefined) {
78 return [
79 ...common,
80 "",
81 `${this.legacyRuntimeStatePath} is the compatibility guard for this older`,
82 "server. Do not remove it while the recorded process is live.",
83 ].join("\n");
84 }
85 return [
86 ...common,
87 "",
88 `Ownership is released automatically when the process exits. ${this.lockPath}`,
89 "contains display metadata only; removing it does not release a live owner.",
90 ].join("\n");
91 }
93​
94export class ServerLockUnavailableError extends Schema.TaggedErrorClass<ServerLockUnavailableError>()(
95 "ServerLockUnavailableError",
96 {
97 lockPath: Schema.String,
98 operation: Schema.String,
99 cause: Schema.Defect(),
100 },
101) {
102 override get message(): string {
103 return `Could not ${this.operation} the server ownership database at ${this.lockPath}.`;
104 }
106​
107export const processIsAliveWith = (pid: number, sendSignal: (pid: number) => void): boolean => {
108 if (!Number.isInteger(pid) || pid <= 0) return false;
109 try {
110 sendSignal(pid);
111 return true;
112 } catch (cause) {
113 return (cause as NodeJS.ErrnoException).code === "EPERM";
114 }
115};
116​
117export const processIsAlive = (pid: number): boolean =>
118 processIsAliveWith(pid, (targetPid) => process.kill(targetPid, 0));
119​
120interface LockDatabase {
121 readonly exec: (sql: string) => void;
122 readonly close: () => void;
124​
125interface HeldServerLock {
126 readonly database: LockDatabase;
127 readonly lockPath: string;
128 readonly ownerId: string;
130​
131class ServerLockAttemptError extends Data.TaggedError("ServerLockAttemptError")<{
132 readonly cause: unknown;
133}> {}
134​
135const readHolder = Effect.fn("serverSingleton.readHolder")(function* (lockPath: string) {
136 const fs = yield* FileSystem.FileSystem;
137 const raw = yield* fs
138 .readFileString(lockPath)
139 .pipe(
140 Effect.catch((error) =>
141 error.reason._tag === "NotFound" ? Effect.succeed("") : Effect.fail(error),
142 ),
143 );
144 return Option.getOrUndefined(decodeHolder(raw));
145});
146​
147const closeDatabase = (database: LockDatabase) =>
148 Effect.sync(() => {
149 try {
150 database.exec("ROLLBACK");
151 } catch {
152 // A failed BEGIN has no transaction to roll back.
153 }
154 database.close();
155 }).pipe(Effect.ignore);
156​
157const openLockDatabase = Effect.fn("serverSingleton.openDatabase")(function* (lockPath: string) {
158 if (process.versions.bun !== undefined) {
159 const { Database } = yield* Effect.promise(() => import("bun:sqlite"));
160 return yield* Effect.try({
161 try: () => {
162 const database = new Database(lockPath, { create: true });
163 return {
164 exec: (sql: string) => database.exec(sql),
165 close: () => database.close(),
166 } satisfies LockDatabase;
167 },
168 catch: (cause) => new ServerLockUnavailableError({ lockPath, operation: "open", cause }),
169 });
170 }
171​
172 const { DatabaseSync } = yield* Effect.promise(() => import("node:sqlite"));
173 return yield* Effect.try({
174 try: () => {
175 const database = new DatabaseSync(lockPath);
176 return {
177 exec: (sql: string) => database.exec(sql),
178 close: () => database.close(),
179 } satisfies LockDatabase;
180 },
181 catch: (cause) => new ServerLockUnavailableError({ lockPath, operation: "open", cause }),
182 });
183});
184​
185export const isServerLockBusyError = (cause: unknown): boolean => {
186 const code =
187 cause instanceof Error && "code" in cause ? String((cause as NodeJS.ErrnoException).code) : "";
188 const errno =
189 cause instanceof Error && "errno" in cause
190 ? Number((cause as NodeJS.ErrnoException).errno)
191 : undefined;
192 const message = cause instanceof Error ? cause.message : String(cause);
193 return (
194 code === "SQLITE_BUSY" ||
195 code === "SQLITE_BUSY_SNAPSHOT" ||
196 errno === 5 ||
197 /database is (?:locked|busy)/i.test(message)
198 );
199};
200​
201/** A pre-lock server is live against this directory. */
202export class LiveLegacyServerRuntime extends Data.TaggedError("LiveLegacyServerRuntime")<{
203 readonly state: {
204 readonly pid: number;
205 readonly port: number;
206 readonly startedAt: string;
207 };
208}> {}
209​
210const beginExclusiveWrite = Effect.fn("serverSingleton.beginExclusiveWrite")(function* (
211 database: LockDatabase,
212 lockPath: string,
213) {
214 const result = yield* Effect.try({
215 try: () => {
216 database.exec("PRAGMA busy_timeout = 0");
217 database.exec("BEGIN IMMEDIATE");
218 },
219 catch: (cause) => new ServerLockAttemptError({ cause }),
220 }).pipe(
221 Effect.as({ ok: true as const }),
222 Effect.catch((error) => Effect.succeed({ ok: false as const, cause: error.cause })),
223 );
224 if (result.ok) return true;
225 if (isServerLockBusyError(result.cause)) return false;
226 return yield* new ServerLockUnavailableError({
227 lockPath,
228 operation: "lock",
229 cause: result.cause,
230 });
231});
232​
233export const serverLockPath = Effect.fn("serverSingleton.lockPath")(function* (stateDir: string) {
234 const path = yield* Path.Path;
235 return path.join(stateDir, SERVER_LOCK_FILENAME);
236});
237​
238export const serverLockDatabasePath = Effect.fn("serverSingleton.databasePath")(function* (
239 stateDir: string,
240) {
241 const path = yield* Path.Path;
242 return path.join(stateDir, SERVER_LOCK_DATABASE_FILENAME);
243});
244​
245export const legacyServerRuntimeStatePath = Effect.fn("serverSingleton.legacyStatePath")(function* (
246 stateDir: string,
247) {
248 const path = yield* Path.Path;
249 return path.join(stateDir, SERVER_RUNTIME_STATE_FILENAME);
250});
251​
252const acquireLock = Effect.fn("serverSingleton.acquireLock")(function* (stateDir: string) {
253 const fs = yield* FileSystem.FileSystem;
254 const path = yield* Path.Path;
255 const crypto = yield* Crypto.Crypto;
256 const lockPath = yield* serverLockPath(stateDir);
257 const databasePath = yield* serverLockDatabasePath(stateDir);
258 const legacyRuntimeStatePath = yield* legacyServerRuntimeStatePath(stateDir);
259​
260 const legacyState = yield* readPersistedServerRuntimeState(legacyRuntimeStatePath);
261 if (Option.isSome(legacyState) && processIsAlive(legacyState.value.pid)) {
262 return yield* new LiveLegacyServerRuntime({ state: legacyState.value });
263 }
264​
265 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
266 const database = yield* openLockDatabase(databasePath);
267 return yield* Effect.gen(function* () {
268 if (!(yield* beginExclusiveWrite(database, databasePath))) {
269 const holder = yield* readHolder(lockPath);
270 return yield* new ServerAlreadyRunningError({
271 stateDir,
272 lockPath,
273 ...(holder === undefined
274 ? {}
275 : {
276 holderPid: holder.pid,
277 holderStartedAt: holder.startedAt,
278 ...(holder.port === undefined ? {} : { holderPort: holder.port }),
279 }),
280 });
281 }
282​
283 const ownerId = yield* crypto.randomUUIDv4;
284 const startedAt = DateTime.formatIso(yield* DateTime.now);
285 yield* writeFileStringAtomically({
286 filePath: lockPath,
287 contents: encodeHolder({ version: 1, ownerId, pid: process.pid, startedAt }),
288 });
289 return { database, lockPath, ownerId } satisfies HeldServerLock;
290 }).pipe(Effect.onError(() => closeDatabase(database)));
291});
292​
293const releaseLock = Effect.fn("serverSingleton.releaseLock")(function* (held: HeldServerLock) {
294 const fs = yield* FileSystem.FileSystem;
295 const holder = yield* readHolder(held.lockPath).pipe(Effect.orElseSucceed(() => undefined));
296 if (holder?.ownerId === held.ownerId) {
297 // Remove metadata while the SQLite transaction still excludes successors.
298 yield* fs.remove(held.lockPath, { force: true }).pipe(Effect.ignore);
299 }
300 yield* closeDatabase(held.database);
301});
302​
303/** Records the bound port in display metadata while SQLite owns the lock. */
304export const recordServerLockPort = Effect.fn("serverSingleton.recordPort")(function* (
305 lockPath: string,
306 port: number,
307) {
308 const holder = yield* readHolder(lockPath);
309 if (holder === undefined || holder.pid !== process.pid) return;
310 yield* writeFileStringAtomically({
311 filePath: lockPath,
312 contents: encodeHolder({ ...holder, port }),
313 }).pipe(Effect.ignore);
314});
315​
316/** Holds the state directory until the caller's scope closes. */
317export const acquireServerSingleton = Effect.fn("serverSingleton.acquire")(function* (
318 stateDir: string,
319) {
320 const legacyRuntimeStatePath = yield* legacyServerRuntimeStatePath(stateDir);
321 return yield* Effect.acquireRelease(
322 acquireLock(stateDir).pipe(
323 Effect.catchTags({
324 LiveLegacyServerRuntime: (legacy) =>
325 Effect.fail(
326 new ServerAlreadyRunningError({
327 stateDir,
328 lockPath: legacyRuntimeStatePath,
329 holderPid: legacy.state.pid,
330 holderPort: legacy.state.port,
331 holderStartedAt: legacy.state.startedAt,
332 legacyRuntimeStatePath,
333 }),
334 ),
335 }),
336 ),
337 releaseLock,
338 ).pipe(Effect.map((held) => held.lockPath));
339});