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

serverRuntimeState.test.ts

302 lines11.9 KB

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 ProcessRunner from "./processRunner.ts";
13import * as ServerOwnership from "./serverOwnership.ts";
14import * as ServerRuntimeState from "./serverRuntimeState.ts";
15​
16const isServerRuntimeStateError = Schema.is(ServerRuntimeState.ServerRuntimeStateError);
17​
18interface CapturedLog {
19 readonly message: unknown;
20 readonly annotations: Readonly<Record<string, unknown>>;
22​
23describe("server ownership", () => {
24 const layerOwnership = ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer));
25 const makeState = ServerRuntimeState.makePersistedServerRuntimeState({
26 config: { host: undefined, devUrl: undefined },
27 port: 3773,
28 });
29​
30 it.effect("lets only one of two racing starts own a state directory", () =>
31 Effect.gen(function* () {
32 const fs = yield* FileSystem.FileSystem;
33 const path = yield* Path.Path;
34 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-race-" });
35 const statePath = path.join(root, "server-runtime.json");
36 const attempts = yield* Effect.all(
37 [
38 ServerOwnership.acquireServerOwnership(statePath).pipe(Effect.result),
39 ServerOwnership.acquireServerOwnership(statePath).pipe(Effect.result),
40 ],
41 { concurrency: "unbounded" },
42 );
43 assert.equal(attempts.filter((result) => result._tag === "Success").length, 1);
44 const refused = attempts.find((result) => result._tag === "Failure");
45 assert.equal(refused?.failure._tag, "ServerAlreadyRunningError");
46 }).pipe(Effect.provide(layerOwnership)),
47 );
48​
49 it.effect("refuses a second owner without touching its record, then allows a restart", () =>
50 Effect.gen(function* () {
51 const fs = yield* FileSystem.FileSystem;
52 const path = yield* Path.Path;
53 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-" });
54 const statePath = path.join(root, "server-runtime.json");
55 const state = yield* makeState;
56 yield* Effect.scoped(
57 Effect.gen(function* () {
58 const owner = yield* ServerOwnership.acquireServerOwnership(statePath);
59 yield* owner.publish(state);
60 const before = yield* fs.readFileString(statePath);
61 const refused = yield* ServerOwnership.acquireServerOwnership(statePath).pipe(
62 Effect.flip,
63 );
64 assert.equal(refused._tag, "ServerAlreadyRunningError");
65 assert.equal(yield* fs.readFileString(statePath), before);
66 }),
67 );
68 assert.isFalse(yield* fs.exists(statePath));
69 yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
70 }).pipe(Effect.provide(layerOwnership)),
71 );
72​
73 it.effect("refuses beside a live pre-lock server and ignores a stale record", () =>
74 Effect.gen(function* () {
75 const fs = yield* FileSystem.FileSystem;
76 const path = yield* Path.Path;
77 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-legacy-" });
78 const statePath = path.join(root, "server-runtime.json");
79 const state = yield* makeState;
80 yield* ServerRuntimeState.persistServerRuntimeState({
81 path: statePath,
82 // @effect-diagnostics-next-line globalDateInEffect:off - Legacy identity uses the real process start time, not TestClock.
83 state: { ...state, startedAt: new Date().toISOString() },
84 });
85 const refused = yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath)).pipe(
86 Effect.flip,
87 );
88 assert.equal(refused._tag, "ServerAlreadyRunningError");
89 yield* ServerRuntimeState.persistServerRuntimeState({
90 path: statePath,
91 state: { ...state, pid: 0 },
92 });
93 yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
94 }).pipe(Effect.provide(layerOwnership)),
95 );
96​
97 it.effect("never removes a runtime record another server published", () =>
98 Effect.gen(function* () {
99 const fs = yield* FileSystem.FileSystem;
100 const path = yield* Path.Path;
101 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-cleanup-" });
102 const statePath = path.join(root, "server-runtime.json");
103 const state = yield* makeState;
104 yield* Effect.scoped(
105 Effect.gen(function* () {
106 const owner = yield* ServerOwnership.acquireServerOwnership(statePath);
107 yield* owner.publish(state);
108 yield* ServerRuntimeState.persistServerRuntimeState({
109 path: statePath,
110 state: { ...state, ownerId: "other-owner" },
111 });
112 }),
113 );
114 const remaining = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
115 assert.equal(Option.getOrThrow(remaining).ownerId, "other-owner");
116 }).pipe(Effect.provide(layerOwnership)),
117 );
118});
119​
120describe("serverRuntimeState", () => {
121 it.effect("persists and reads the runtime state", () =>
122 Effect.gen(function* () {
123 const fileSystem = yield* FileSystem.FileSystem;
124 const path = yield* Path.Path;
125 const root = yield* fileSystem.makeTempDirectoryScoped({
126 prefix: "t3-server-runtime-state-test-",
127 });
128 const statePath = path.join(root, "runtime", "server.json");
129 const state: ServerRuntimeState.PersistedServerRuntimeState = {
130 version: 1,
131 pid: 123,
132 host: "127.0.0.1",
133 port: 4_971,
134 origin: "http://127.0.0.1:4971",
135 devUrl: "http://localhost:5733/",
136 startedAt: "2026-06-20T00:00:00.000Z",
137 };
138​
139 yield* ServerRuntimeState.persistServerRuntimeState({ path: statePath, state });
140 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
141​
142 assert.deepEqual(Option.getOrThrow(restored), state);
143 }).pipe(Effect.provide(NodeServices.layer)),
144 );
145​
146 it.effect("records the dev web URL when the server fronts a dev server", () =>
147 Effect.gen(function* () {
148 const state = yield* ServerRuntimeState.makePersistedServerRuntimeState({
149 config: { host: undefined, devUrl: new URL("http://localhost:5733") },
150 port: 13_773,
151 });
152​
153 assert.equal(state.devUrl, "http://localhost:5733/");
154 assert.equal(state.origin, "http://127.0.0.1:13773");
155​
156 const withoutDev = yield* ServerRuntimeState.makePersistedServerRuntimeState({
157 config: { host: undefined, devUrl: undefined },
158 port: 13_773,
159 });
160 assert.isFalse("devUrl" in withoutDev);
161 }),
162 );
163​
164 it.effect("marks a service-supervised server so CLIs can tell it from a manual one", () =>
165 Effect.gen(function* () {
166 const managed = yield* ServerRuntimeState.makePersistedServerRuntimeState({
167 config: { host: undefined, devUrl: undefined },
168 port: 13_773,
169 serviceManaged: true,
170 });
171 const manual = yield* ServerRuntimeState.makePersistedServerRuntimeState({
172 config: { host: undefined, devUrl: undefined },
173 port: 13_773,
174 });
175​
176 assert.isTrue(managed.serviceManaged);
177 assert.isFalse("serviceManaged" in manual);
178 }),
179 );
180​
181 it.effect("treats a missing runtime state file as absent", () =>
182 Effect.gen(function* () {
183 const fileSystem = yield* FileSystem.FileSystem;
184 const path = yield* Path.Path;
185 const root = yield* fileSystem.makeTempDirectoryScoped({
186 prefix: "t3-server-runtime-state-test-",
187 });
188​
189 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(
190 path.join(root, "missing.json"),
191 );
192​
193 assert.isTrue(Option.isNone(restored));
194 }).pipe(Effect.provide(NodeServices.layer)),
195 );
196​
197 it.effect("preserves malformed state decode failures", () => {
198 const logs: CapturedLog[] = [];
199 const logger = Logger.make(({ fiber, message }) => {
200 logs.push({
201 message,
202 annotations: fiber.getRef(References.CurrentLogAnnotations),
203 });
204 });
205​
206 return Effect.gen(function* () {
207 const fileSystem = yield* FileSystem.FileSystem;
208 const path = yield* Path.Path;
209 const root = yield* fileSystem.makeTempDirectoryScoped({
210 prefix: "t3-server-runtime-state-test-",
211 });
212 const statePath = path.join(root, "server.json");
213 yield* fileSystem.writeFileString(statePath, "{not json");
214​
215 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
216​
217 assert.isTrue(Option.isNone(restored));
218 assert.equal(logs[0]?.message, `Failed to decode server runtime state at ${statePath}.`);
219 const error = logs[0]?.annotations.cause;
220 assert.isTrue(isServerRuntimeStateError(error));
221 if (isServerRuntimeStateError(error)) {
222 assert.equal(error.operation, "decode");
223 assert.equal(error.statePath, statePath);
224 assert.equal(error.message, `Failed to decode server runtime state at ${statePath}.`);
225 assert.deepInclude(error.cause, { _tag: "SchemaError" });
226 }
227 }).pipe(
228 Effect.provide(
229 Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
230 ),
231 );
232 });
233​
234 it.effect("preserves runtime state read failures", () => {
235 const logs: CapturedLog[] = [];
236 const logger = Logger.make(({ fiber, message }) => {
237 logs.push({
238 message,
239 annotations: fiber.getRef(References.CurrentLogAnnotations),
240 });
241 });
242​
243 return Effect.gen(function* () {
244 const fileSystem = yield* FileSystem.FileSystem;
245 const path = yield* Path.Path;
246 const root = yield* fileSystem.makeTempDirectoryScoped({
247 prefix: "t3-server-runtime-state-test-",
248 });
249 const statePath = path.join(root, "server.json");
250 yield* fileSystem.makeDirectory(statePath);
251​
252 const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
253​
254 assert.isTrue(Option.isNone(restored));
255 assert.equal(logs[0]?.message, `Failed to read server runtime state at ${statePath}.`);
256 const error = logs[0]?.annotations.cause;
257 assert.isTrue(isServerRuntimeStateError(error));
258 if (isServerRuntimeStateError(error)) {
259 assert.equal(error.operation, "read");
260 assert.equal(error.statePath, statePath);
261 assert.equal(error.message, `Failed to read server runtime state at ${statePath}.`);
262 assert.deepInclude(error.cause, { _tag: "PlatformError" });
263 }
264 }).pipe(
265 Effect.provide(
266 Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
267 ),
268 );
269 });
270​
271 it.effect("preserves runtime state persistence failures", () =>
272 Effect.gen(function* () {
273 const fileSystem = yield* FileSystem.FileSystem;
274 const path = yield* Path.Path;
275 const root = yield* fileSystem.makeTempDirectoryScoped({
276 prefix: "t3-server-runtime-state-test-",
277 });
278 const blockedDirectory = path.join(root, "not-a-directory");
279 const statePath = path.join(blockedDirectory, "server.json");
280 yield* fileSystem.writeFileString(blockedDirectory, "blocked");
281​
282 const error = yield* ServerRuntimeState.persistServerRuntimeState({
283 path: statePath,
284 state: {
285 version: 1,
286 pid: 123,
287 port: 4_971,
288 origin: "http://127.0.0.1:4971",
289 startedAt: "2026-06-20T00:00:00.000Z",
290 },
291 }).pipe(Effect.flip);
292​
293 assert.isTrue(isServerRuntimeStateError(error));
294 if (isServerRuntimeStateError(error)) {
295 assert.equal(error.operation, "persist");
296 assert.equal(error.statePath, statePath);
297 assert.equal(error.message, `Failed to persist server runtime state at ${statePath}.`);
298 assert.deepInclude(error.cause, { _tag: "PlatformError" });
299 }
300 }).pipe(Effect.provide(NodeServices.layer)),
301 );
302});