Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Logger from "effect/Logger";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as References from "effect/References";
10import * as Schema from "effect/Schema";
11
12import * as ServerRuntimeState from "./serverRuntimeState.ts";
13
14const isServerRuntimeStateError = Schema.is(ServerRuntimeState.ServerRuntimeStateError);
15const isServerStateDirConflictError = Schema.is(ServerRuntimeState.ServerStateDirConflictError);
16
17interface CapturedLog {
18 readonly message: unknown;
19 readonly annotations: Readonly<Record<string, unknown>>;
20}
21
22describe("serverRuntimeState", () => {
23 it.effect("persists and reads the runtime state", () =>
24 Effect.gen(function* () {
25 const fileSystem = yield* FileSystem.FileSystem;
26 const path = yield* Path.Path;
27 const root = yield* fileSystem.makeTempDirectoryScoped({
28 prefix: "t3-server-runtime-state-test-",
29 });
30 const statePath = path.join(root, "runtime", "server.json");
31 const state: ServerRuntimeState.PersistedServerRuntimeState = {
32 version: 1,
33 pid: 123,
34 host: "127.0.0.1",
35 port: 4_971,
36 origin: "http://127.0.0.1:4971",
37 startedAt: "2026-06-20T00:00:00.000Z",
38 };
39
40 yield* ServerRuntimeState.persistServerRuntimeState({ path: statePath, state });
41 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
42
43 assert.deepEqual(Option.getOrThrow(restored), state);
44 }).pipe(Effect.provide(NodeServices.layer)),
45 );
46
47 it.effect("treats a missing runtime state file as absent", () =>
48 Effect.gen(function* () {
49 const fileSystem = yield* FileSystem.FileSystem;
50 const path = yield* Path.Path;
51 const root = yield* fileSystem.makeTempDirectoryScoped({
52 prefix: "t3-server-runtime-state-test-",
53 });
54
55 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(
56 path.join(root, "missing.json"),
57 );
58
59 assert.isTrue(Option.isNone(restored));
60 }).pipe(Effect.provide(NodeServices.layer)),
61 );
62
63 it.effect("preserves malformed state decode failures", () => {
64 const logs: CapturedLog[] = [];
65 const logger = Logger.make(({ fiber, message }) => {
66 logs.push({
67 message,
68 annotations: fiber.getRef(References.CurrentLogAnnotations),
69 });
70 });
71
72 return Effect.gen(function* () {
73 const fileSystem = yield* FileSystem.FileSystem;
74 const path = yield* Path.Path;
75 const root = yield* fileSystem.makeTempDirectoryScoped({
76 prefix: "t3-server-runtime-state-test-",
77 });
78 const statePath = path.join(root, "server.json");
79 yield* fileSystem.writeFileString(statePath, "{not json");
80
81 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
82
83 assert.isTrue(Option.isNone(restored));
84 assert.equal(logs[0]?.message, `Failed to decode server runtime state at ${statePath}.`);
85 const error = logs[0]?.annotations.cause;
86 assert.isTrue(isServerRuntimeStateError(error));
87 if (isServerRuntimeStateError(error)) {
88 assert.equal(error.operation, "decode");
89 assert.equal(error.statePath, statePath);
90 assert.equal(error.message, `Failed to decode server runtime state at ${statePath}.`);
91 assert.deepInclude(error.cause, { _tag: "SchemaError" });
92 }
93 }).pipe(
94 Effect.provide(
95 Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
96 ),
97 );
98 });
99
100 it.effect("preserves runtime state read failures", () => {
101 const logs: CapturedLog[] = [];
102 const logger = Logger.make(({ fiber, message }) => {
103 logs.push({
104 message,
105 annotations: fiber.getRef(References.CurrentLogAnnotations),
106 });
107 });
108
109 return Effect.gen(function* () {
110 const fileSystem = yield* FileSystem.FileSystem;
111 const path = yield* Path.Path;
112 const root = yield* fileSystem.makeTempDirectoryScoped({
113 prefix: "t3-server-runtime-state-test-",
114 });
115 const statePath = path.join(root, "server.json");
116 yield* fileSystem.makeDirectory(statePath);
117
118 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
119
120 assert.isTrue(Option.isNone(restored));
121 assert.equal(logs[0]?.message, `Failed to read server runtime state at ${statePath}.`);
122 const error = logs[0]?.annotations.cause;
123 assert.isTrue(isServerRuntimeStateError(error));
124 if (isServerRuntimeStateError(error)) {
125 assert.equal(error.operation, "read");
126 assert.equal(error.statePath, statePath);
127 assert.equal(error.message, `Failed to read server runtime state at ${statePath}.`);
128 assert.deepInclude(error.cause, { _tag: "PlatformError" });
129 }
130 }).pipe(
131 Effect.provide(
132 Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
133 ),
134 );
135 });
136
137 it.effect("preserves runtime state persistence failures", () =>
138 Effect.gen(function* () {
139 const fileSystem = yield* FileSystem.FileSystem;
140 const path = yield* Path.Path;
141 const root = yield* fileSystem.makeTempDirectoryScoped({
142 prefix: "t3-server-runtime-state-test-",
143 });
144 const blockedDirectory = path.join(root, "not-a-directory");
145 const statePath = path.join(blockedDirectory, "server.json");
146 yield* fileSystem.writeFileString(blockedDirectory, "blocked");
147
148 const error = yield* ServerRuntimeState.persistServerRuntimeState({
149 path: statePath,
150 state: {
151 version: 1,
152 pid: 123,
153 port: 4_971,
154 origin: "http://127.0.0.1:4971",
155 startedAt: "2026-06-20T00:00:00.000Z",
156 },
157 }).pipe(Effect.flip);
158
159 assert.isTrue(isServerRuntimeStateError(error));
160 if (isServerRuntimeStateError(error)) {
161 assert.equal(error.operation, "persist");
162 assert.equal(error.statePath, statePath);
163 assert.equal(error.message, `Failed to persist server runtime state at ${statePath}.`);
164 assert.deepInclude(error.cause, { _tag: "PlatformError" });
165 }
166 }).pipe(Effect.provide(NodeServices.layer)),
167 );
168});
169
170describe("decideServerRuntimeStartup", () => {
171 const state: ServerRuntimeState.PersistedServerRuntimeState = {
172 version: 1,
173 pid: 4_242,
174 host: "127.0.0.1",
175 port: 4_971,
176 origin: "http://127.0.0.1:4971",
177 startedAt: "2026-06-20T00:00:00.000Z",
178 };
179 const alwaysAlive = () => true;
180 const alwaysDead = () => false;
181
182 it("proceeds when no discovery file exists", () => {
183 const decision = ServerRuntimeState.decideServerRuntimeStartup({
184 existing: Option.none(),
185 ownPid: 999,
186 isPidAlive: alwaysAlive,
187 });
188 assert.equal(decision._tag, "proceed");
189 });
190
191 it("reports a conflict when the recorded pid is alive", () => {
192 const decision = ServerRuntimeState.decideServerRuntimeStartup({
193 existing: Option.some(state),
194 ownPid: 999,
195 isPidAlive: alwaysAlive,
196 });
197 assert.equal(decision._tag, "conflict");
198 if (decision._tag === "conflict") {
199 assert.deepEqual(decision.state, state);
200 }
201 });
202
203 it("proceeds when the recorded pid is dead (stale file)", () => {
204 const decision = ServerRuntimeState.decideServerRuntimeStartup({
205 existing: Option.some(state),
206 ownPid: 999,
207 isPidAlive: alwaysDead,
208 });
209 assert.equal(decision._tag, "proceed");
210 });
211
212 it("proceeds when the recorded pid is our own (same-process restart)", () => {
213 const decision = ServerRuntimeState.decideServerRuntimeStartup({
214 existing: Option.some(state),
215 ownPid: state.pid,
216 // Would report a conflict if own-pid were not special-cased.
217 isPidAlive: alwaysAlive,
218 });
219 assert.equal(decision._tag, "proceed");
220 });
221});
222
223describe("ensureExclusiveStateDir", () => {
224 const state: ServerRuntimeState.PersistedServerRuntimeState = {
225 version: 1,
226 pid: 4_242,
227 host: "127.0.0.1",
228 port: 4_971,
229 origin: "http://127.0.0.1:4971",
230 startedAt: "2026-06-20T00:00:00.000Z",
231 };
232
233 it.effect("fails with a typed conflict error naming pid, port, origin, and state dir", () =>
234 Effect.gen(function* () {
235 const fileSystem = yield* FileSystem.FileSystem;
236 const path = yield* Path.Path;
237 const stateDir = yield* fileSystem.makeTempDirectoryScoped({
238 prefix: "t3-server-state-dir-guard-test-",
239 });
240 const statePath = path.join(stateDir, "server-runtime.json");
241 yield* ServerRuntimeState.persistServerRuntimeState({ path: statePath, state });
242
243 const error = yield* ServerRuntimeState.ensureExclusiveStateDir({
244 statePath,
245 stateDir,
246 ownPid: 999,
247 isPidAlive: () => true,
248 }).pipe(Effect.flip);
249
250 assert.isTrue(isServerStateDirConflictError(error));
251 if (isServerStateDirConflictError(error)) {
252 assert.equal(error.pid, state.pid);
253 assert.equal(error.port, state.port);
254 assert.equal(error.origin, state.origin);
255 assert.equal(error.stateDir, stateDir);
256 assert.include(error.message, String(state.pid));
257 assert.include(error.message, stateDir);
258 assert.include(error.message, "--base-dir");
259 }
260 }).pipe(Effect.provide(NodeServices.layer)),
261 );
262
263 it.effect("proceeds when the recorded pid is dead", () =>
264 Effect.gen(function* () {
265 const fileSystem = yield* FileSystem.FileSystem;
266 const path = yield* Path.Path;
267 const stateDir = yield* fileSystem.makeTempDirectoryScoped({
268 prefix: "t3-server-state-dir-guard-test-",
269 });
270 const statePath = path.join(stateDir, "server-runtime.json");
271 yield* ServerRuntimeState.persistServerRuntimeState({ path: statePath, state });
272
273 yield* ServerRuntimeState.ensureExclusiveStateDir({
274 statePath,
275 stateDir,
276 ownPid: 999,
277 isPidAlive: () => false,
278 });
279 }).pipe(Effect.provide(NodeServices.layer)),
280 );
281
282 it.effect("proceeds when the discovery file is missing or corrupt", () =>
283 Effect.gen(function* () {
284 const fileSystem = yield* FileSystem.FileSystem;
285 const path = yield* Path.Path;
286 const stateDir = yield* fileSystem.makeTempDirectoryScoped({
287 prefix: "t3-server-state-dir-guard-test-",
288 });
289 const missingPath = path.join(stateDir, "server-runtime.json");
290
291 // Missing file: proceed.
292 yield* ServerRuntimeState.ensureExclusiveStateDir({
293 statePath: missingPath,
294 stateDir,
295 ownPid: 999,
296 isPidAlive: () => true,
297 });
298
299 // Corrupt file: read returns none, so proceed even against a "live" pid.
300 yield* fileSystem.writeFileString(missingPath, "{not json");
301 yield* ServerRuntimeState.ensureExclusiveStateDir({
302 statePath: missingPath,
303 stateDir,
304 ownPid: 999,
305 isPidAlive: () => true,
306 });
307 }).pipe(
308 Effect.provide(
309 Layer.merge(
310 NodeServices.layer,
311 Logger.layer([Logger.make(() => {})], { mergeWithExisting: false }),
312 ),
313 ),
314 ),
315 );
316
317 it.effect("fails closed when the discovery file cannot be read", () =>
318 Effect.gen(function* () {
319 const fileSystem = yield* FileSystem.FileSystem;
320 const path = yield* Path.Path;
321 const stateDir = yield* fileSystem.makeTempDirectoryScoped({
322 prefix: "t3-server-state-dir-guard-test-",
323 });
324 const statePath = path.join(stateDir, "server-runtime.json");
325 yield* fileSystem.makeDirectory(statePath);
326
327 const error = yield* ServerRuntimeState.ensureExclusiveStateDir({
328 statePath,
329 stateDir,
330 ownPid: 999,
331 isPidAlive: () => true,
332 }).pipe(Effect.flip);
333
334 assert.isTrue(isServerRuntimeStateError(error));
335 if (isServerRuntimeStateError(error)) {
336 assert.equal(error.operation, "read");
337 assert.equal(error.statePath, statePath);
338 }
339 }).pipe(Effect.provide(NodeServices.layer)),
340 );
341});