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

serverSingleton.test.ts

431 lines17.4 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as DateTime from "effect/DateTime";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as Schedule from "effect/Schedule";
10import * as Schema from "effect/Schema";
11​
12import { PersistedServerRuntimeState } from "./serverRuntimeState.ts";
13import {
14 SERVER_LOCK_FILENAME,
15 SERVER_RUNTIME_STATE_FILENAME,
16 acquireServerSingleton,
17 processIsAlive,
18 recordServerLockPort,
19 releaseServerLock,
20 serverLockPath,
21} from "./serverSingleton.ts";
22​
23const layer = it.layer(NodeServices.layer);
24​
25const makeStateDir = Effect.fn("test.makeStateDir")(function* () {
26 const fs = yield* FileSystem.FileSystem;
27 return yield* fs.makeTempDirectory({ prefix: "t3-singleton-" });
28});
29​
30/** A stale lock file, written without the module's own encoder on purpose. */
31const staleHolder = (pid: number) =>
32 `{"version":1,"pid":${pid},"startedAt":"2026-01-01T00:00:00.000Z"}`;
33​
34const PersistedServerRuntimeStateFromJson = Schema.fromJsonString(PersistedServerRuntimeState);
35const encodeRuntimeState = Schema.encodeSync(PersistedServerRuntimeStateFromJson);
36​
37/** What a pre-lock server persists: its live pid and port, and no lock file. */
38const legacyRuntimeState = (pid: number, port: number) =>
39 `${encodeRuntimeState({
40 version: 1,
41 pid,
42 port,
43 origin: `http://127.0.0.1:${port}`,
44 startedAt: "2026-08-27T12:00:00.000Z",
45 })}\n`;
46​
47layer("serverSingleton", (it) => {
48 it.effect("claims a free directory and releases it on scope exit", () =>
49 Effect.gen(function* () {
50 const stateDir = yield* makeStateDir();
51 const fs = yield* FileSystem.FileSystem;
52 const lockPath = yield* serverLockPath(stateDir);
53​
54 yield* Effect.scoped(
55 Effect.gen(function* () {
56 yield* acquireServerSingleton(stateDir);
57 assert.isTrue(yield* fs.exists(lockPath));
58 }),
59 );
60 // Released on scope exit, so a restart is not blocked by its predecessor.
61 assert.isFalse(yield* fs.exists(lockPath));
62 }),
63 );
64​
65 it.effect("refuses a second server while the first holds the directory", () =>
66 Effect.gen(function* () {
67 const stateDir = yield* makeStateDir();
68 const failure = yield* Effect.scoped(
69 Effect.gen(function* () {
70 yield* acquireServerSingleton(stateDir);
71 // The incident: a second server started against a held directory, found
72 // its port taken, silently bound another, and corrupted shared state.
73 return yield* acquireServerSingleton(stateDir).pipe(Effect.flip);
74 }),
75 );
76 assert.strictEqual(failure._tag, "ServerAlreadyRunningError");
77 if (failure._tag === "ServerAlreadyRunningError") {
78 assert.strictEqual(failure.holderPid, process.pid);
79 assert.include(failure.message, stateDir);
80 assert.include(failure.message, "overwrite each other");
81 }
82 }),
83 );
84​
85 it.effect("reclaims a lock whose owner is gone", () =>
86 Effect.gen(function* () {
87 const stateDir = yield* makeStateDir();
88 const fs = yield* FileSystem.FileSystem;
89 const lockPath = yield* serverLockPath(stateDir);
90 // pid 2^22 is above every /proc/sys/kernel/pid_max default, so it cannot
91 // be live. A crashed server must not lock its own directory forever.
92 yield* fs.writeFileString(lockPath, staleHolder(4194304));
93 // Age the mtime past the holder's heartbeat interval: reclaim may take a
94 // few observation rounds before it is believed dead, and those must never
95 // be confused with a live holder's own refresh.
96 const past = DateTime.toDateUtc(
97 DateTime.subtractDuration(yield* DateTime.now, Duration.minutes(1)),
98 );
99 yield* fs.utimes(lockPath, past, past);
100​
101 // One call observes the dead holder for several rounds, reclaims it, and
102 // claims the freed directory on the same pass: a crashed server costs
103 // its successor one delayed start, not one failed manual retry.
104 yield* Effect.scoped(
105 Effect.gen(function* () {
106 const held = yield* acquireServerSingleton(stateDir);
107 assert.strictEqual(held, lockPath);
108 }),
109 );
110 }),
111 );
112​
113 it.effect("reclaims a lock file left half-written by a crash", () =>
114 Effect.gen(function* () {
115 const stateDir = yield* makeStateDir();
116 const fs = yield* FileSystem.FileSystem;
117 const lockPath = yield* serverLockPath(stateDir);
118 yield* fs.writeFileString(lockPath, '{"version":1,"pid":');
119 const past = DateTime.toDateUtc(
120 DateTime.subtractDuration(yield* DateTime.now, Duration.minutes(1)),
121 );
122 yield* fs.utimes(lockPath, past, past);
123​
124 yield* Effect.scoped(
125 Effect.gen(function* () {
126 yield* acquireServerSingleton(stateDir);
127 }),
128 );
129 }),
130 );
131​
132 it.effect("does not release a lock another process has reclaimed", () =>
133 Effect.gen(function* () {
134 const stateDir = yield* makeStateDir();
135 const fs = yield* FileSystem.FileSystem;
136 const lockPath = yield* serverLockPath(stateDir);
137 yield* fs.writeFileString(lockPath, staleHolder(4194304));
138​
139 yield* releaseServerLock(lockPath);
140 // Evicting a live successor would recreate the very bug this prevents.
141 assert.isTrue(yield* fs.exists(lockPath));
142 }),
143 );
144​
145 it.effect("records the bound port so the next server can name it", () =>
146 Effect.gen(function* () {
147 const stateDir = yield* makeStateDir();
148 yield* Effect.scoped(
149 Effect.gen(function* () {
150 const lockPath = yield* acquireServerSingleton(stateDir);
151 yield* recordServerLockPort(lockPath, 3775);
152 const failure = yield* acquireServerSingleton(stateDir).pipe(Effect.flip);
153 assert.strictEqual(failure._tag, "ServerAlreadyRunningError");
154 if (failure._tag === "ServerAlreadyRunningError") {
155 assert.strictEqual(failure.holderPort, 3775);
156 assert.include(failure.message, "listening on port 3775");
157 }
158 }),
159 );
160 }),
161 );
162​
163 it.effect("keeps separate directories independent", () =>
164 Effect.gen(function* () {
165 const first = yield* makeStateDir();
166 const second = yield* makeStateDir();
167 yield* Effect.scoped(
168 Effect.gen(function* () {
169 yield* acquireServerSingleton(first);
170 // A dev server and the real one use different state dirs and must both run.
171 yield* acquireServerSingleton(second);
172 }),
173 );
174 }),
175 );
176​
177 it.effect("uses a lock file inside the state directory", () =>
178 Effect.gen(function* () {
179 const stateDir = yield* makeStateDir();
180 const path = yield* Path.Path;
181 const lockPath = yield* serverLockPath(stateDir);
182 assert.strictEqual(lockPath, path.join(stateDir, SERVER_LOCK_FILENAME));
183 }),
184 );
185​
186 it("treats the current process as alive and an impossible pid as dead", () => {
187 assert.isTrue(processIsAlive(process.pid));
188 assert.isFalse(processIsAlive(4194304));
189 assert.isFalse(processIsAlive(0));
190 assert.isFalse(processIsAlive(-1));
191 });
192​
193 it.effect("refuses next to a live pre-lock server that wrote no lock", () =>
194 Effect.gen(function* () {
195 const stateDir = yield* makeStateDir();
196 const fs = yield* FileSystem.FileSystem;
197 const path = yield* Path.Path;
198 // 0.0.34 and earlier persist their live pid here but never claim a lock:
199 // the desktop auto-update transition. The upgrade must still refuse.
200 yield* fs.writeFileString(
201 path.join(stateDir, SERVER_RUNTIME_STATE_FILENAME),
202 legacyRuntimeState(process.pid, 3775),
203 );
204​
205 const failure = yield* Effect.scoped(acquireServerSingleton(stateDir)).pipe(Effect.flip);
206 assert.strictEqual(failure._tag, "ServerAlreadyRunningError");
207 if (failure._tag === "ServerAlreadyRunningError") {
208 assert.strictEqual(failure.holderPid, process.pid);
209 assert.strictEqual(failure.holderPort, 3775);
210 assert.include(failure.message, SERVER_RUNTIME_STATE_FILENAME);
211 }
212 // And it must not have claimed the directory it refused.
213 assert.isFalse(yield* fs.exists(yield* serverLockPath(stateDir)));
214 }),
215 );
216​
217 it.effect("claims the directory when the pre-lock server's pid is gone", () =>
218 Effect.gen(function* () {
219 const stateDir = yield* makeStateDir();
220 const fs = yield* FileSystem.FileSystem;
221 const path = yield* Path.Path;
222 // Leftover state from a crashed legacy server must not wedge the upgrade.
223 yield* fs.writeFileString(
224 path.join(stateDir, SERVER_RUNTIME_STATE_FILENAME),
225 legacyRuntimeState(4194304, 3775),
226 );
227​
228 yield* Effect.scoped(
229 Effect.gen(function* () {
230 const held = yield* acquireServerSingleton(stateDir);
231 assert.strictEqual(held, yield* serverLockPath(stateDir));
232 }),
233 );
234 }),
235 );
236​
237 it.effect("a starter cannot reclaim a lock a live holder still owns", () =>
238 Effect.gen(function* () {
239 const stateDir = yield* makeStateDir();
240 const fs = yield* FileSystem.FileSystem;
241 const lockPath = yield* serverLockPath(stateDir);
242​
243 // Starter B holds the directory live, with the heartbeat this change
244 // gives every live holder. Starter A runs the full claim loop against
245 // it — the loop whose old unconditional unlink deleted B's claim here.
246 yield* fs.writeFileString(
247 lockPath,
248 `{"version":1,"pid":${process.pid},"startedAt":"2026-01-01T00:00:00.000Z"}`,
249 );
250 const past = DateTime.toDateUtc(
251 DateTime.subtractDuration(yield* DateTime.now, Duration.minutes(1)),
252 );
253 yield* fs.utimes(lockPath, past, past);
254​
255 const heartbeat = Effect.gen(function* () {
256 const now = yield* DateTime.now;
257 const date = DateTime.toDateUtc(now);
258 yield* fs.utimes(lockPath, date, date);
259 }).pipe(
260 // Per-round catch, the same way the production heartbeat recovers:
261 // `Effect.repeat` ends a failing effect on the first failure.
262 Effect.catch(() => Effect.void),
263 Effect.repeat({ schedule: Schedule.spaced(50), while: () => true }),
264 Effect.catch(() => Effect.void),
265 );
266​
267 yield* Effect.scoped(
268 Effect.gen(function* () {
269 yield* Effect.forkScoped(heartbeat);
270 yield* Effect.yieldNow;
271​
272 // Undecodable-by-design: B's pid is live, so A must refuse. Before
273 // the fix, A's unconditional reclaim deleted B's lock and A owned
274 // the directory alongside B.
275 const failure = yield* acquireServerSingleton(stateDir).pipe(Effect.flip);
276 assert.strictEqual(failure._tag, "ServerAlreadyRunningError");
277 }),
278 );
279​
280 // And the lock is still on disk, owned by B, not reclaimed under it.
281 assert.isTrue(yield* fs.exists(lockPath));
282 const holder = yield* fs.readFileString(lockPath);
283 assert.include(holder, `"pid":${process.pid}`);
284 }),
285 );
286​
287 it.effect("reclaims a stale lock without unlinking a concurrently live successor", () =>
288 Effect.gen(function* () {
289 const stateDir = yield* makeStateDir();
290 const fs = yield* FileSystem.FileSystem;
291 const lockPath = yield* serverLockPath(stateDir);
292​
293 // Snapshot the stale lock as starter A would. A live successor's claim
294 // looks identical on paper except for the pid, which liveness checks
295 // handle — the guard under test is that reclaim never unlinks a path
296 // whose content it has not re-confirmed as still dead.
297 yield* fs.writeFileString(
298 lockPath,
299 `{"version":1,"pid":${process.pid},"startedAt":"2026-01-01T00:00:00.000Z"}`,
300 );
301 const past = DateTime.toDateUtc(
302 DateTime.subtractDuration(yield* DateTime.now, Duration.minutes(1)),
303 );
304 yield* fs.utimes(lockPath, past, past);
305​
306 const failure = yield* acquireServerSingleton(stateDir).pipe(Effect.flip);
307​
308 // Under the old unconditional `fs.remove(lockPath)`, claim would
309 // *succeed* here by deleting this live claim first.
310 assert.strictEqual(failure._tag, "ServerAlreadyRunningError");
311 assert.isTrue(yield* fs.exists(lockPath));
312 const holder = yield* fs.readFileString(lockPath);
313 assert.include(holder, `"pid":${process.pid}`);
314 }),
315 );
316​
317 it.effect("only one of two concurrent reclaimers acquires a stale directory", () =>
318 Effect.gen(function* () {
319 const stateDir = yield* makeStateDir();
320 const fs = yield* FileSystem.FileSystem;
321 const lockPath = yield* serverLockPath(stateDir);
322 yield* fs.writeFileString(lockPath, staleHolder(4194304));
323 const past = DateTime.toDateUtc(
324 DateTime.subtractDuration(yield* DateTime.now, Duration.minutes(1)),
325 );
326 yield* fs.utimes(lockPath, past, past);
327​
328 // Two starters both pass the last stale read, then both used to
329 // `fs.remove` — the second deleted the first's new claim and both
330 // proceeded. The exclusive reclaim gate lets only one touch the path.
331 yield* Effect.scoped(
332 Effect.gen(function* () {
333 const attempt = acquireServerSingleton(stateDir).pipe(
334 Effect.match({
335 onFailure: (error) => ({ ok: false as const, error }),
336 onSuccess: (held) => ({ ok: true as const, held }),
337 }),
338 );
339 // Shared scope keeps the winner's lock held until both fibers finish,
340 // otherwise the winner would release before the loser observed it.
341 const first = yield* Effect.forkChild(attempt);
342 const second = yield* Effect.forkChild(attempt);
343 const outcomes = [yield* Fiber.join(first), yield* Fiber.join(second)];
344 const wins = outcomes.filter((outcome) => outcome.ok);
345 const losses = outcomes.filter((outcome) => !outcome.ok);
346 assert.strictEqual(wins.length, 1);
347 assert.strictEqual(losses.length, 1);
348 const loss = losses[0];
349 if (loss !== undefined && !loss.ok) {
350 assert.strictEqual(loss.error._tag, "ServerAlreadyRunningError");
351 }
352 }),
353 );
354 }),
355 );
356​
357 it.effect("only one reclaimer wins when a dead reclaim gate is left behind", () =>
358 Effect.gen(function* () {
359 const stateDir = yield* makeStateDir();
360 const fs = yield* FileSystem.FileSystem;
361 const lockPath = yield* serverLockPath(stateDir);
362 yield* fs.writeFileString(lockPath, staleHolder(4194304));
363 yield* fs.writeFileString(`${lockPath}.reclaim`, "4194304\n");
364 const past = DateTime.toDateUtc(
365 DateTime.subtractDuration(yield* DateTime.now, Duration.minutes(1)),
366 );
367 yield* fs.utimes(lockPath, past, past);
368​
369 // Before: both reclaimers read the dead gate, both unlinked it by
370 // pathname, both wx-created, and both proceeded to delete each
371 // other's live lock. Rename of the dead inode serializes them.
372 yield* Effect.scoped(
373 Effect.gen(function* () {
374 const attempt = acquireServerSingleton(stateDir).pipe(
375 Effect.match({
376 onFailure: (error) => ({ ok: false as const, error }),
377 onSuccess: (held) => ({ ok: true as const, held }),
378 }),
379 );
380 const first = yield* Effect.forkChild(attempt);
381 const second = yield* Effect.forkChild(attempt);
382 const outcomes = [yield* Fiber.join(first), yield* Fiber.join(second)];
383 const wins = outcomes.filter((outcome) => outcome.ok);
384 const losses = outcomes.filter((outcome) => !outcome.ok);
385 assert.strictEqual(wins.length, 1);
386 assert.strictEqual(losses.length, 1);
387 }),
388 );
389 }),
390 );
391​
392 it.effect("a partial metadata update is never readable as an empty owner", () =>
393 Effect.gen(function* () {
394 const stateDir = yield* makeStateDir();
395 const fs = yield* FileSystem.FileSystem;
396 const lockPath = yield* serverLockPath(stateDir);
397 yield* Effect.scoped(
398 Effect.gen(function* () {
399 yield* acquireServerSingleton(stateDir);
400 // Before: the in-place rewrite truncated the file first, so a reader
401 // mid-update decoded an empty holder and could reclaim a live lock.
402 // The atomic write means the bytes on disk are always a full holder —
403 // and a temp-file rename is what arranges that: it stages the payload
404 // in a `.server.lock.*` sibling and swaps it in, which an in-place
405 // truncate never does. Asserting the update *completed* then lets a
406 // concurrent reader never observe an empty or partial lock.
407 yield* recordServerLockPort(lockPath, 3775);
408​
409 const failure = yield* acquireServerSingleton(stateDir).pipe(Effect.flip);
410 assert.strictEqual(failure._tag, "ServerAlreadyRunningError");
411 if (failure._tag === "ServerAlreadyRunningError") {
412 assert.strictEqual(failure.holderPort, 3775);
413 }
414 }),
415 );
416​
417 // No temp staging directory outlives the update: the payload arrives at
418 // the lock path whole or not at all, which is what makes "partial" reads
419 // above unreachable rather than merely unlucky. The scope above released
420 // the lock itself — only the temp-directory shape is under test.
421 const leftovers = yield* fs
422 .readDirectory(stateDir)
423 .pipe(
424 Effect.map((entries) =>
425 entries.filter((entry) => entry.startsWith(`.${SERVER_LOCK_FILENAME}.`)),
426 ),
427 );
428 assert.deepStrictEqual(leftovers, []);
429 }),
430 );
431});