Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import { SERVER_EXIT_CODE_STATE_DIR_OWNED } from "@t3tools/contracts";
4import { vi } from "vite-plus/test";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8
9import { Launcher, readServiceState, writeServiceState } from "./serviceLauncher.ts";
10import * as ServerOwnershipLock from "./serverOwnershipLock.ts";
11import * as ServerRuntimeState from "./serverRuntimeState.ts";
12import {
13 compareExactServiceVersions,
14 decodeServiceState,
15 isExactServiceVersion,
16 SERVICE_LAUNCHER_PROTOCOL,
17 SERVICE_RESTART_PENDING_FILE,
18 SERVICE_STOP_MARKER_FILE,
19} from "./cloud/serviceProtocol.ts";
20
21it("accepts only exact semantic versions", () => {
22 for (const version of ["0.0.0", "1.2.3", "1.2.3-alpha.1", "1.2.3-0", "1.2.3+001"]) {
23 assert.isTrue(isExactServiceVersion(version), version);
24 }
25 for (const version of ["latest", "01.2.3", "1.2.3-01", "1.2.3-alpha..1", "1.2.3+."]) {
26 assert.isFalse(isExactServiceVersion(version), version);
27 }
28});
29
30it("orders exact semantic versions without treating build metadata as precedence", () => {
31 assert.equal(compareExactServiceVersions("1.2.3", "1.2.3"), 0);
32 assert.equal(compareExactServiceVersions("1.2.4", "1.2.3"), 1);
33 assert.equal(compareExactServiceVersions("2.0.0-alpha.1", "2.0.0-alpha.2"), -1);
34 assert.equal(compareExactServiceVersions("2.0.0-alpha.2", "2.0.0-alpha.beta"), -1);
35 assert.equal(compareExactServiceVersions("2.0.0-alpha-beta", "2.0.0-alpha-alpha"), 1);
36 assert.equal(compareExactServiceVersions("2.0.0", "2.0.0-rc.1"), 1);
37 assert.equal(compareExactServiceVersions("2.0.0+one", "2.0.0+two"), 0);
38});
39
40it("rejects contradictory service state", () => {
41 assert.isUndefined(
42 decodeServiceState({
43 protocol: SERVICE_LAUNCHER_PROTOCOL,
44 activeVersion: "0.0.31",
45 update: {
46 id: "update-1",
47 fromVersion: "0.0.30",
48 targetVersion: "0.0.32",
49 dbPath: "/tmp/state.sqlite",
50 status: "pending",
51 },
52 }),
53 );
54
55 assert.isUndefined(
56 decodeServiceState({
57 protocol: SERVICE_LAUNCHER_PROTOCOL,
58 activeVersion: "1.0.0",
59 update: {
60 id: "update-3",
61 fromVersion: "1.0.0",
62 targetVersion: "1.1.0",
63 status: "pending",
64 },
65 }),
66 );
67
68 assert.isUndefined(
69 decodeServiceState({
70 protocol: SERVICE_LAUNCHER_PROTOCOL,
71 activeVersion: "1.0.0",
72 update: {
73 id: "update-2",
74 fromVersion: "1.0.0",
75 targetVersion: "0.9.0",
76 dbPath: "/tmp/state.sqlite",
77 status: "pending",
78 },
79 }),
80 );
81});
82
83// A pinned runtime is an executable at <versionDir>/t3. The tests stand one up
84// as a Node shebang script so the launcher spawns it the way it spawns the
85// real single-executable, IPC channel included.
86const writeFakeRuntime = (
87 fs: FileSystem.FileSystem,
88 path: Path.Path,
89 versionDir: string,
90 childSource: string,
91) =>
92 Effect.gen(function* () {
93 const entryPath = path.join(versionDir, "t3");
94 yield* fs.makeDirectory(versionDir, { recursive: true });
95 yield* fs.writeFileString(entryPath, `#!${process.execPath}\n${childSource}`);
96 yield* fs.chmod(entryPath, 0o755);
97 yield* fs.writeFileString(
98 path.join(versionDir, ".install-complete"),
99 `${path.basename(versionDir)}\n`,
100 );
101 return entryPath;
102 });
103
104it.layer(NodeServices.layer)("service state persistence", (it) => {
105 it.effect("parks on ownership refusal until explicitly stopped instead of restarting", () =>
106 Effect.gen(function* () {
107 const fs = yield* FileSystem.FileSystem;
108 const path = yield* Path.Path;
109 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-refused-" });
110 const statePath = path.join(root, "runtime", "service-state.json");
111 yield* writeFakeRuntime(
112 fs,
113 path,
114 path.join(root, "runtime", "versions", "1.0.0"),
115 `process.exit(${SERVER_EXIT_CODE_STATE_DIR_OWNED});\n`,
116 );
117 yield* Effect.promise(() =>
118 writeServiceState(statePath, {
119 protocol: SERVICE_LAUNCHER_PROTOCOL,
120 activeVersion: "1.0.0",
121 }),
122 );
123 const refused = Promise.withResolvers<void>();
124 yield* Effect.acquireRelease(
125 Effect.sync(() =>
126 vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
127 if (String(chunk).includes("waiting for a service restart")) refused.resolve();
128 return true;
129 }),
130 ),
131 (spy) => Effect.sync(() => spy.mockRestore()),
132 );
133 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
134 let completed = false;
135 const running = launcher.run().finally(() => {
136 completed = true;
137 });
138 yield* Effect.addFinalizer(() => Effect.promise(() => launcher.stop("SIGTERM")));
139 yield* Effect.promise(() => refused.promise);
140 assert.isFalse(completed);
141 yield* Effect.promise(() => launcher.stop("SIGTERM"));
142 yield* Effect.promise(() => running);
143 assert.isTrue(completed);
144 }),
145 );
146
147 it.effect("refuses backup and interrupted restore beside a live database owner", () =>
148 Effect.gen(function* () {
149 const fs = yield* FileSystem.FileSystem;
150 const path = yield* Path.Path;
151 for (const [recovery, ownerKind] of [
152 ["backup", "locked"],
153 ["restore", "locked"],
154 ["backup", "legacy"],
155 ["restore", "legacy"],
156 ["backup", "released"],
157 ] as const) {
158 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-owned-" });
159 const statePath = path.join(root, "runtime", "service-state.json");
160 const databasePath = path.join(root, "userdata", "state.sqlite");
161 const backupDir = path.join(root, "runtime", "db-backup", "owned-update");
162 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
163 yield* fs.writeFileString(databasePath, "live database");
164 yield* fs.writeFileString(`${databasePath}-wal`, "live wal");
165 yield* writeFakeRuntime(
166 fs,
167 path,
168 path.join(root, "runtime", "versions", "1.1.0"),
169 'throw new Error("Recovery must not start a trial beside the live owner");\n',
170 );
171 const hasBackup = recovery === "restore" || ownerKind === "released";
172 if (hasBackup) {
173 yield* fs.makeDirectory(backupDir, { recursive: true });
174 yield* fs.writeFileString(path.join(backupDir, "database"), "older backup");
175 if (recovery === "restore") {
176 yield* fs.writeFileString(path.join(backupDir, ".restore-pending"), "");
177 }
178 }
179 yield* Effect.promise(() =>
180 writeServiceState(statePath, {
181 protocol: SERVICE_LAUNCHER_PROTOCOL,
182 activeVersion: "1.0.0",
183 update: {
184 id: "owned-update",
185 fromVersion: "1.0.0",
186 targetVersion: "1.1.0",
187 dbPath: databasePath,
188 status: "pending",
189 },
190 }),
191 );
192 yield* Effect.scoped(
193 Effect.gen(function* () {
194 if (ownerKind === "locked") {
195 yield* Effect.acquireRelease(
196 Effect.promise(() =>
197 ServerOwnershipLock.acquireServerOwnershipLock(path.dirname(databasePath)),
198 ),
199 (lock) => Effect.sync(() => lock.close()),
200 );
201 } else if (ownerKind === "released") {
202 const acquire = ServerOwnershipLock.acquireServerOwnershipLock;
203 const foreignOwner = yield* Effect.promise(() => acquire(path.dirname(databasePath)));
204 let released = false;
205 yield* Effect.addFinalizer(() =>
206 Effect.sync(() => {
207 if (!released) foreignOwner.close();
208 }),
209 );
210 yield* Effect.acquireRelease(
211 Effect.sync(() =>
212 vi
213 .spyOn(ServerOwnershipLock, "acquireServerOwnershipLock")
214 .mockImplementationOnce(async (...args) => {
215 try {
216 return await acquire(...args);
217 } finally {
218 // Real contention occurs, then ownership ends before
219 // the launcher can attempt an unsafe second acquire.
220 foreignOwner.close();
221 released = true;
222 }
223 }),
224 ),
225 (spy) => Effect.sync(() => spy.mockRestore()),
226 );
227 } else {
228 yield* ServerRuntimeState.persistServerRuntimeState({
229 path: path.join(path.dirname(databasePath), "server-runtime.json"),
230 state: yield* ServerRuntimeState.makePersistedServerRuntimeState({
231 config: { host: undefined, devUrl: undefined },
232 port: 3773,
233 }),
234 });
235 }
236 const refused = Promise.withResolvers<void>();
237 yield* Effect.acquireRelease(
238 Effect.sync(() =>
239 vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
240 if (String(chunk).includes("waiting for a service restart")) refused.resolve();
241 return true;
242 }),
243 ),
244 (spy) => Effect.sync(() => spy.mockRestore()),
245 );
246 const launcher = new Launcher(
247 root,
248 yield* Effect.promise(() => readServiceState(statePath)),
249 );
250 const running = launcher.run();
251 yield* Effect.addFinalizer(() => Effect.promise(() => launcher.stop("SIGTERM")));
252 yield* Effect.promise(() =>
253 Promise.race([refused.promise, running.catch(() => undefined)]),
254 );
255 assert.equal(yield* fs.readFileString(databasePath), "live database");
256 const cancelled = yield* Effect.promise(() => readServiceState(statePath));
257 assert.equal(cancelled.update?.status, "failed");
258 assert.equal(
259 cancelled.update?.status === "failed" ? cancelled.update.reason : undefined,
260 "state-dir-owned",
261 );
262 assert.equal(yield* fs.readFileString(databasePath), "live database");
263 assert.equal(yield* fs.readFileString(`${databasePath}-wal`), "live wal");
264 assert.equal(yield* fs.exists(backupDir), hasBackup);
265 assert.isFalse(yield* fs.exists(`${backupDir}.staging`));
266 yield* Effect.promise(() => launcher.stop("SIGTERM"));
267 yield* Effect.promise(() => running);
268 }),
269 );
270
271 // Simulate accepted foreign work before its owner stops. An explicit
272 // service restart must discard the cancelled snapshot, never restore it.
273 yield* fs.writeFileString(databasePath, "foreign owner's accepted writes");
274 yield* fs.remove(path.join(path.dirname(databasePath), "server-runtime.json"), {
275 force: true,
276 });
277 yield* writeFakeRuntime(
278 fs,
279 path,
280 path.join(root, "runtime", "versions", "1.0.0"),
281 "process.exit(1);\n",
282 );
283 const restarted = new Launcher(
284 root,
285 yield* Effect.promise(() => readServiceState(statePath)),
286 );
287 yield* Effect.tryPromise(() => restarted.run()).pipe(Effect.flip);
288 assert.equal(yield* fs.readFileString(databasePath), "foreign owner's accepted writes");
289 assert.isFalse(yield* fs.exists(backupDir));
290 }
291 }),
292 );
293
294 it.effect("durably replaces and strictly reads one state document", () =>
295 Effect.gen(function* () {
296 const fs = yield* FileSystem.FileSystem;
297 const path = yield* Path.Path;
298 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-test-" });
299 const statePath = path.join(root, "runtime", "service-state.json");
300 const state = {
301 protocol: SERVICE_LAUNCHER_PROTOCOL,
302 activeVersion: "0.0.31",
303 } as const;
304
305 yield* Effect.promise(() => writeServiceState(statePath, state));
306 assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), state);
307 }),
308 );
309
310 it.effect("a fresh launcher clears a restart deferred by t3 update", () =>
311 Effect.gen(function* () {
312 const fs = yield* FileSystem.FileSystem;
313 const path = yield* Path.Path;
314 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-restart-" });
315 const statePath = path.join(root, "runtime", "service-state.json");
316 const restartPending = path.join(root, "runtime", SERVICE_RESTART_PENDING_FILE);
317 yield* writeFakeRuntime(
318 fs,
319 path,
320 path.join(root, "runtime", "versions", "1.0.0"),
321 "setInterval(() => {}, 1_000);\n",
322 );
323 yield* Effect.promise(() =>
324 writeServiceState(statePath, {
325 protocol: SERVICE_LAUNCHER_PROTOCOL,
326 activeVersion: "1.0.0",
327 }),
328 );
329 const run = () =>
330 Effect.gen(function* () {
331 const launcher = new Launcher(
332 root,
333 yield* Effect.promise(() => readServiceState(statePath)),
334 );
335 const running = launcher.run();
336 yield* Effect.promise(() => launcher.stop("SIGTERM"));
337 yield* Effect.promise(() => running);
338 });
339
340 // A launcher that is still the old version leaves a marker that waits
341 // for a newer one.
342 yield* fs.writeFileString(restartPending, "1.0.1\n");
343 yield* run();
344 assert.isTrue(yield* fs.exists(restartPending));
345
346 // Whoever restarted the service, the launcher now runs what the unit
347 // names, so the deferred-restart marker is gone.
348 yield* fs.writeFileString(restartPending, "1.0.0\n");
349 yield* run();
350 assert.isFalse(yield* fs.exists(restartPending));
351 }),
352 );
353
354 it.effect("serializes shutdown with launcher recovery", () =>
355 Effect.gen(function* () {
356 const fs = yield* FileSystem.FileSystem;
357 const path = yield* Path.Path;
358 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-stop-" });
359 const statePath = path.join(root, "runtime", "service-state.json");
360 yield* writeFakeRuntime(
361 fs,
362 path,
363 path.join(root, "runtime", "versions", "1.0.0"),
364 "setInterval(() => {}, 1_000);\n",
365 );
366 yield* Effect.promise(() =>
367 writeServiceState(statePath, {
368 protocol: SERVICE_LAUNCHER_PROTOCOL,
369 activeVersion: "1.0.0",
370 }),
371 );
372
373 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
374 const running = launcher.run();
375 const stopping = launcher.stop("SIGTERM");
376 // An explicit stop leaves the marker that tells a child shutting down
377 // mid-update that no replacement server is coming. It is present as
378 // soon as stop() returns its promise, before queued transitions run.
379 assert.isTrue(yield* fs.exists(path.join(root, "runtime", SERVICE_STOP_MARKER_FILE)));
380 yield* Effect.promise(() => stopping);
381 yield* Effect.promise(() => running);
382 }),
383 );
384
385 it.effect("commits only after the trial reports prepared", () =>
386 Effect.gen(function* () {
387 const fs = yield* FileSystem.FileSystem;
388 const path = yield* Path.Path;
389 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-flow-" });
390 const statePath = path.join(root, "runtime", "service-state.json");
391 const databasePath = path.join(root, "userdata", "state.sqlite");
392 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
393 yield* fs.writeFileString(databasePath, "before trial");
394 // @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
395 const encodedDatabasePath = JSON.stringify(databasePath);
396 const childSource = `
397const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
398if (context.update?.status === "pending") {
399 process.send({ type: "prepared", updateId: context.update.id });
400 process.on("message", (message) => {
401 if (message.type === "committed") process.exit(0);
402 });
403} else if (context.update === undefined) {
404 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
405 setInterval(() => {}, 1_000);
406} else {
407 process.exit(0);
408}
409`;
410 for (const version of ["1.0.0", "1.1.0"]) {
411 yield* writeFakeRuntime(
412 fs,
413 path,
414 path.join(root, "runtime", "versions", version),
415 childSource,
416 );
417 }
418 yield* Effect.promise(() =>
419 writeServiceState(statePath, {
420 protocol: SERVICE_LAUNCHER_PROTOCOL,
421 activeVersion: "1.0.0",
422 }),
423 );
424
425 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
426 yield* Effect.promise(() =>
427 launcher.run().then(
428 () => Promise.reject(new Error("launcher unexpectedly completed")),
429 () => Promise.resolve(),
430 ),
431 );
432
433 const state = yield* Effect.promise(() => readServiceState(statePath));
434 assert.equal(state.activeVersion, "1.1.0");
435 assert.equal(state.update?.status, "committed");
436 }),
437 );
438
439 it.effect("rolls back a trial that reports the wrong update ID", () =>
440 Effect.gen(function* () {
441 const fs = yield* FileSystem.FileSystem;
442 const path = yield* Path.Path;
443 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
444 const statePath = path.join(root, "runtime", "service-state.json");
445 const databasePath = path.join(root, "userdata", "state.sqlite");
446 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
447 yield* fs.writeFileString(databasePath, "before trial");
448 // @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
449 const encodedDatabasePath = JSON.stringify(databasePath);
450 const childSource = `
451const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
452if (context.update?.status === "pending") {
453 process.send({ type: "prepared", updateId: "wrong-update" });
454} else if (context.update === undefined) {
455 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
456 setInterval(() => {}, 1_000);
457} else {
458 process.exit(0);
459}
460`;
461 for (const version of ["1.0.0", "1.1.0"]) {
462 yield* writeFakeRuntime(
463 fs,
464 path,
465 path.join(root, "runtime", "versions", version),
466 childSource,
467 );
468 }
469 yield* Effect.promise(() =>
470 writeServiceState(statePath, {
471 protocol: SERVICE_LAUNCHER_PROTOCOL,
472 activeVersion: "1.0.0",
473 }),
474 );
475
476 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
477 yield* Effect.promise(() =>
478 launcher.run().then(
479 () => Promise.reject(new Error("launcher unexpectedly completed")),
480 () => Promise.resolve(),
481 ),
482 );
483
484 const state = yield* Effect.promise(() => readServiceState(statePath));
485 assert.equal(state.activeVersion, "1.0.0");
486 assert.equal(state.update?.status, "rolled-back");
487 assert.equal(
488 state.update?.status === "rolled-back" ? state.update.reason : undefined,
489 "invalid-prepared",
490 );
491 }),
492 );
493
494 it.effect("restores the database when a migrating trial exits", () =>
495 Effect.gen(function* () {
496 const fs = yield* FileSystem.FileSystem;
497 const path = yield* Path.Path;
498 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-db-" });
499 const statePath = path.join(root, "runtime", "service-state.json");
500 const databasePath = path.join(root, "userdata", "state.sqlite");
501 const original = "database before migration";
502 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
503 yield* fs.writeFileString(databasePath, original);
504 // @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
505 const encodedDatabasePath = JSON.stringify(databasePath);
506 const childSource = `
507import { writeFileSync } from "node:fs";
508const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
509if (context.update?.status === "pending") {
510 writeFileSync(context.update.dbPath, "database after migration");
511 writeFileSync(context.update.dbPath + "-wal", "trial wal");
512 writeFileSync(context.update.dbPath + "-shm", "trial shm");
513 process.exit(1);
514} else if (context.update === undefined) {
515 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
516 setInterval(() => {}, 1_000);
517} else {
518 process.exit(0);
519}
520`;
521 for (const version of ["1.0.0", "1.1.0"]) {
522 yield* writeFakeRuntime(
523 fs,
524 path,
525 path.join(root, "runtime", "versions", version),
526 childSource,
527 );
528 }
529 yield* Effect.promise(() =>
530 writeServiceState(statePath, {
531 protocol: SERVICE_LAUNCHER_PROTOCOL,
532 activeVersion: "1.0.0",
533 }),
534 );
535
536 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
537 yield* Effect.promise(() =>
538 launcher.run().then(
539 () => Promise.reject(new Error("launcher unexpectedly completed")),
540 () => Promise.resolve(),
541 ),
542 );
543
544 const state = yield* Effect.promise(() => readServiceState(statePath));
545 assert.equal(state.activeVersion, "1.0.0");
546 assert.equal(state.update?.status, "rolled-back");
547 assert.equal(yield* fs.readFileString(databasePath), original);
548 assert.isFalse(yield* fs.exists(`${databasePath}-wal`));
549 assert.isFalse(yield* fs.exists(`${databasePath}-shm`));
550 const updateId = state.update?.id;
551 assert.isDefined(updateId);
552 assert.isFalse(yield* fs.exists(path.join(root, "runtime", "db-backup", updateId)));
553 }),
554 );
555});