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

serverRuntimeState.test.ts

440 lines18.7 KB

1// @effect-diagnostics nodeBuiltinImport:off - Ownership tests exercise real OS locks and a task-owned child process.
2import { assert, describe, it } from "@effect/vitest";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as NodeFS from "node:fs";
5import * as NodeFSP from "node:fs/promises";
6import * as NodeChildProcess from "node:child_process";
7import * as NodeAssert from "node:assert/strict";
8import * as NodePath from "node:path";
9import * as NodeOS from "node:os";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Logger from "effect/Logger";
14import * as Option from "effect/Option";
15import * as Path from "effect/Path";
16import * as References from "effect/References";
17import * as Schema from "effect/Schema";
18​
19import * as ServerRuntimeState from "./serverRuntimeState.ts";
20import * as ServerOwnership from "./serverOwnership.ts";
21import * as ProcessRunner from "./processRunner.ts";
22import { acquireServerOwnershipLock } from "./serverOwnershipLock.ts";
23​
24const isServerRuntimeStateError = Schema.is(ServerRuntimeState.ServerRuntimeStateError);
25​
26interface CapturedLog {
27 readonly message: unknown;
28 readonly annotations: Readonly<Record<string, unknown>>;
30​
31describe("serverRuntimeState", () => {
32 it("releases the OS ownership lock after its task-owned process crashes", async () => {
33 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-owner-crash-"));
34 const moduleUrl = new URL("./serverOwnershipLock.ts", import.meta.url).href;
35 const encodedModuleUrl = JSON.stringify(moduleUrl);
36 const child = NodeChildProcess.spawn(
37 process.execPath,
38 [
39 "--input-type=module",
40 "--eval",
41 `const { acquireServerOwnershipLock } = await import(${encodedModuleUrl});
42const ownership = await acquireServerOwnershipLock(process.argv[1]);
43process.on('disconnect', () => ownership.close());
44process.send('owned');`,
45 root,
46 ],
47 { stdio: ["ignore", "ignore", "pipe", "ipc"] },
48 );
49 const exited = new Promise<void>((resolve) => {
50 child.once("close", () => resolve());
51 child.once("error", () => resolve());
52 });
53 try {
54 await new Promise<void>((resolve, reject) => {
55 child.once("message", () => resolve());
56 child.once("error", reject);
57 child.once("exit", () => reject(new Error("Owner exited before claiming the directory.")));
58 });
59 await NodeAssert.rejects(
60 () => acquireServerOwnershipLock(root),
61 (cause: unknown) =>
62 cause instanceof Error &&
63 (("errcode" in cause && cause.errcode === 5) ||
64 ("code" in cause && cause.code === "SQLITE_BUSY")),
65 );
66 child.kill("SIGKILL");
67 await exited;
68 const replacement = await acquireServerOwnershipLock(root);
69 replacement.close();
70 } finally {
71 if (child.pid !== undefined && child.exitCode === null && child.signalCode === null) {
72 child.kill("SIGKILL");
73 await exited;
74 }
75 await NodeFSP.rm(root, { recursive: true, force: true });
76 }
77 });
78​
79 it.effect("only one racing start can acquire a shared state directory", () =>
80 Effect.gen(function* () {
81 const fs = yield* FileSystem.FileSystem;
82 const path = yield* Path.Path;
83 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-race-" });
84 const statePath = path.join(root, "server-runtime.json");
85 const attempts = yield* Effect.all(
86 [
87 ServerOwnership.acquireServerOwnership(statePath).pipe(Effect.result),
88 ServerOwnership.acquireServerOwnership(statePath).pipe(Effect.result),
89 ],
90 { concurrency: "unbounded" },
91 );
92 assert.equal(attempts.filter((result) => result._tag === "Success").length, 1);
93 const refused = attempts.find((result) => result._tag === "Failure");
94 assert.equal(refused?.failure._tag, "ServerAlreadyRunningError");
95 }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))),
96 );
97​
98 it.effect(
99 "refuses a second owner, preserves its runtime record, and permits a clean restart",
100 () =>
101 Effect.gen(function* () {
102 const fs = yield* FileSystem.FileSystem;
103 const path = yield* Path.Path;
104 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-" });
105 const statePath = path.join(root, "server-runtime.json");
106 const state = yield* ServerRuntimeState.makePersistedServerRuntimeState({
107 config: { host: undefined, devUrl: undefined },
108 port: 3773,
109 });
110 yield* Effect.scoped(
111 Effect.gen(function* () {
112 const owner = yield* ServerOwnership.acquireServerOwnership(statePath);
113 yield* owner.publish(state);
114 const before = yield* fs.readFileString(statePath);
115 const refused = yield* ServerOwnership.acquireServerOwnership(statePath).pipe(
116 Effect.flip,
117 );
118 assert.equal(refused._tag, "ServerAlreadyRunningError");
119 assert.equal(yield* fs.readFileString(statePath), before);
120 }),
121 );
122 assert.isFalse(yield* fs.exists(statePath));
123 yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
124 }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))),
125 );
126​
127 it.effect(
128 "resolves symlink aliases to the same owner and permits a separate state directory",
129 () =>
130 Effect.gen(function* () {
131 const fs = yield* FileSystem.FileSystem;
132 const path = yield* Path.Path;
133 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-alias-" });
134 const directory = path.join(root, "state");
135 const alias = path.join(root, "alias");
136 yield* fs.makeDirectory(directory);
137 yield* Effect.sync(() => NodeFS.symlinkSync(directory, alias, "junction"));
138 yield* ServerOwnership.acquireServerOwnership(path.join(directory, "server-runtime.json"));
139 const refused = yield* ServerOwnership.acquireServerOwnership(
140 path.join(alias, "server-runtime.json"),
141 ).pipe(Effect.flip);
142 assert.equal(refused._tag, "ServerAlreadyRunningError");
143 yield* ServerOwnership.acquireServerOwnership(
144 path.join(root, "other", "server-runtime.json"),
145 );
146 }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))),
147 );
148​
149 it.effect("fails closed beside a live legacy owner and allows a stale legacy record", () =>
150 Effect.gen(function* () {
151 const fs = yield* FileSystem.FileSystem;
152 const path = yield* Path.Path;
153 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-legacy-" });
154 const statePath = path.join(root, "server-runtime.json");
155 const state = yield* ServerRuntimeState.makePersistedServerRuntimeState({
156 config: { host: undefined, devUrl: undefined },
157 port: 3773,
158 });
159 yield* ServerRuntimeState.persistServerRuntimeState({
160 path: statePath,
161 // @effect-diagnostics-next-line globalDateInEffect:off - Legacy identity uses the real process start time, not TestClock.
162 state: { ...state, startedAt: new Date().toISOString() },
163 });
164 const refused = yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath)).pipe(
165 Effect.flip,
166 );
167 assert.equal(refused._tag, "ServerAlreadyRunningError");
168 yield* ServerRuntimeState.persistServerRuntimeState({
169 path: statePath,
170 state: { ...state, pid: 0 },
171 });
172 yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
173 }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))),
174 );
175​
176 it.effect("refuses a malformed owner record without losing the ownership lock on recovery", () =>
177 Effect.gen(function* () {
178 const fs = yield* FileSystem.FileSystem;
179 const path = yield* Path.Path;
180 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-malformed-" });
181 const statePath = path.join(root, "server-runtime.json");
182 yield* fs.writeFileString(statePath, "{incomplete");
183 const failed = yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath)).pipe(
184 Effect.flip,
185 );
186 assert.equal(failed._tag, "ServerOwnershipError");
187 assert.equal(yield* fs.readFileString(statePath), "{incomplete");
188 yield* fs.remove(statePath);
189 yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
190 }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))),
191 );
192​
193 it.effect("an old owner's shutdown never removes a runtime record it did not publish", () =>
194 Effect.gen(function* () {
195 const fs = yield* FileSystem.FileSystem;
196 const path = yield* Path.Path;
197 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-cleanup-" });
198 const statePath = path.join(root, "server-runtime.json");
199 const state = yield* ServerRuntimeState.makePersistedServerRuntimeState({
200 config: { host: undefined, devUrl: undefined },
201 port: 3773,
202 });
203 yield* Effect.scoped(
204 Effect.gen(function* () {
205 const owner = yield* ServerOwnership.acquireServerOwnership(statePath);
206 yield* owner.publish(state);
207 yield* ServerRuntimeState.persistServerRuntimeState({
208 path: statePath,
209 state: { ...state, ownerId: "other-owner" },
210 });
211 }),
212 );
213 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
214 assert.equal(Option.getOrThrow(restored).ownerId, "other-owner");
215 }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))),
216 );
217​
218 it.effect("a released owner cannot publish state after a successor starts", () =>
219 Effect.gen(function* () {
220 const fs = yield* FileSystem.FileSystem;
221 const path = yield* Path.Path;
222 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-released-" });
223 const statePath = path.join(root, "server-runtime.json");
224 const state = yield* ServerRuntimeState.makePersistedServerRuntimeState({
225 config: { host: undefined, devUrl: undefined },
226 port: 3773,
227 });
228 const released = yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
229 const successor = yield* ServerOwnership.acquireServerOwnership(statePath);
230 yield* successor.publish({ ...state, port: 3774, origin: "http://127.0.0.1:3774" });
231 const before = yield* fs.readFileString(statePath);
232 const refused = yield* released.publish(state).pipe(Effect.flip);
233 assert.equal(refused._tag, "ServerOwnershipReleasedError");
234 assert.equal(yield* fs.readFileString(statePath), before);
235 }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))),
236 );
237​
238 it.effect("a discovery publication failure does not release a live ownership lock", () =>
239 Effect.gen(function* () {
240 const fs = yield* FileSystem.FileSystem;
241 const path = yield* Path.Path;
242 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-publish-failure-" });
243 const statePath = path.join(root, "server-runtime.json");
244 const owner = yield* ServerOwnership.acquireServerOwnership(statePath);
245 const state = yield* ServerRuntimeState.makePersistedServerRuntimeState({
246 config: { host: undefined, devUrl: undefined },
247 port: 3773,
248 });
249 yield* fs.makeDirectory(statePath);
250 const failed = yield* owner.publish(state).pipe(Effect.flip);
251 assert.equal(failed._tag, "ServerOwnershipError");
252 const refused = yield* ServerOwnership.acquireServerOwnership(statePath).pipe(Effect.flip);
253 assert.equal(refused._tag, "ServerAlreadyRunningError");
254 }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))),
255 );
256​
257 it.effect("persists and reads the runtime state", () =>
258 Effect.gen(function* () {
259 const fileSystem = yield* FileSystem.FileSystem;
260 const path = yield* Path.Path;
261 const root = yield* fileSystem.makeTempDirectoryScoped({
262 prefix: "t3-server-runtime-state-test-",
263 });
264 const statePath = path.join(root, "runtime", "server.json");
265 const state: ServerRuntimeState.PersistedServerRuntimeState = {
266 version: 1,
267 pid: 123,
268 host: "127.0.0.1",
269 port: 4_971,
270 origin: "http://127.0.0.1:4971",
271 devUrl: "http://localhost:5733/",
272 startedAt: "2026-06-20T00:00:00.000Z",
273 };
274​
275 yield* ServerRuntimeState.persistServerRuntimeState({ path: statePath, state });
276 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
277​
278 assert.deepEqual(Option.getOrThrow(restored), state);
279 }).pipe(Effect.provide(NodeServices.layer)),
280 );
281​
282 it.effect("records the dev web URL when the server fronts a dev server", () =>
283 Effect.gen(function* () {
284 const state = yield* ServerRuntimeState.makePersistedServerRuntimeState({
285 config: { host: undefined, devUrl: new URL("http://localhost:5733") },
286 port: 13_773,
287 });
288​
289 assert.equal(state.devUrl, "http://localhost:5733/");
290 assert.equal(state.origin, "http://127.0.0.1:13773");
291​
292 const withoutDev = yield* ServerRuntimeState.makePersistedServerRuntimeState({
293 config: { host: undefined, devUrl: undefined },
294 port: 13_773,
295 });
296 assert.isFalse("devUrl" in withoutDev);
297 }),
298 );
299​
300 it.effect("marks a service-supervised server so CLIs can tell it from a manual one", () =>
301 Effect.gen(function* () {
302 const managed = yield* ServerRuntimeState.makePersistedServerRuntimeState({
303 config: { host: undefined, devUrl: undefined },
304 port: 13_773,
305 serviceManaged: true,
306 });
307 const manual = yield* ServerRuntimeState.makePersistedServerRuntimeState({
308 config: { host: undefined, devUrl: undefined },
309 port: 13_773,
310 });
311​
312 assert.isTrue(managed.serviceManaged);
313 // Older readers decode the file without the field, so it is omitted
314 // rather than written as false.
315 assert.isFalse("serviceManaged" in manual);
316 }),
317 );
318​
319 it.effect("treats a missing runtime state file as absent", () =>
320 Effect.gen(function* () {
321 const fileSystem = yield* FileSystem.FileSystem;
322 const path = yield* Path.Path;
323 const root = yield* fileSystem.makeTempDirectoryScoped({
324 prefix: "t3-server-runtime-state-test-",
325 });
326​
327 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(
328 path.join(root, "missing.json"),
329 );
330​
331 assert.isTrue(Option.isNone(restored));
332 }).pipe(Effect.provide(NodeServices.layer)),
333 );
334​
335 it.effect("preserves malformed state decode failures", () => {
336 const logs: CapturedLog[] = [];
337 const logger = Logger.make(({ fiber, message }) => {
338 logs.push({
339 message,
340 annotations: fiber.getRef(References.CurrentLogAnnotations),
341 });
342 });
343​
344 return Effect.gen(function* () {
345 const fileSystem = yield* FileSystem.FileSystem;
346 const path = yield* Path.Path;
347 const root = yield* fileSystem.makeTempDirectoryScoped({
348 prefix: "t3-server-runtime-state-test-",
349 });
350 const statePath = path.join(root, "server.json");
351 yield* fileSystem.writeFileString(statePath, "{not json");
352​
353 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
354​
355 assert.isTrue(Option.isNone(restored));
356 assert.equal(logs[0]?.message, `Failed to decode server runtime state at ${statePath}.`);
357 const error = logs[0]?.annotations.cause;
358 assert.isTrue(isServerRuntimeStateError(error));
359 if (isServerRuntimeStateError(error)) {
360 assert.equal(error.operation, "decode");
361 assert.equal(error.statePath, statePath);
362 assert.equal(error.message, `Failed to decode server runtime state at ${statePath}.`);
363 assert.deepInclude(error.cause, { _tag: "SchemaError" });
364 }
365 }).pipe(
366 Effect.provide(
367 Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
368 ),
369 );
370 });
371​
372 it.effect("preserves runtime state read failures", () => {
373 const logs: CapturedLog[] = [];
374 const logger = Logger.make(({ fiber, message }) => {
375 logs.push({
376 message,
377 annotations: fiber.getRef(References.CurrentLogAnnotations),
378 });
379 });
380​
381 return Effect.gen(function* () {
382 const fileSystem = yield* FileSystem.FileSystem;
383 const path = yield* Path.Path;
384 const root = yield* fileSystem.makeTempDirectoryScoped({
385 prefix: "t3-server-runtime-state-test-",
386 });
387 const statePath = path.join(root, "server.json");
388 yield* fileSystem.makeDirectory(statePath);
389​
390 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
391​
392 assert.isTrue(Option.isNone(restored));
393 assert.equal(logs[0]?.message, `Failed to read server runtime state at ${statePath}.`);
394 const error = logs[0]?.annotations.cause;
395 assert.isTrue(isServerRuntimeStateError(error));
396 if (isServerRuntimeStateError(error)) {
397 assert.equal(error.operation, "read");
398 assert.equal(error.statePath, statePath);
399 assert.equal(error.message, `Failed to read server runtime state at ${statePath}.`);
400 assert.deepInclude(error.cause, { _tag: "PlatformError" });
401 }
402 }).pipe(
403 Effect.provide(
404 Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
405 ),
406 );
407 });
408​
409 it.effect("preserves runtime state persistence failures", () =>
410 Effect.gen(function* () {
411 const fileSystem = yield* FileSystem.FileSystem;
412 const path = yield* Path.Path;
413 const root = yield* fileSystem.makeTempDirectoryScoped({
414 prefix: "t3-server-runtime-state-test-",
415 });
416 const blockedDirectory = path.join(root, "not-a-directory");
417 const statePath = path.join(blockedDirectory, "server.json");
418 yield* fileSystem.writeFileString(blockedDirectory, "blocked");
419​
420 const error = yield* ServerRuntimeState.persistServerRuntimeState({
421 path: statePath,
422 state: {
423 version: 1,
424 pid: 123,
425 port: 4_971,
426 origin: "http://127.0.0.1:4971",
427 startedAt: "2026-06-20T00:00:00.000Z",
428 },
429 }).pipe(Effect.flip);
430​
431 assert.isTrue(isServerRuntimeStateError(error));
432 if (isServerRuntimeStateError(error)) {
433 assert.equal(error.operation, "persist");
434 assert.equal(error.statePath, statePath);
435 assert.equal(error.message, `Failed to persist server runtime state at ${statePath}.`);
436 assert.deepInclude(error.cause, { _tag: "PlatformError" });
437 }
438 }).pipe(Effect.provide(NodeServices.layer)),
439 );
440});