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

serviceLauncher.test.ts

889 lines34.5 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off - observes the children the launcher spawns with Node built-ins.
2import type * as NodeChildProcess from "node:child_process";
3​
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { assert, it } from "@effect/vitest";
6import { SERVER_EXIT_CODE_STATE_DIR_OWNED } from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as NodeSqlite from "node:sqlite";
11// @effect-diagnostics-next-line nodeBuiltinImport:off - injects staging failures into the standalone Node backup helper.
12import * as NodeFSP from "node:fs/promises";
13import { prepareServiceDatabaseBackup } from "./serviceDatabaseBackup.ts";
14import { expect, vi } from "vite-plus/test";
15​
16import {
17 databaseBackupBlocker,
18 Launcher,
19 PREPARED_TIMEOUT_MS,
20 type BackupSpaceProbe,
21 readServiceState,
22 writeServiceState,
23} from "./serviceLauncher.ts";
24import {
25 compareExactServiceVersions,
26 decodeServiceState,
27 isExactServiceVersion,
28 SERVICE_LAUNCHER_PROTOCOL,
29 SERVICE_RESTART_PENDING_FILE,
30 SERVICE_STOP_MARKER_FILE,
31} from "./cloud/serviceProtocol.ts";
32​
33const spawnedChildren = vi.hoisted((): Array<NodeChildProcess.ChildProcess> => []);
34​
35vi.mock("node:fs/promises", { spy: true });
36​
37vi.mock("node:child_process", async (importOriginal) => {
38 const actual = await importOriginal<typeof NodeChildProcess>();
39 const spawn = (...args: Parameters<typeof actual.spawn>) => {
40 const child = actual.spawn(...args);
41 spawnedChildren.push(child);
42 return child;
43 };
44 return { ...actual, spawn: spawn as typeof actual.spawn };
45});
46​
47const writeSparseFile = (filePath: string, size: number) =>
48 Effect.gen(function* () {
49 const fileSystem = yield* FileSystem.FileSystem;
50 yield* fileSystem.writeFileString(filePath, "");
51 yield* fileSystem.truncate(filePath, size);
52 });
53​
54it("accepts only exact semantic versions", () => {
55 for (const version of ["0.0.0", "1.2.3", "1.2.3-alpha.1", "1.2.3-0", "1.2.3+001"]) {
56 assert.isTrue(isExactServiceVersion(version), version);
57 }
58 for (const version of ["latest", "01.2.3", "1.2.3-01", "1.2.3-alpha..1", "1.2.3+."]) {
59 assert.isFalse(isExactServiceVersion(version), version);
60 }
61});
62​
63it("orders exact semantic versions without treating build metadata as precedence", () => {
64 assert.equal(compareExactServiceVersions("1.2.3", "1.2.3"), 0);
65 assert.equal(compareExactServiceVersions("1.2.4", "1.2.3"), 1);
66 assert.equal(compareExactServiceVersions("2.0.0-alpha.1", "2.0.0-alpha.2"), -1);
67 assert.equal(compareExactServiceVersions("2.0.0-alpha.2", "2.0.0-alpha.beta"), -1);
68 assert.equal(compareExactServiceVersions("2.0.0-alpha-beta", "2.0.0-alpha-alpha"), 1);
69 assert.equal(compareExactServiceVersions("2.0.0", "2.0.0-rc.1"), 1);
70 assert.equal(compareExactServiceVersions("2.0.0+one", "2.0.0+two"), 0);
71});
72​
73it("rejects contradictory service state", () => {
74 assert.isUndefined(
75 decodeServiceState({
76 protocol: SERVICE_LAUNCHER_PROTOCOL,
77 activeVersion: "0.0.31",
78 update: {
79 id: "update-1",
80 fromVersion: "0.0.30",
81 targetVersion: "0.0.32",
82 dbPath: "/tmp/state.sqlite",
83 status: "pending",
84 },
85 }),
86 );
87​
88 assert.isUndefined(
89 decodeServiceState({
90 protocol: SERVICE_LAUNCHER_PROTOCOL,
91 activeVersion: "1.0.0",
92 update: {
93 id: "update-3",
94 fromVersion: "1.0.0",
95 targetVersion: "1.1.0",
96 status: "pending",
97 },
98 }),
99 );
100​
101 assert.isUndefined(
102 decodeServiceState({
103 protocol: SERVICE_LAUNCHER_PROTOCOL,
104 activeVersion: "1.0.0",
105 update: {
106 id: "update-2",
107 fromVersion: "1.0.0",
108 targetVersion: "0.9.0",
109 dbPath: "/tmp/state.sqlite",
110 status: "pending",
111 },
112 }),
113 );
114});
115​
116const writeFakeRuntime = (
117 fs: FileSystem.FileSystem,
118 path: Path.Path,
119 versionDir: string,
120 childSource: string,
121) =>
122 Effect.gen(function* () {
123 const entryPath = path.join(versionDir, "t3");
124 yield* fs.makeDirectory(versionDir, { recursive: true });
125 yield* fs.writeFileString(entryPath, `#!${process.execPath}\n${childSource}`);
126 yield* fs.chmod(entryPath, 0o755);
127 yield* fs.writeFileString(
128 path.join(versionDir, ".install-complete"),
129 `${path.basename(versionDir)}\n`,
130 );
131 return entryPath;
132 });
133​
134it.layer(NodeServices.layer)("service state persistence", (it) => {
135 it.effect.each([
136 { operation: "rm", code: "ENOTDIR" },
137 { operation: "mkdir", code: "EACCES" },
138 ] as const)(
139 "online backup releases its WAL reader when staging $operation fails",
140 ({ operation, code }) =>
141 Effect.gen(function* () {
142 const fs = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-backup-staging-" });
145 const sourcePath = path.join(root, "source.sqlite");
146 const writer = yield* Effect.acquireRelease(
147 Effect.sync(() => new NodeSqlite.DatabaseSync(sourcePath)),
148 (db) => Effect.sync(() => db.close()),
149 );
150 writer.exec(
151 "PRAGMA journal_mode=WAL; CREATE TABLE records(value TEXT); INSERT INTO records VALUES('before'); PRAGMA wal_checkpoint(TRUNCATE)",
152 );
153 assert.equal(writer.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()?.busy, 0);
154 yield* Effect.promise(async () => {
155 const failure = Object.assign(new Error(`staging ${operation} failed`), { code });
156 const setup = vi.mocked(NodeFSP[operation]).mockRejectedValueOnce(failure);
157 try {
158 await expect(
159 prepareServiceDatabaseBackup(sourcePath, path.join(root, "backup")),
160 ).rejects.toMatchObject({ code });
161 } finally {
162 setup.mockRestore();
163 }
164 });
165 writer.exec("INSERT INTO records VALUES('after')");
166 assert.equal(writer.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()?.busy, 0);
167 }),
168 );
169​
170 it.effect("online update backups retain acknowledged writes after the snapshot", () =>
171 Effect.gen(function* () {
172 const fs = yield* FileSystem.FileSystem;
173 const path = yield* Path.Path;
174 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-online-backup-" });
175 const sourcePath = path.join(root, "source.sqlite");
176 const writer = yield* Effect.acquireRelease(
177 Effect.sync(() => new NodeSqlite.DatabaseSync(sourcePath)),
178 (db) => Effect.sync(() => db.close()),
179 );
180 writer.exec(
181 "PRAGMA journal_mode=WAL; CREATE TABLE records(id INTEGER PRIMARY KEY, value TEXT); INSERT INTO records VALUES(1,'before'); PRAGMA wal_checkpoint(TRUNCATE)",
182 );
183 const prepared = yield* Effect.acquireRelease(
184 Effect.tryPromise(async () => {
185 const backup = await prepareServiceDatabaseBackup(sourcePath, path.join(root, "backup"));
186 if (backup === undefined) throw new Error("A WAL database is copied online.");
187 return backup;
188 }),
189 (backup) => Effect.sync(() => backup.close()),
190 );
191 writer.exec(
192 "UPDATE records SET value='acknowledged'; INSERT INTO records VALUES(2,'after'); CREATE TABLE later(id INTEGER)",
193 );
194 assert.equal(writer.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()?.busy, 1);
195 yield* Effect.tryPromise(() => prepared.finish());
196 const restored = yield* Effect.acquireRelease(
197 Effect.sync(() => new NodeSqlite.DatabaseSync(path.join(root, "backup", "database"))),
198 (db) => Effect.sync(() => db.close()),
199 );
200 assert.deepEqual(
201 restored
202 .prepare("SELECT * FROM records ORDER BY id")
203 .all()
204 .map((row) => ({ ...row })),
205 [
206 { id: 1, value: "acknowledged" },
207 { id: 2, value: "after" },
208 ],
209 );
210 assert.equal(restored.prepare("PRAGMA integrity_check").get()?.integrity_check, "ok");
211 assert.equal(restored.prepare("SELECT COUNT(*) AS n FROM later").get()?.n, 0);
212 }),
213 );
214 it.effect("durably replaces and strictly reads one state document", () =>
215 Effect.gen(function* () {
216 const fs = yield* FileSystem.FileSystem;
217 const path = yield* Path.Path;
218 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-test-" });
219 const statePath = path.join(root, "runtime", "service-state.json");
220 const state = {
221 protocol: SERVICE_LAUNCHER_PROTOCOL,
222 activeVersion: "0.0.31",
223 } as const;
224​
225 yield* Effect.promise(() => writeServiceState(statePath, state));
226 assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), state);
227 }),
228 );
229​
230 it.effect("a fresh launcher clears a restart deferred by t3 update", () =>
231 Effect.gen(function* () {
232 const fs = yield* FileSystem.FileSystem;
233 const path = yield* Path.Path;
234 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-restart-" });
235 const statePath = path.join(root, "runtime", "service-state.json");
236 const restartPending = path.join(root, "runtime", SERVICE_RESTART_PENDING_FILE);
237 yield* writeFakeRuntime(
238 fs,
239 path,
240 path.join(root, "runtime", "versions", "1.0.0"),
241 "setInterval(() => {}, 1_000);\n",
242 );
243 yield* Effect.promise(() =>
244 writeServiceState(statePath, {
245 protocol: SERVICE_LAUNCHER_PROTOCOL,
246 activeVersion: "1.0.0",
247 }),
248 );
249 const run = () =>
250 Effect.gen(function* () {
251 const launcher = new Launcher(
252 root,
253 yield* Effect.promise(() => readServiceState(statePath)),
254 );
255 const running = launcher.run();
256 yield* Effect.promise(() => launcher.stop("SIGTERM"));
257 yield* Effect.promise(() => running);
258 });
259​
260 yield* fs.writeFileString(restartPending, "1.0.1\n");
261 yield* run();
262 assert.isTrue(yield* fs.exists(restartPending));
263​
264 yield* fs.writeFileString(restartPending, "1.0.0\n");
265 yield* run();
266 assert.isFalse(yield* fs.exists(restartPending));
267 }),
268 );
269​
270 it.effect("stays idle instead of exiting when another server owns the T3 home", () =>
271 Effect.gen(function* () {
272 const fs = yield* FileSystem.FileSystem;
273 const path = yield* Path.Path;
274 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-refused-" });
275 const statePath = path.join(root, "runtime", "service-state.json");
276 yield* writeFakeRuntime(
277 fs,
278 path,
279 path.join(root, "runtime", "versions", "1.0.0"),
280 `process.exit(${SERVER_EXIT_CODE_STATE_DIR_OWNED});\n`,
281 );
282 yield* Effect.promise(() =>
283 writeServiceState(statePath, {
284 protocol: SERVICE_LAUNCHER_PROTOCOL,
285 activeVersion: "1.0.0",
286 }),
287 );
288 const refused = Promise.withResolvers<void>();
289 yield* Effect.acquireRelease(
290 Effect.sync(() =>
291 vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
292 if (String(chunk).includes("owns this T3 home")) refused.resolve();
293 return true;
294 }),
295 ),
296 (spy) => Effect.sync(() => spy.mockRestore()),
297 );
298 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
299 let completed = false;
300 const running = launcher.run().finally(() => {
301 completed = true;
302 });
303 yield* Effect.promise(() => refused.promise);
304 assert.isFalse(completed);
305 yield* Effect.promise(() => launcher.stop("SIGTERM"));
306 yield* Effect.promise(() => running);
307 }),
308 );
309​
310 it.effect("serializes shutdown with launcher recovery", () =>
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-stop-" });
315 const statePath = path.join(root, "runtime", "service-state.json");
316 const stagingDir = path.join(root, "runtime", "db-backup", "failed-online-backup.staging");
317 yield* fs.makeDirectory(stagingDir, { recursive: true });
318 yield* fs.writeFileString(path.join(stagingDir, "database"), "incomplete online backup");
319 yield* writeFakeRuntime(
320 fs,
321 path,
322 path.join(root, "runtime", "versions", "1.0.0"),
323 "setInterval(() => {}, 1_000);\n",
324 );
325 yield* Effect.promise(() =>
326 writeServiceState(statePath, {
327 protocol: SERVICE_LAUNCHER_PROTOCOL,
328 activeVersion: "1.0.0",
329 update: {
330 id: "failed-online-backup",
331 fromVersion: "1.0.0",
332 targetVersion: "1.1.0",
333 status: "failed",
334 },
335 }),
336 );
337​
338 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
339 const running = launcher.run();
340 const stopping = launcher.stop("SIGTERM");
341 assert.isTrue(yield* fs.exists(path.join(root, "runtime", SERVICE_STOP_MARKER_FILE)));
342 yield* Effect.promise(() => stopping);
343 yield* Effect.promise(() => running);
344 assert.isFalse(yield* fs.exists(stagingDir));
345 }),
346 );
347​
348 it.effect("commits only after the trial reports prepared", () =>
349 Effect.gen(function* () {
350 const fs = yield* FileSystem.FileSystem;
351 const path = yield* Path.Path;
352 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-flow-" });
353 const statePath = path.join(root, "runtime", "service-state.json");
354 const databasePath = path.join(root, "userdata", "state.sqlite");
355 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
356 yield* fs.writeFileString(databasePath, "before trial");
357 const encodedDatabasePath = JSON.stringify(databasePath);
358 const childSource = `
359const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
360if (context.update?.status === "pending") {
361 process.send({ type: "prepared", updateId: context.update.id });
362 process.on("message", (message) => {
363 if (message.type === "committed") process.exit(0);
364 });
365} else if (context.update === undefined) {
366 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
367 setInterval(() => {}, 1_000);
368} else {
369 process.exit(0);
371`;
372 for (const version of ["1.0.0", "1.1.0"]) {
373 yield* writeFakeRuntime(
374 fs,
375 path,
376 path.join(root, "runtime", "versions", version),
377 childSource,
378 );
379 }
380 yield* Effect.promise(() =>
381 writeServiceState(statePath, {
382 protocol: SERVICE_LAUNCHER_PROTOCOL,
383 activeVersion: "1.0.0",
384 }),
385 );
386​
387 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
388 yield* Effect.promise(() =>
389 launcher.run().then(
390 () => Promise.reject(new Error("launcher unexpectedly completed")),
391 () => Promise.resolve(),
392 ),
393 );
394​
395 const state = yield* Effect.promise(() => readServiceState(statePath));
396 assert.equal(state.activeVersion, "1.1.0");
397 assert.equal(state.update?.status, "committed");
398 }),
399 );
400​
401 it.effect("rolls back a trial that reports the wrong update ID", () =>
402 Effect.gen(function* () {
403 const fs = yield* FileSystem.FileSystem;
404 const path = yield* Path.Path;
405 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
406 const statePath = path.join(root, "runtime", "service-state.json");
407 const databasePath = path.join(root, "userdata", "state.sqlite");
408 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
409 yield* fs.writeFileString(databasePath, "before trial");
410 const encodedDatabasePath = JSON.stringify(databasePath);
411 const childSource = `
412const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
413if (context.update?.status === "pending") {
414 process.send({ type: "prepared", updateId: "wrong-update" });
415} else if (context.update === undefined) {
416 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
417 setInterval(() => {}, 1_000);
418} else {
419 process.exit(0);
421`;
422 for (const version of ["1.0.0", "1.1.0"]) {
423 yield* writeFakeRuntime(
424 fs,
425 path,
426 path.join(root, "runtime", "versions", version),
427 childSource,
428 );
429 }
430 yield* Effect.promise(() =>
431 writeServiceState(statePath, {
432 protocol: SERVICE_LAUNCHER_PROTOCOL,
433 activeVersion: "1.0.0",
434 }),
435 );
436​
437 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
438 yield* Effect.promise(() =>
439 launcher.run().then(
440 () => Promise.reject(new Error("launcher unexpectedly completed")),
441 () => Promise.resolve(),
442 ),
443 );
444​
445 const state = yield* Effect.promise(() => readServiceState(statePath));
446 assert.equal(state.activeVersion, "1.0.0");
447 assert.equal(state.update?.status, "rolled-back");
448 assert.equal(
449 state.update?.status === "rolled-back" ? state.update.reason : undefined,
450 "invalid-prepared",
451 );
452 }),
453 );
454​
455 it.effect("restores an online backup when a trial migration fails", () =>
456 Effect.gen(function* () {
457 const fs = yield* FileSystem.FileSystem;
458 const path = yield* Path.Path;
459 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-online-rollback-" });
460 const databasePath = path.join(root, "userdata", "state.sqlite");
461 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
462 const original = new NodeSqlite.DatabaseSync(databasePath);
463 original.exec(
464 "PRAGMA journal_mode=WAL; CREATE TABLE records(value TEXT); INSERT INTO records VALUES('before')",
465 );
466 original.close();
467 const childSource = `
468import { DatabaseSync } from "node:sqlite";
469const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
470if (context.update?.status === "pending") {
471 const db = new DatabaseSync(context.update.dbPath);
472 db.exec("CREATE TABLE trial_migration(id INTEGER); UPDATE records SET value='trial'");
473 db.close();
474 process.exit(1);
475} else if (context.update === undefined) {
476 process.send({type:"request-update",targetVersion:"1.1.0",dbPath:${JSON.stringify(databasePath)}});
477 setInterval(() => {}, 1000);
478} else process.exit(0);
479`;
480 for (const version of ["1.0.0", "1.1.0"]) {
481 yield* writeFakeRuntime(
482 fs,
483 path,
484 path.join(root, "runtime", "versions", version),
485 childSource,
486 );
487 }
488 const launcher = new Launcher(root, {
489 protocol: SERVICE_LAUNCHER_PROTOCOL,
490 activeVersion: "1.0.0",
491 });
492 yield* Effect.promise(() => launcher.run().catch(() => undefined));
493 const state = yield* Effect.promise(() =>
494 readServiceState(path.join(root, "runtime", "service-state.json")),
495 );
496 assert.equal(state.activeVersion, "1.0.0");
497 assert.equal(state.update?.status, "rolled-back");
498 const restored = new NodeSqlite.DatabaseSync(databasePath);
499 try {
500 assert.equal(restored.prepare("SELECT value FROM records").get()?.value, "before");
501 assert.equal(
502 restored
503 .prepare("SELECT COUNT(*) n FROM sqlite_schema WHERE name='trial_migration'")
504 .get()?.n,
505 0,
506 );
507 assert.equal(restored.prepare("PRAGMA integrity_check").get()?.integrity_check, "ok");
508 } finally {
509 restored.close();
510 }
511 }),
512 );
513​
514 // Migrations on a large database can keep a trial busy for minutes before it
515 // reports prepared. Only a trial that stays stuck past the window rolls back.
516 it.effect.each([
517 { prepares: true, status: "committed", activeVersion: "1.1.0" },
518 { prepares: false, status: "rolled-back", activeVersion: "1.0.0" },
519 ] as const)(
520 "gives a trial the full prepared window (prepares: $prepares)",
521 ({ prepares, status, activeVersion }) =>
522 Effect.gen(function* () {
523 const fs = yield* FileSystem.FileSystem;
524 const path = yield* Path.Path;
525 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-slow-" });
526 const statePath = path.join(root, "runtime", "service-state.json");
527 const databasePath = path.join(root, "userdata", "state.sqlite");
528 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
529 yield* fs.writeFileString(databasePath, "before trial");
530 const childSource = `
531const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
532if (context.update?.status !== "pending") process.exit(0);
533process.on("message", (message) => {
534 if (message.type === "test-prepare") process.send({ type: "prepared", updateId: context.update.id });
535 if (message.type === "committed") process.exit(0);
536});
537setInterval(() => {}, 1_000);
538`;
539 for (const version of ["1.0.0", "1.1.0"]) {
540 yield* writeFakeRuntime(
541 fs,
542 path,
543 path.join(root, "runtime", "versions", version),
544 childSource,
545 );
546 }
547 yield* Effect.promise(() =>
548 writeServiceState(statePath, {
549 protocol: SERVICE_LAUNCHER_PROTOCOL,
550 activeVersion: "1.0.0",
551 update: {
552 id: "update-1",
553 fromVersion: "1.0.0",
554 targetVersion: "1.1.0",
555 dbPath: databasePath,
556 status: "pending",
557 },
558 }),
559 );
560​
561 // Effect schedules on setImmediate, so faking only timeouts leaves it running.
562 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
563 yield* Effect.addFinalizer(() => Effect.sync(() => vi.useRealTimers()));
564 const launcher = new Launcher(
565 root,
566 yield* Effect.promise(() => readServiceState(statePath)),
567 );
568 const running = launcher.run().then(
569 () => Promise.reject(new Error("launcher unexpectedly completed")),
570 () => Promise.resolve(),
571 );
572 yield* Effect.promise(() =>
573 vi.waitFor(() => assert.equal(vi.getTimerCount(), 1), { timeout: 10_000 }),
574 );
575 yield* Effect.promise(() => vi.advanceTimersByTimeAsync(121_000));
576 if (prepares) spawnedChildren.at(-1)!.send({ type: "test-prepare" });
577 else yield* Effect.promise(() => vi.advanceTimersByTimeAsync(PREPARED_TIMEOUT_MS));
578 yield* Effect.promise(() => running);
579​
580 const state = yield* Effect.promise(() => readServiceState(statePath));
581 assert.equal(state.activeVersion, activeVersion);
582 assert.equal(state.update?.status, status);
583 if (!prepares) {
584 assert.equal(
585 state.update?.status === "rolled-back" ? state.update.reason : undefined,
586 "prepared-timeout",
587 );
588 }
589 }),
590 );
591​
592 it.effect.each(["file", "symlink", "dangling symlink"] as const)(
593 "restores the database when a migrating trial exits, with the database a %s",
594 (kind) =>
595 Effect.gen(function* () {
596 const fs = yield* FileSystem.FileSystem;
597 const path = yield* Path.Path;
598 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-db-" });
599 const statePath = path.join(root, "runtime", "service-state.json");
600 const databasePath = path.join(root, "userdata", "state.sqlite");
601 const databaseFile =
602 kind === "file" ? databasePath : path.join(root, "data", "original.sqlite");
603 const linkTarget = kind === "dangling symlink" ? "../original.sqlite" : databaseFile;
604 const original = "database before migration";
605 yield* fs.makeDirectory(path.dirname(databaseFile), { recursive: true });
606 if (kind === "dangling symlink") {
607 yield* fs.makeDirectory(path.join(root, "data", "sub"));
608 yield* fs.symlink(path.join(root, "data", "sub"), path.dirname(databasePath));
609 } else {
610 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
611 }
612 yield* fs.writeFileString(databaseFile, original);
613 if (kind !== "file") yield* fs.symlink(linkTarget, databasePath);
614 const encodedDatabasePath = JSON.stringify(databasePath);
615 const childSource = `
616import { realpathSync, unlinkSync, writeFileSync } from "node:fs";
617const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
618if (context.update?.status === "pending") {
619 writeFileSync(context.update.dbPath, "database after migration");
620 writeFileSync(context.update.dbPath + "-wal", "trial wal");
621 writeFileSync(context.update.dbPath + "-shm", "trial shm");
622 ${kind === "dangling symlink" ? "unlinkSync(realpathSync(context.update.dbPath));" : ""}
623 process.exit(1);
624} else if (context.update === undefined) {
625 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
626 setInterval(() => {}, 1_000);
627} else {
628 process.exit(0);
630`;
631 for (const version of ["1.0.0", "1.1.0"]) {
632 yield* writeFakeRuntime(
633 fs,
634 path,
635 path.join(root, "runtime", "versions", version),
636 childSource,
637 );
638 }
639 yield* Effect.promise(() =>
640 writeServiceState(statePath, {
641 protocol: SERVICE_LAUNCHER_PROTOCOL,
642 activeVersion: "1.0.0",
643 }),
644 );
645​
646 const launcher = new Launcher(
647 root,
648 yield* Effect.promise(() => readServiceState(statePath)),
649 );
650 yield* Effect.promise(() =>
651 launcher.run().then(
652 () => Promise.reject(new Error("launcher unexpectedly completed")),
653 () => Promise.resolve(),
654 ),
655 );
656​
657 const state = yield* Effect.promise(() => readServiceState(statePath));
658 assert.equal(state.activeVersion, "1.0.0");
659 assert.equal(state.update?.status, "rolled-back");
660 assert.equal(yield* fs.readFileString(databaseFile), original);
661 if (kind !== "file") assert.equal(yield* fs.readLink(databasePath), linkTarget);
662 assert.isFalse(yield* fs.exists(path.join(root, "original.sqlite")));
663 assert.isFalse(yield* fs.exists(`${databasePath}-wal`));
664 assert.isFalse(yield* fs.exists(`${databasePath}-shm`));
665 const updateId = state.update?.id;
666 assert.isDefined(updateId);
667 assert.isFalse(yield* fs.exists(path.join(root, "runtime", "db-backup", updateId)));
668 }),
669 );
670​
671 const requestRejectedUpdate = (backupSpaceProbe: Partial<BackupSpaceProbe>) =>
672 Effect.gen(function* () {
673 const fs = yield* FileSystem.FileSystem;
674 const path = yield* Path.Path;
675 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-space-" });
676 const statePath = path.join(root, "runtime", "service-state.json");
677 const databasePath = path.join(root, "userdata", "state.sqlite");
678 const replyPath = path.join(root, "rejection.txt");
679 const trialMarker = path.join(root, "trial-started");
680 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
681 yield* fs.writeFileString(databasePath, "database");
682 const encoded = JSON.stringify({ databasePath, replyPath, trialMarker });
683 const childSource = `
684import { writeFileSync } from "node:fs";
685const paths = ${encoded};
686const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
687if (context.update?.status === "pending") {
688 writeFileSync(paths.trialMarker, "started");
689 process.exit(1);
690} else if (context.update === undefined) {
691 process.on("message", (message) => {
692 if (message.type === "update-rejected") {
693 writeFileSync(paths.replyPath, message.reason);
694 process.exit(0);
695 }
696 });
697 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
698 setInterval(() => {}, 1_000);
699} else {
700 process.exit(0);
702`;
703 for (const version of ["1.0.0", "1.1.0"]) {
704 yield* writeFakeRuntime(
705 fs,
706 path,
707 path.join(root, "runtime", "versions", version),
708 childSource,
709 );
710 }
711 yield* Effect.promise(() =>
712 writeServiceState(statePath, {
713 protocol: SERVICE_LAUNCHER_PROTOCOL,
714 activeVersion: "1.0.0",
715 }),
716 );
717​
718 const launcher = new Launcher(
719 root,
720 yield* Effect.promise(() => readServiceState(statePath)),
721 { backupSpaceProbe },
722 );
723 yield* Effect.promise(() =>
724 launcher.run().then(
725 () => Promise.reject(new Error("launcher unexpectedly completed")),
726 () => Promise.resolve(),
727 ),
728 );
729​
730 return {
731 reason: yield* fs.readFileString(replyPath),
732 trialStarted: yield* fs.exists(trialMarker),
733 state: yield* Effect.promise(() => readServiceState(statePath)),
734 };
735 });
736​
737 it.effect("refuses a backup that cannot fit and leaves the server running", () =>
738 Effect.gen(function* () {
739 const { reason, trialStarted, state } = yield* requestRejectedUpdate({
740 readFreeBytes: () => Promise.resolve(0),
741 canClone: () => Promise.resolve(true),
742 });
743​
744 assert.include(reason, "Not enough free disk space");
745 assert.include(reason, "The server was not stopped");
746 assert.isFalse(trialStarted);
747 assert.equal(state.activeVersion, "1.0.0");
748 assert.isUndefined(state.update);
749 }),
750 );
751​
752 it.effect("refuses the update when free space cannot be checked", () =>
753 Effect.gen(function* () {
754 const { reason, trialStarted, state } = yield* requestRejectedUpdate({
755 readFreeBytes: () => Promise.reject(new Error("statfs unavailable")),
756 });
757​
758 assert.include(
759 reason,
760 "Could not check that the database backup fits before updating: statfs unavailable",
761 );
762 assert.isFalse(trialStarted);
763 assert.equal(state.activeVersion, "1.0.0");
764 assert.isUndefined(state.update);
765 }),
766 );
767​
768 it.effect("records no update when the server exits during the backup check", () =>
769 Effect.gen(function* () {
770 const fs = yield* FileSystem.FileSystem;
771 const path = yield* Path.Path;
772 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-exit-" });
773 const statePath = path.join(root, "runtime", "service-state.json");
774 const databasePath = path.join(root, "userdata", "state.sqlite");
775 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
776 yield* fs.writeFileString(databasePath, "database");
777 const encoded = JSON.stringify({ databasePath });
778 const childSource = `
779const paths = ${encoded};
780process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath }, () =>
781 process.exit(3),
782);
783setInterval(() => {}, 1_000);
784`;
785 for (const version of ["1.0.0", "1.1.0"]) {
786 yield* writeFakeRuntime(
787 fs,
788 path,
789 path.join(root, "runtime", "versions", version),
790 childSource,
791 );
792 }
793 yield* Effect.promise(() =>
794 writeServiceState(statePath, {
795 protocol: SERVICE_LAUNCHER_PROTOCOL,
796 activeVersion: "1.0.0",
797 }),
798 );
799 const launcher = new Launcher(
800 root,
801 yield* Effect.promise(() => readServiceState(statePath)),
802 {
803 backupSpaceProbe: {
804 readFreeBytes: () => {
805 const child = spawnedChildren.at(-1)!;
806 return new Promise((resolve) => {
807 if (!child.connected) resolve(Number.MAX_SAFE_INTEGER);
808 else child.once("disconnect", () => resolve(Number.MAX_SAFE_INTEGER));
809 });
810 },
811 },
812 },
813 );
814 const failure = yield* Effect.promise(() =>
815 launcher.run().then(
816 () => new Error("launcher unexpectedly completed"),
817 (cause: unknown) => cause as Error,
818 ),
819 );
820​
821 assert.include(failure.message, "Active child exited unexpectedly (3)");
822 const state = yield* Effect.promise(() => readServiceState(statePath));
823 assert.equal(state.activeVersion, "1.0.0");
824 assert.isUndefined(state.update);
825 }),
826 );
827​
828 it.effect("checks database backup space against clone or full-copy needs", () =>
829 Effect.gen(function* () {
830 const fs = yield* FileSystem.FileSystem;
831 const path = yield* Path.Path;
832 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-blocker-" });
833 const databasePath = path.join(root, "state.sqlite");
834 yield* writeSparseFile(databasePath, 10 * 1024 ** 3);
835 const check = (free: number, cloneable: boolean) =>
836 Effect.promise(() =>
837 databaseBackupBlocker(root, databasePath, {
838 readFreeBytes: () => Promise.resolve(free),
839 canClone: () => Promise.resolve(cloneable),
840 }),
841 );
842​
843 assert.isUndefined(yield* check(11 * 1024 ** 3, false));
844 assert.isUndefined(yield* check(1.5 * 1024 ** 3, true));
845 assert.include((yield* check(0.5 * 1024 ** 3, true)) ?? "", "1.0 GB needed, 0.5 GB free");
846 const blocker = yield* check(8 * 1024 ** 3, false);
847 assert.include(blocker ?? "", "Not enough free disk space");
848 assert.include(blocker ?? "", "10.5 GB needed, 8.0 GB free");
849 assert.include(blocker ?? "", "The server was not stopped");
850 }),
851 );
852​
853 it.effect("fails the backup check when the database cannot be inspected", () =>
854 Effect.gen(function* () {
855 const fs = yield* FileSystem.FileSystem;
856 const path = yield* Path.Path;
857 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-blocker-" });
858 const error = yield* Effect.promise(() =>
859 databaseBackupBlocker(root, path.join(root, "missing.sqlite"), {
860 readFreeBytes: () => Promise.resolve(0),
861 }).then(
862 () => undefined,
863 (cause: unknown) => cause,
864 ),
865 );
866 assert.equal((error as NodeJS.ErrnoException | undefined)?.code, "ENOENT");
867 }),
868 );
869​
870 it.effect("recognizes a clone into the backup directory on this filesystem", () =>
871 Effect.gen(function* () {
872 const fs = yield* FileSystem.FileSystem;
873 const path = yield* Path.Path;
874 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-clone-" });
875 const databasePath = path.join(root, "userdata", "state.sqlite");
876 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
877 yield* fs.writeFileString(databasePath, "database");
878 const blocker = yield* Effect.promise(() =>
879 databaseBackupBlocker(root, databasePath, { readFreeBytes: () => Promise.resolve(0) }),
880 );
881 assert.include(
882 blocker ?? "",
883 // oxlint-disable-next-line t3code/no-global-process-runtime -- mirrors the standalone launcher's own platform check.
884 process.platform === "darwin" ? "1.0 GB needed, 0.0 GB free" : "GB needed, 0.0 GB free",
885 );
886 assert.deepEqual(yield* fs.readDirectory(path.join(root, "runtime", "db-backup")), []);
887 }),
888 );
889});