Open History to see the last commit
1/**
2 * One server per data directory.
3 *
4 * Two T3 Code servers pointed at the same `--base-dir` both open `state.sqlite`
5 * and both write `settings.json`, and they overwrite each other. The observed
6 * incident: a desktop app auto-updated to a newer server while the old one was
7 * still running, the new process found its port taken, silently bound a random
8 * one, and ran blind against shared state. The visible symptom was a settings
9 * toggle that would not stick — hours away from the actual cause.
10 *
11 * Nothing about that is detectable after the fact, so the fix is to refuse at
12 * startup. A second server against a held directory exits with one clear
13 * message instead of corrupting state.
14 *
15 * ## Why a pid file rather than `flock`
16 *
17 * An advisory `flock` is the better primitive: the kernel drops it when the
18 * holder dies, so a crashed server leaves nothing stale to clean up. Node has no
19 * binding for it, and adding a native dependency to the server for one lock is a
20 * worse trade than handling staleness here.
21 *
22 * So the lock is an atomically created file holding the owner's identity, and
23 * liveness is checked with signal 0. The tradeoff is honest: if a server is
24 * killed and its pid is later reused by an unrelated process, this refuses to
25 * start until the file is removed. That is the safe direction to fail, and the
26 * message names the file so recovery is one `rm`.
27 *
28 * ## Upgrading from a pre-lock version
29 *
30 * A pre-lock server writes no `server.lock`, so the file alone cannot see one.
31 * It does persist `server-runtime.json` with its live pid though, so before
32 * claiming the directory a live legacy runtime state is read as a held lock
33 * and refused the same way. Otherwise the desktop auto-update incident this
34 * exists to prevent still happens once on upgrade day — the new server starts
35 * next to the old one against the same state.
36 */
37import * as Data from "effect/Data";
38import * as DateTime from "effect/DateTime";
39import * as Effect from "effect/Effect";
40import * as FileSystem from "effect/FileSystem";
41import * as Option from "effect/Option";
42import * as Path from "effect/Path";
43import * as PlatformError from "effect/PlatformError";
44import * as Schedule from "effect/Schedule";
45import * as Schema from "effect/Schema";
46
47import { writeFileStringAtomically } from "./atomicWrite.ts";
48import { readPersistedServerRuntimeState } from "./serverRuntimeState.ts";
49
50export const SERVER_LOCK_FILENAME = "server.lock";
51export const SERVER_RUNTIME_STATE_FILENAME = "server-runtime.json";
52
53export const ServerLockHolder = Schema.Struct({
54 version: Schema.Literal(1),
55 pid: Schema.Int,
56 startedAt: Schema.String,
57 /** Absent until the server binds; the lock is taken before a port exists. */
58 port: Schema.optional(Schema.Int),
59});
60export type ServerLockHolder = typeof ServerLockHolder.Type;
61
62const ServerLockHolderFromJson = Schema.fromJsonString(ServerLockHolder);
63const decodeHolder = Schema.decodeUnknownOption(ServerLockHolderFromJson);
64const encodeHolder = Schema.encodeSync(ServerLockHolderFromJson);
65
66export class ServerAlreadyRunningError extends Schema.TaggedError<ServerAlreadyRunningError>()(
67 "ServerAlreadyRunningError",
68 {
69 stateDir: Schema.String,
70 lockPath: Schema.String,
71 holderPid: Schema.Int,
72 holderPort: Schema.optional(Schema.Int),
73 holderStartedAt: Schema.String,
74 },
75) {
76 override get message(): string {
77 const where =
78 this.holderPort === undefined
79 ? `pid ${this.holderPid}`
80 : `pid ${this.holderPid}, listening on port ${this.holderPort}`;
81 return [
82 "Another T3 Code server is already using this data directory.",
83 "",
84 ` data directory: ${this.stateDir}`,
85 ` held by: ${where}`,
86 ` since: ${this.holderStartedAt}`,
87 "",
88 "Two servers sharing one data directory overwrite each other's state.sqlite",
89 "and settings.json. Stop the running server, or start this one with a",
90 "different --base-dir.",
91 "",
92 `If that process is gone, remove ${this.lockPath} and start again.`,
93 ].join("\n");
94 }
95}
96
97export class ServerLockUnavailableError extends Schema.TaggedError<ServerLockUnavailableError>()(
98 "ServerLockUnavailableError",
99 {
100 lockPath: Schema.String,
101 attempts: Schema.Int,
102 cause: Schema.optional(Schema.Defect()),
103 },
104) {
105 override get message(): string {
106 return `Could not claim the server lock at ${this.lockPath} after ${this.attempts} attempts; another starting server kept reclaiming it.`;
107 }
108}
109
110// How many reclaim-and-retry rounds against a confirmed-dead lock a starter
111// tolerates before concluding something else keeps recreating it: nothing a
112// real dead holder produces, everything a permission wall or a competing
113// starter produces.
114const MAX_RECLAIM_CYCLES = 3;
115
116/**
117 * Whether a pid is a live process.
118 *
119 * `EPERM` means it exists and belongs to someone else, which still counts — a
120 * server started under a different user is exactly the case that must not be
121 * trampled.
122 */
123export const processIsAlive = (pid: number): boolean => {
124 if (!Number.isInteger(pid) || pid <= 0) return false;
125 try {
126 process.kill(pid, 0);
127 return true;
128 } catch (cause) {
129 return (cause as NodeJS.ErrnoException).code === "EPERM";
130 }
131};
132
133const readHolder = Effect.fn("serverSingleton.readHolder")(function* (lockPath: string) {
134 const fs = yield* FileSystem.FileSystem;
135 const raw = yield* fs
136 .readFileString(lockPath)
137 .pipe(
138 Effect.catch((error) =>
139 error.reason._tag === "NotFound" ? Effect.succeed("") : Effect.fail(error),
140 ),
141 );
142 return Option.getOrUndefined(decodeHolder(raw));
143});
144
145// A dead holder's lock is not unlinked outright: between one starter reading a
146// stale lock and another recreating it, an unconditional unlink would remove a
147// live successor's claim. Reclamation instead refreshes the file's mtime
148// `MAX_CLAIM_ATTEMPTS` times; only a file that stays the same dead content
149// across every attempt is removed, so a live recreation always survives. The
150// holder bumps the mtime once between attempts while it owns the lock, so no
151// sequence of slower starters can reclaim out from under it either — and a
152// dead holder still recycles its lock inside a second of startup time.
153const MAX_CLAIM_ATTEMPTS = 3;
154const RECLAIM_OBSERVATION_DELAY_MILLIS = 200;
155
156const isAlreadyExists = (error: PlatformError.PlatformError): boolean =>
157 error.reason._tag === "AlreadyExists";
158
159const isNotFound = (error: PlatformError.PlatformError): boolean => error.reason._tag === "NotFound";
160
161const reclaimGatePath = (lockPath: string): string => `${lockPath}.reclaim`;
162
163/**
164 * Serialize stale-lock takeover. Two reclaimers can both finish the last
165 * stale read, then both `remove` — the second deletes the first's fresh
166 * claim. An exclusive gate file makes exactly one reclaimer allowed to
167 * touch `server.lock`; everyone else backs off and retries the create.
168 */
169const takeReclaimGate = Effect.fn("serverSingleton.takeReclaimGate")(function* (lockPath: string) {
170 const fs = yield* FileSystem.FileSystem;
171 const gatePath = reclaimGatePath(lockPath);
172 const existing = yield* fs.readFileString(gatePath).pipe(
173 Effect.catch((error) => (isNotFound(error) ? Effect.succeed(undefined) : Effect.fail(error))),
174 );
175 if (existing !== undefined) {
176 const gatePid = Number.parseInt(existing.trim(), 10);
177 if (processIsAlive(gatePid)) return false;
178 // Rename, do not unlink-by-name: two reclaimers that both saw a dead
179 // gate used to `remove` then `wx`, and the second deleted the first's
180 // fresh gate. Only one rename of the dead inode can succeed.
181 const deadPath = `${gatePath}.dead.${process.pid}`;
182 const renamed = yield* fs.rename(gatePath, deadPath).pipe(
183 Effect.as(true),
184 Effect.catch((error) => (isNotFound(error) ? Effect.succeed(false) : Effect.fail(error))),
185 );
186 if (renamed) {
187 yield* fs.remove(deadPath, { force: true }).pipe(Effect.ignore);
188 } else {
189 return false;
190 }
191 }
192 return yield* fs.writeFileString(gatePath, `${process.pid}\n`, { flag: "wx" }).pipe(
193 Effect.as(true),
194 Effect.catch((error) => (isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error))),
195 );
196});
197
198const lockIsOlderThanGrace = Effect.fn("serverSingleton.lockIsOlderThanGrace")(function* (
199 lockPath: string,
200) {
201 const fs = yield* FileSystem.FileSystem;
202 const info = yield* fs.stat(lockPath).pipe(
203 Effect.catch((error) => (isNotFound(error) ? Effect.succeed(undefined) : Effect.fail(error))),
204 );
205 if (info === undefined) return false;
206 const mtime = Option.getOrUndefined(info.mtime);
207 if (mtime === undefined) return false;
208 const now = yield* DateTime.now;
209 return DateTime.toEpochMillis(now) - mtime.getTime() >= RECLAIM_OBSERVATION_DELAY_MILLIS;
210});
211
212/**
213 * A pre-lock server is live against this directory. Failure-phase marker rather
214 * than an error: `serverRuntimeState.ts` already owns the file's decode-error
215 * type, and the refusal shown to the user is the same `ServerAlreadyRunningError`
216 * either way — `server.ts` converts this at the boundary where the config with
217 * the path lives.
218 */
219export class LiveLegacyServerRuntime extends Data.TaggedError("LiveLegacyServerRuntime")<{
220 readonly state: {
221 readonly pid: number;
222 readonly port: number;
223 readonly startedAt: string;
224 };
225}> {}
226
227/**
228 * Claims the directory, or explains who holds it.
229 *
230 * A lock file whose owner is gone is reclaimed rather than treated as a
231 * permanent block: a dead holder must not lock its own directory forever.
232 * Reclaiming re-races the exclusive create, so two servers starting together
233 * still produce exactly one winner.
234 */
235const claimLock = Effect.fn("serverSingleton.claimLock")(function* (input: {
236 readonly stateDir: string;
237 readonly lockPath: string;
238 readonly legacyRuntimeStatePath: string;
239 readonly startedAt: string;
240}) {
241 const fs = yield* FileSystem.FileSystem;
242 const path = yield* Path.Path;
243 const payload = encodeHolder({ version: 1, pid: process.pid, startedAt: input.startedAt });
244
245 // A pre-lock server writes no lock, so the file alone is blind to one — but
246 // it does persist its live pid in `server-runtime.json`. Refuse a live
247 // legacy runtime exactly like a live lock holder, before the lock is ever
248 // created; otherwise the upgrade that introduces this guard still starts
249 // next to the very server it is meant to replace. A dead legacy pid is
250 // ignored here: reclaim of its leftover lock is what removes the file.
251 const legacyState = yield* readPersistedServerRuntimeState(input.legacyRuntimeStatePath);
252 if (Option.isSome(legacyState) && processIsAlive(legacyState.value.pid)) {
253 return yield* new LiveLegacyServerRuntime({ state: legacyState.value });
254 }
255
256 yield* fs.makeDirectory(path.dirname(input.lockPath), { recursive: true });
257
258 // Counts how often this starter was forced to refresh a candidate stale lock
259 // before believing it is really dead, and how often a confirmed-dead lock
260 // bounced it back to another round (see the constants above).
261 let reclaimRefreshes = 0;
262 let reclaimCycles = 0;
263 while (true) {
264 // A scheduler yield between attempts, so a reclaim observation round lets
265 // other starters (and the holder's heartbeat) run before this starter
266 // concludes a lock never changed. Real time only — resolvable under
267 // `TestClock`.
268 yield* Effect.yieldNow;
269 const created = yield* fs.writeFileString(input.lockPath, payload, { flag: "wx" }).pipe(
270 Effect.as(true),
271 Effect.catch((error) =>
272 isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
273 ),
274 );
275 if (created) return undefined;
276
277 const holder = yield* readHolder(input.lockPath);
278 if (holder !== undefined && processIsAlive(holder.pid)) {
279 return new ServerAlreadyRunningError({
280 stateDir: input.stateDir,
281 lockPath: input.lockPath,
282 holderPid: holder.pid,
283 ...(holder.port === undefined ? {} : { holderPort: holder.port }),
284 holderStartedAt: holder.startedAt,
285 });
286 }
287
288 // The read found no live owner — either a decodeable dead holder, or
289 // `undefined` because the file is missing (another starter mid-reclaim)
290 // or undecodable (a crash tore a write in half). Never unlink after one
291 // read: between this starter's read and its remove, a successor can win
292 // the re-race and recreate its own live lock, and the unlink would delete
293 // that. The candidate is mtime-refreshed and re-observed across
294 // `MAX_CLAIM_ATTEMPTS` rounds, and only a file that stayed untouched
295 // through every round is removed — a live successor's heartbeat always
296 // refreshes inside one round, so the file a reclaimer finally removes is
297 // provably still dead. The wait lands in the *next* loop head's
298 // `Effect.yieldNow`, which keeps `claimLock` real-time-only so tests can
299 // drive it without a fake clock.
300 if (reclaimRefreshes >= MAX_CLAIM_ATTEMPTS) {
301 // Removing frees the directory, and the create is retried on the next
302 // pass: a cleanly restarted server after a crash claims its directory
303 // here, not on a later manual retry. Bounded, so a lock another starter
304 // keeps recreating (or a permissions wall keeps failing to remove for)
305 // still surfaces as itself.
306 const wonGate = yield* takeReclaimGate(input.lockPath);
307 if (!wonGate) {
308 reclaimRefreshes = 0;
309 reclaimCycles += 1;
310 if (reclaimCycles >= MAX_RECLAIM_CYCLES) {
311 return new ServerLockUnavailableError({
312 lockPath: input.lockPath,
313 attempts: reclaimCycles,
314 });
315 }
316 continue;
317 }
318 const gatePath = reclaimGatePath(input.lockPath);
319 const takeover = yield* Effect.gen(function* () {
320 const existsAfterGate = yield* fs.exists(input.lockPath);
321 if (!existsAfterGate) {
322 const created = yield* fs.writeFileString(input.lockPath, payload, { flag: "wx" }).pipe(
323 Effect.as(true),
324 Effect.catch((error) =>
325 isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
326 ),
327 );
328 return created ? undefined : "retry";
329 }
330 const holderAfterGate = yield* readHolder(input.lockPath);
331 if (holderAfterGate !== undefined && processIsAlive(holderAfterGate.pid)) {
332 return new ServerAlreadyRunningError({
333 stateDir: input.stateDir,
334 lockPath: input.lockPath,
335 holderPid: holderAfterGate.pid,
336 ...(holderAfterGate.port === undefined ? {} : { holderPort: holderAfterGate.port }),
337 holderStartedAt: holderAfterGate.startedAt,
338 });
339 }
340 // An empty or half-written lock may be a creator still inside
341 // writeFileString. Observation rounds are scheduler yields, not
342 // elapsed time, so require a real mtime grace and re-check it
343 // immediately before unlink.
344 if (holderAfterGate === undefined && !(yield* lockIsOlderThanGrace(input.lockPath))) {
345 return "retry";
346 }
347 yield* fs.remove(input.lockPath, { force: true });
348 const created = yield* fs.writeFileString(input.lockPath, payload, { flag: "wx" }).pipe(
349 Effect.as(true),
350 Effect.catch((error) =>
351 isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
352 ),
353 );
354 return created ? undefined : "retry";
355 }).pipe(
356 Effect.ensuring(fs.remove(gatePath, { force: true }).pipe(Effect.ignore)),
357 );
358 if (takeover === "retry") {
359 reclaimRefreshes = 0;
360 reclaimCycles += 1;
361 if (reclaimCycles >= MAX_RECLAIM_CYCLES) {
362 return new ServerLockUnavailableError({
363 lockPath: input.lockPath,
364 attempts: reclaimCycles,
365 });
366 }
367 continue;
368 }
369 return takeover;
370 }
371
372 reclaimRefreshes += 1;
373 // Do not refresh an undecodable lock: that file may still be mid-write,
374 // and bumping its mtime would hide the grace period below.
375 if (holder === undefined) {
376 continue;
377 }
378 const now = yield* DateTime.now;
379 // NotFound-tolerant: a shutdown mid-release can drop the file between our
380 // read and our refresh, and the starter that released it is nobody's live
381 // claim either way. The next pass's create or re-read settles it.
382 yield* fs
383 .utimes(input.lockPath, DateTime.toDateUtc(now), DateTime.toDateUtc(now))
384 .pipe(
385 Effect.catch((error) =>
386 error.reason._tag === "NotFound" ? Effect.void : Effect.fail(error),
387 ),
388 );
389 }
390});
391
392/**
393 * A live lock holder refreshes its claim's mtime once per reclaim-observation
394 * round while it owns the lock. Any starter mid-reclaim then sees the file
395 * change and backs off, so the holder's lock cannot be reclaimed from under it
396 * no matter how many starters race. Stops with the scope that holds the lock.
397 */
398const holdServerLock = Effect.fn("serverSingleton.hold")(function* (lockPath: string) {
399 const fs = yield* FileSystem.FileSystem;
400 const tick = Effect.gen(function* () {
401 const holder = yield* readHolder(lockPath);
402 if (holder === undefined || holder.pid !== process.pid) return;
403 const now = yield* DateTime.now;
404 const date = DateTime.toDateUtc(now);
405 yield* fs.utimes(lockPath, date, date);
406 });
407 const reschedule = Schedule.spaced(RECLAIM_OBSERVATION_DELAY_MILLIS);
408 yield* Effect.forkScoped(
409 tick.pipe(
410 // Each tick is caught individually: `Effect.repeat` ends a failing
411 // effect on the first failure, so recovery has to live inside the round.
412 // The holder keeps refreshing for as long as it owns the lock, through
413 // whatever transient filesystem errors come and go.
414 Effect.catch(() => Effect.void),
415 Effect.repeat({ schedule: reschedule, while: () => true }),
416 Effect.catch(() => Effect.void),
417 ),
418 );
419});
420
421/**
422 * Releases only a lock this process verifiably owns, so a successor is never
423 * evicted. An undecodable file is left alone: it is either a live re-entrant
424 * claim (the winning starter's just-created file, or another process's) or a
425 * crash fragment, and crash fragments are what reclaim exists for.
426 */
427export const releaseServerLock = Effect.fn("serverSingleton.release")(function* (lockPath: string) {
428 const fs = yield* FileSystem.FileSystem;
429 const holder = yield* readHolder(lockPath);
430 if (holder === undefined || holder.pid !== process.pid) return;
431 yield* fs.remove(lockPath, { force: true }).pipe(Effect.ignore);
432});
433
434/**
435 * Records the bound port on the lock we already hold.
436 *
437 * The rewrite goes through write-temp-then-rename so a reader never observes
438 * an empty or partial file: with an in-place rewrite, a concurrent starter
439 * could mistake the truncated file for a crashed owner and reclaim a live
440 * lock — the exact concurrent-servers corruption the lock exists to prevent.
441 *
442 * Only for the error message a *later* server prints: knowing the holder's port
443 * turns "something else is running" into an address the user can open. Failure
444 * is ignored — the lock's job is done once it is held.
445 */
446export const recordServerLockPort = Effect.fn("serverSingleton.recordPort")(function* (
447 lockPath: string,
448 port: number,
449) {
450 const holder = yield* readHolder(lockPath);
451 if (holder === undefined || holder.pid !== process.pid) return;
452 yield* writeFileStringAtomically({
453 filePath: lockPath,
454 contents: encodeHolder({ ...holder, port }),
455 }).pipe(Effect.ignore);
456});
457
458export const serverLockPath = Effect.fn("serverSingleton.lockPath")(function* (stateDir: string) {
459 const path = yield* Path.Path;
460 return path.join(stateDir, SERVER_LOCK_FILENAME);
461});
462
463export const legacyServerRuntimeStatePath = Effect.fn("serverSingleton.legacyStatePath")(function* (
464 stateDir: string,
465) {
466 const path = yield* Path.Path;
467 return path.join(stateDir, SERVER_RUNTIME_STATE_FILENAME);
468});
469
470/**
471 * Holds the data directory for the lifetime of the returned scope.
472 *
473 * Acquired before anything opens the database or binds a port, and released on
474 * shutdown. A live pre-lock server reads as a held lock here too: callers see
475 * one refusal type regardless of which generation holds the directory.
476 */
477export const acquireServerSingleton = Effect.fn("serverSingleton.acquire")(function* (
478 stateDir: string,
479) {
480 const lockPath = yield* serverLockPath(stateDir);
481 const legacyRuntimeStatePath = yield* legacyServerRuntimeStatePath(stateDir);
482 const startedAt = DateTime.formatIso(yield* DateTime.now);
483 return yield* Effect.acquireRelease(
484 Effect.gen(function* () {
485 const failure = yield* claimLock({
486 stateDir,
487 lockPath,
488 legacyRuntimeStatePath,
489 startedAt,
490 }).pipe(
491 // The message names `server-runtime.json` (not `server.lock`) as the
492 // file to remove if the process is gone — that is all a pre-lock
493 // server ever wrote.
494 Effect.catchTags({
495 LiveLegacyServerRuntime: (legacy) =>
496 Effect.fail(
497 new ServerAlreadyRunningError({
498 stateDir,
499 lockPath: legacyRuntimeStatePath,
500 holderPid: legacy.state.pid,
501 holderPort: legacy.state.port,
502 holderStartedAt: legacy.state.startedAt,
503 }),
504 ),
505 }),
506 );
507 if (failure !== undefined) return yield* failure;
508 yield* holdServerLock(lockPath);
509 return lockPath;
510 }),
511 () => releaseServerLock(lockPath).pipe(Effect.ignore),
512 );
513});