Open History to see the last commit
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// @effect-diagnostics-next-line nodeBuiltinImport:off - the free-space probe is a plain Promise callback.
4import * as NodeFS from "node:fs";
5import * as NodeSqlite from "node:sqlite";
6
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { assert, it } from "@effect/vitest";
9import { SERVER_EXIT_CODE_STATE_DIR_OWNED } from "@t3tools/contracts";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Path from "effect/Path";
14import { vi } from "vite-plus/test";
15
16import {
17 databaseBackupBlocker,
18 Launcher,
19 main,
20 readServiceEnvironment,
21 type BackupSpaceProbe,
22 readServiceState,
23 writeServiceState,
24} from "./serviceLauncher.ts";
25import {
26 compareExactServiceVersions,
27 decodeServiceState,
28 isExactServiceVersion,
29 SERVICE_ENV_FILE,
30 SERVICE_LAUNCHER_PROTOCOL,
31 SERVICE_RESTART_PENDING_FILE,
32} from "./cloud/serviceProtocol.ts";
33
34const spawnedChildren = vi.hoisted((): Array<NodeChildProcess.ChildProcess> => []);
35
36vi.mock("node:child_process", async (importOriginal) => {
37 const actual = await importOriginal<typeof NodeChildProcess>();
38 const spawn = (...args: Parameters<typeof actual.spawn>) => {
39 const child = actual.spawn(...args);
40 spawnedChildren.push(child);
41 return child;
42 };
43 return { ...actual, spawn: spawn as typeof actual.spawn };
44});
45
46const writeSparseFile = (filePath: string, size: number) =>
47 Effect.gen(function* () {
48 const fileSystem = yield* FileSystem.FileSystem;
49 yield* fileSystem.writeFileString(filePath, "");
50 yield* fileSystem.truncate(filePath, size);
51 });
52
53it("accepts only exact semantic versions", () => {
54 for (const version of ["0.0.0", "1.2.3", "1.2.3-alpha.1", "1.2.3-0", "1.2.3+001"]) {
55 assert.isTrue(isExactServiceVersion(version), version);
56 }
57 for (const version of ["latest", "01.2.3", "1.2.3-01", "1.2.3-alpha..1", "1.2.3+."]) {
58 assert.isFalse(isExactServiceVersion(version), version);
59 }
60});
61
62it("orders exact semantic versions without treating build metadata as precedence", () => {
63 assert.equal(compareExactServiceVersions("1.2.3", "1.2.3"), 0);
64 assert.equal(compareExactServiceVersions("1.2.4", "1.2.3"), 1);
65 assert.equal(compareExactServiceVersions("2.0.0-alpha.1", "2.0.0-alpha.2"), -1);
66 assert.equal(compareExactServiceVersions("2.0.0-alpha.2", "2.0.0-alpha.beta"), -1);
67 assert.equal(compareExactServiceVersions("2.0.0-alpha-beta", "2.0.0-alpha-alpha"), 1);
68 assert.equal(compareExactServiceVersions("2.0.0", "2.0.0-rc.1"), 1);
69 assert.equal(compareExactServiceVersions("2.0.0+one", "2.0.0+two"), 0);
70});
71
72it("rejects contradictory service state", () => {
73 assert.isUndefined(
74 decodeServiceState({
75 protocol: SERVICE_LAUNCHER_PROTOCOL,
76 activeVersion: "0.0.31",
77 update: {
78 id: "update-1",
79 fromVersion: "0.0.30",
80 targetVersion: "0.0.32",
81 dbPath: "/tmp/state.sqlite",
82 status: "pending",
83 },
84 }),
85 );
86
87 assert.isUndefined(
88 decodeServiceState({
89 protocol: SERVICE_LAUNCHER_PROTOCOL,
90 activeVersion: "1.0.0",
91 update: {
92 id: "update-3",
93 fromVersion: "1.0.0",
94 targetVersion: "1.1.0",
95 status: "pending",
96 },
97 }),
98 );
99
100 assert.isUndefined(
101 decodeServiceState({
102 protocol: SERVICE_LAUNCHER_PROTOCOL,
103 activeVersion: "1.0.0",
104 update: {
105 id: "update-2",
106 fromVersion: "1.0.0",
107 targetVersion: "0.9.0",
108 dbPath: "/tmp/state.sqlite",
109 status: "pending",
110 },
111 }),
112 );
113});
114
115const writeFakeRuntime = (
116 fs: FileSystem.FileSystem,
117 path: Path.Path,
118 versionDir: string,
119 childSource: string,
120) =>
121 Effect.gen(function* () {
122 const entryPath = path.join(versionDir, "t3");
123 yield* fs.makeDirectory(versionDir, { recursive: true });
124 yield* fs.writeFileString(entryPath, `#!${process.execPath}\n${childSource}`);
125 yield* fs.chmod(entryPath, 0o755);
126 yield* fs.writeFileString(
127 path.join(versionDir, ".install-complete"),
128 `${path.basename(versionDir)}\n`,
129 );
130 return entryPath;
131 });
132
133it.layer(NodeServices.layer)("service state persistence", (it) => {
134 it.effect(
135 "loads optional service.env literally without changing inherited or managed variables",
136 () =>
137 Effect.gen(function* () {
138 const fs = yield* FileSystem.FileSystem;
139 const path = yield* Path.Path;
140 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-env-" });
141 const inherited = Object.freeze({
142 PATH: "inherited-path",
143 T3CODE_HOME: root,
144 T3_BOOT_SERVICE_UNIT: "managed-unit",
145 T3_SERVICE_LAUNCHER_CONTEXT: "managed-context",
146 T3CODE_PORT: "ambient",
147 });
148 assert.deepEqual(
149 yield* Effect.promise(() => readServiceEnvironment(root, inherited)),
150 inherited,
151 );
152 yield* fs.writeFileString(
153 path.join(root, SERVICE_ENV_FILE),
154 [
155 "# service configuration",
156 "export T3CODE_PORT=1234 # inline comment",
157 'T3CODE_TOKEN="literal $HOME ${USER} $(whoami) # token"',
158 'MULTILINE="first\nsecond"',
159 "EMPTY=",
160 "PATH=/bad",
161 "Path=/bad",
162 "T3CODE_HOME=/bad",
163 "t3code_home=/bad",
164 "T3_BOOT_SERVICE_UNIT=bad",
165 "t3_boot_service_unit=bad",
166 "T3_SERVICE_LAUNCHER_CONTEXT=bad",
167 "t3_service_launcher_context=bad",
168 ].join("\n"),
169 );
170 assert.deepEqual(yield* Effect.promise(() => readServiceEnvironment(root, inherited)), {
171 ...inherited,
172 T3CODE_PORT: "1234",
173 T3CODE_TOKEN: "literal $HOME ${USER} $(whoami) # token",
174 MULTILINE: "first\nsecond",
175 EMPTY: "",
176 });
177 }),
178 );
179
180 it.effect("a fresh launcher clears a restart deferred by t3 update", () =>
181 Effect.gen(function* () {
182 const fs = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-restart-" });
185 const statePath = path.join(root, "runtime", "service-state.json");
186 const restartPending = path.join(root, "runtime", SERVICE_RESTART_PENDING_FILE);
187 yield* writeFakeRuntime(
188 fs,
189 path,
190 path.join(root, "runtime", "versions", "1.0.0"),
191 "setInterval(() => {}, 1_000);\n",
192 );
193 yield* Effect.promise(() =>
194 writeServiceState(statePath, {
195 protocol: SERVICE_LAUNCHER_PROTOCOL,
196 activeVersion: "1.0.0",
197 }),
198 );
199 const run = () =>
200 Effect.gen(function* () {
201 const launcher = new Launcher(
202 root,
203 yield* Effect.promise(() => readServiceState(statePath)),
204 );
205 const running = launcher.run();
206 yield* Effect.promise(() => launcher.stop("SIGTERM"));
207 yield* Effect.promise(() => running);
208 });
209
210 yield* fs.writeFileString(restartPending, "1.0.1\n");
211 yield* run();
212 assert.isTrue(yield* fs.exists(restartPending));
213
214 yield* fs.writeFileString(restartPending, "1.0.0\n");
215 yield* run();
216 assert.isFalse(yield* fs.exists(restartPending));
217 }),
218 );
219
220 it.effect("stays idle instead of exiting when another server owns the T3 home", () =>
221 Effect.gen(function* () {
222 const fs = yield* FileSystem.FileSystem;
223 const path = yield* Path.Path;
224 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-refused-" });
225 const statePath = path.join(root, "runtime", "service-state.json");
226 yield* writeFakeRuntime(
227 fs,
228 path,
229 path.join(root, "runtime", "versions", "1.0.0"),
230 `process.exit(${SERVER_EXIT_CODE_STATE_DIR_OWNED});\n`,
231 );
232 yield* Effect.promise(() =>
233 writeServiceState(statePath, {
234 protocol: SERVICE_LAUNCHER_PROTOCOL,
235 activeVersion: "1.0.0",
236 }),
237 );
238 const refused = Promise.withResolvers<void>();
239 yield* Effect.acquireRelease(
240 Effect.sync(() =>
241 vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
242 if (String(chunk).includes("owns this T3 home")) refused.resolve();
243 return true;
244 }),
245 ),
246 (spy) => Effect.sync(() => spy.mockRestore()),
247 );
248 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
249 let completed = false;
250 const running = launcher.run().finally(() => {
251 completed = true;
252 });
253 yield* Effect.promise(() => refused.promise);
254 assert.isFalse(completed);
255 yield* Effect.promise(() => launcher.stop("SIGTERM"));
256 yield* Effect.promise(() => running);
257 }),
258 );
259
260 it.effect("commits only after the trial reports prepared", () =>
261 Effect.gen(function* () {
262 const fs = yield* FileSystem.FileSystem;
263 const path = yield* Path.Path;
264 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-flow-" });
265 const statePath = path.join(root, "runtime", "service-state.json");
266 const databasePath = path.join(root, "userdata", "state.sqlite");
267 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
268 yield* fs.writeFileString(databasePath, "before trial");
269 const encodedDatabasePath = JSON.stringify(databasePath);
270 const childSource = `
271const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
272if (context.update?.status === "pending") {
273 process.send({ type: "prepared", updateId: context.update.id });
274 process.on("message", (message) => {
275 if (message.type === "committed") process.exit(0);
276 });
277} else if (context.update === undefined) {
278 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
279 setInterval(() => {}, 1_000);
280} else {
281 process.exit(0);
282}
283`;
284 for (const version of ["1.0.0", "1.1.0"]) {
285 yield* writeFakeRuntime(
286 fs,
287 path,
288 path.join(root, "runtime", "versions", version),
289 childSource,
290 );
291 }
292 yield* Effect.promise(() =>
293 writeServiceState(statePath, {
294 protocol: SERVICE_LAUNCHER_PROTOCOL,
295 activeVersion: "1.0.0",
296 }),
297 );
298
299 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
300 yield* Effect.promise(() =>
301 launcher.run().then(
302 () => Promise.reject(new Error("launcher unexpectedly completed")),
303 () => Promise.resolve(),
304 ),
305 );
306
307 const state = yield* Effect.promise(() => readServiceState(statePath));
308 assert.equal(state.activeVersion, "1.1.0");
309 assert.equal(state.update?.status, "committed");
310 }),
311 );
312
313 it.effect("rolls back invalid trials with the startup environment", () =>
314 Effect.gen(function* () {
315 const fs = yield* FileSystem.FileSystem;
316 const path = yield* Path.Path;
317 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
318 const statePath = path.join(root, "runtime", "service-state.json");
319 const databasePath = path.join(root, "userdata", "state.sqlite");
320 const observationsPath = path.join(root, "environment-observations.jsonl");
321 const envPath = path.join(root, SERVICE_ENV_FILE);
322 yield* fs.writeFileString(envPath, "T3CODE_TEST_SERVICE_TOKEN=initial\n");
323 vi.stubEnv("T3CODE_HOME", root);
324 vi.stubEnv("T3CODE_TEST_SERVICE_TOKEN", "inherited");
325 yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs()));
326 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
327 yield* fs.writeFileString(databasePath, "before trial");
328 const encodedDatabasePath = JSON.stringify(databasePath);
329 const childSource = `
330import { appendFileSync, writeFileSync } from "node:fs";
331const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
332appendFileSync(${JSON.stringify(observationsPath)}, JSON.stringify({
333 token: process.env.T3CODE_TEST_SERVICE_TOKEN,
334 update: context.update?.status ?? "active",
335}) + "\\n");
336if (context.update?.status === "pending") {
337 process.send({ type: "prepared", updateId: "wrong-update" });
338} else if (context.update === undefined) {
339 writeFileSync(${JSON.stringify(envPath)}, "T3CODE_TEST_SERVICE_TOKEN=changed\\n");
340 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
341 setInterval(() => {}, 1_000);
342} else {
343 process.exit(0);
344}
345`;
346 for (const version of ["1.0.0", "1.1.0"]) {
347 yield* writeFakeRuntime(
348 fs,
349 path,
350 path.join(root, "runtime", "versions", version),
351 childSource,
352 );
353 }
354 yield* Effect.promise(() =>
355 writeServiceState(statePath, {
356 protocol: SERVICE_LAUNCHER_PROTOCOL,
357 activeVersion: "1.0.0",
358 }),
359 );
360
361 yield* Effect.promise(() =>
362 main().then(
363 () => Promise.reject(new Error("launcher unexpectedly completed")),
364 () => Promise.resolve(),
365 ),
366 );
367
368 const state = yield* Effect.promise(() => readServiceState(statePath));
369 assert.equal(state.activeVersion, "1.0.0");
370 assert.equal(state.update?.status, "rolled-back");
371 assert.equal(
372 state.update?.status === "rolled-back" ? state.update.reason : undefined,
373 "invalid-prepared",
374 );
375 const observations = (yield* fs.readFileString(observationsPath))
376 .trim()
377 .split("\n")
378 .map((line) => JSON.parse(line));
379 assert.deepEqual(observations, [
380 { token: "initial", update: "active" },
381 { token: "initial", update: "pending" },
382 { token: "initial", update: "rolled-back" },
383 ]);
384 assert.equal((yield* HostProcess.Environment).T3CODE_TEST_SERVICE_TOKEN, "inherited");
385 assert.equal(yield* fs.readFileString(envPath), "T3CODE_TEST_SERVICE_TOKEN=changed\n");
386 }),
387 );
388
389 it.effect.each(["file", "symlink", "dangling symlink"] as const)(
390 "restores the database when a migrating trial exits, with the database a %s",
391 (kind) =>
392 Effect.gen(function* () {
393 const fs = yield* FileSystem.FileSystem;
394 const path = yield* Path.Path;
395 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-db-" });
396 const statePath = path.join(root, "runtime", "service-state.json");
397 const databasePath = path.join(root, "userdata", "state.sqlite");
398 const databaseFile =
399 kind === "file" ? databasePath : path.join(root, "data", "original.sqlite");
400 const linkTarget = kind === "dangling symlink" ? "../original.sqlite" : databaseFile;
401 const original = "database before migration";
402 yield* fs.makeDirectory(path.dirname(databaseFile), { recursive: true });
403 if (kind === "dangling symlink") {
404 yield* fs.makeDirectory(path.join(root, "data", "sub"));
405 yield* fs.symlink(path.join(root, "data", "sub"), path.dirname(databasePath));
406 } else {
407 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
408 }
409 yield* fs.writeFileString(databaseFile, original);
410 if (kind !== "file") yield* fs.symlink(linkTarget, databasePath);
411 const encodedDatabasePath = JSON.stringify(databasePath);
412 const childSource = `
413import { realpathSync, unlinkSync, writeFileSync } from "node:fs";
414const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
415if (context.update?.status === "pending") {
416 writeFileSync(context.update.dbPath, "database after migration");
417 writeFileSync(context.update.dbPath + "-wal", "trial wal");
418 writeFileSync(context.update.dbPath + "-shm", "trial shm");
419 ${kind === "dangling symlink" ? "unlinkSync(realpathSync(context.update.dbPath));" : ""}
420 process.exit(1);
421} else if (context.update === undefined) {
422 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
423 setInterval(() => {}, 1_000);
424} else {
425 process.exit(0);
426}
427`;
428 for (const version of ["1.0.0", "1.1.0"]) {
429 yield* writeFakeRuntime(
430 fs,
431 path,
432 path.join(root, "runtime", "versions", version),
433 childSource,
434 );
435 }
436 yield* Effect.promise(() =>
437 writeServiceState(statePath, {
438 protocol: SERVICE_LAUNCHER_PROTOCOL,
439 activeVersion: "1.0.0",
440 }),
441 );
442
443 const launcher = new Launcher(
444 root,
445 yield* Effect.promise(() => readServiceState(statePath)),
446 );
447 yield* Effect.promise(() =>
448 launcher.run().then(
449 () => Promise.reject(new Error("launcher unexpectedly completed")),
450 () => Promise.resolve(),
451 ),
452 );
453
454 const state = yield* Effect.promise(() => readServiceState(statePath));
455 assert.equal(state.activeVersion, "1.0.0");
456 assert.equal(state.update?.status, "rolled-back");
457 assert.equal(yield* fs.readFileString(databaseFile), original);
458 if (kind !== "file") assert.equal(yield* fs.readLink(databasePath), linkTarget);
459 assert.isFalse(yield* fs.exists(path.join(root, "original.sqlite")));
460 assert.isFalse(yield* fs.exists(`${databasePath}-wal`));
461 assert.isFalse(yield* fs.exists(`${databasePath}-shm`));
462 const updateId = state.update?.id;
463 assert.isDefined(updateId);
464 assert.isFalse(yield* fs.exists(path.join(root, "runtime", "db-backup", updateId)));
465 }),
466 );
467
468 it.effect.each(["wal", "delete"] as const)(
469 "backs up a %s-mode database (online when WAL) and restores its final state",
470 (journalMode) =>
471 Effect.gen(function* () {
472 const fs = yield* FileSystem.FileSystem;
473 const path = yield* Path.Path;
474 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-online-" });
475 const statePath = path.join(root, "runtime", "service-state.json");
476 const databasePath = path.join(root, "userdata", "state.sqlite");
477 const observationsPath = path.join(root, "observations.json");
478 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
479 // SQLite keeps -wal beside the symlink's target, so the backup must restore it there.
480 yield* fs.symlink("actual.sqlite", databasePath);
481 const seed = new NodeSqlite.DatabaseSync(databasePath);
482 seed.exec(`
483 PRAGMA journal_mode = ${journalMode};
484 CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT NOT NULL);
485 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 500)
486 INSERT INTO events (payload) SELECT 'before the update ' || i FROM n;
487 `);
488 seed.close();
489
490 const encoded = JSON.stringify({ root, databasePath, observationsPath, journalMode });
491 const childSource = `
492import { readdirSync, writeFileSync } from "node:fs";
493import { DatabaseSync } from "node:sqlite";
494const paths = ${encoded};
495const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
496if (context.update?.status === "pending") {
497 writeFileSync(paths.observationsPath + ".trial", JSON.stringify(
498 readdirSync(paths.root + "/runtime/db-backup/" + context.update.id).sort(),
499 ));
500 const trial = new DatabaseSync(context.update.dbPath);
501 trial.exec("PRAGMA journal_mode = " + paths.journalMode + "; INSERT INTO events (payload) VALUES ('trial');");
502 trial.close();
503 process.exit(1);
504} else if (context.update === undefined) {
505 const db = new DatabaseSync(paths.databasePath);
506 db.exec("PRAGMA busy_timeout = 5000;");
507 db.exec("PRAGMA journal_mode = " + paths.journalMode + ";");
508 const insert = db.prepare("INSERT INTO events (payload) VALUES (?)");
509 const writer = setInterval(() => insert.run("written while serving"), 1);
510 process.once("SIGTERM", () => {
511 clearInterval(writer);
512 insert.run("last write before stopping");
513 const backupRoot = paths.root + "/runtime/db-backup";
514 writeFileSync(paths.observationsPath, JSON.stringify({
515 backupsAtStop: readdirSync(backupRoot).map((entry) => readdirSync(backupRoot + "/" + entry)),
516 rows: db.prepare("SELECT count(*) AS n FROM events").get().n,
517 }));
518 db.close();
519 process.exit(0);
520 });
521 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
522} else {
523 process.exit(0);
524}
525`;
526 for (const version of ["1.0.0", "1.1.0"]) {
527 yield* writeFakeRuntime(
528 fs,
529 path,
530 path.join(root, "runtime", "versions", version),
531 childSource,
532 );
533 }
534 yield* Effect.promise(() =>
535 writeServiceState(statePath, {
536 protocol: SERVICE_LAUNCHER_PROTOCOL,
537 activeVersion: "1.0.0",
538 }),
539 );
540
541 const launcher = new Launcher(
542 root,
543 yield* Effect.promise(() => readServiceState(statePath)),
544 {
545 backupSpaceProbe: { canClone: async () => false },
546 },
547 );
548 yield* Effect.promise(() =>
549 launcher.run().then(
550 () => Promise.reject(new Error("launcher unexpectedly completed")),
551 () => Promise.resolve(),
552 ),
553 );
554
555 const state = yield* Effect.promise(() => readServiceState(statePath));
556 assert.equal(state.update?.status, "rolled-back");
557 const observed = JSON.parse(yield* fs.readFileString(observationsPath));
558 // A WAL database's main file is copied before the server is asked to stop; others fall back offline.
559 assert.deepEqual(observed.backupsAtStop, journalMode === "wal" ? [["database"]] : []);
560 assert.isAbove(observed.rows, 501);
561 // Only the online copy holds no -shm: the offline fallback copies the one the server left.
562 assert.deepEqual(
563 JSON.parse(yield* fs.readFileString(`${observationsPath}.trial`)),
564 journalMode === "wal" ? ["database", "database-wal"] : ["database"],
565 );
566 const restored = new NodeSqlite.DatabaseSync(databasePath);
567 try {
568 assert.equal(restored.prepare("PRAGMA integrity_check").get()?.integrity_check, "ok");
569 assert.equal(
570 restored.prepare("SELECT count(*) AS n FROM events").get()?.n,
571 observed.rows,
572 );
573 assert.equal(
574 restored
575 .prepare(
576 "SELECT count(*) AS n FROM events WHERE payload = 'last write before stopping'",
577 )
578 .get()?.n,
579 1,
580 );
581 } finally {
582 restored.close();
583 }
584 }),
585 );
586
587 const requestRejectedUpdate = (backupSpaceProbe: Partial<BackupSpaceProbe>) =>
588 Effect.gen(function* () {
589 const fs = yield* FileSystem.FileSystem;
590 const path = yield* Path.Path;
591 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-space-" });
592 const statePath = path.join(root, "runtime", "service-state.json");
593 const databasePath = path.join(root, "userdata", "state.sqlite");
594 const replyPath = path.join(root, "rejection.txt");
595 const trialMarker = path.join(root, "trial-started");
596 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
597 yield* fs.writeFileString(databasePath, "database");
598 const encoded = JSON.stringify({ databasePath, replyPath, trialMarker });
599 const childSource = `
600import { writeFileSync } from "node:fs";
601const paths = ${encoded};
602const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
603if (context.update?.status === "pending") {
604 writeFileSync(paths.trialMarker, "started");
605 process.exit(1);
606} else if (context.update === undefined) {
607 process.on("message", (message) => {
608 if (message.type === "update-rejected") {
609 writeFileSync(paths.replyPath, message.reason);
610 process.exit(0);
611 }
612 });
613 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
614 setInterval(() => {}, 1_000);
615} else {
616 process.exit(0);
617}
618`;
619 for (const version of ["1.0.0", "1.1.0"]) {
620 yield* writeFakeRuntime(
621 fs,
622 path,
623 path.join(root, "runtime", "versions", version),
624 childSource,
625 );
626 }
627 yield* Effect.promise(() =>
628 writeServiceState(statePath, {
629 protocol: SERVICE_LAUNCHER_PROTOCOL,
630 activeVersion: "1.0.0",
631 }),
632 );
633
634 const launcher = new Launcher(
635 root,
636 yield* Effect.promise(() => readServiceState(statePath)),
637 { backupSpaceProbe },
638 );
639 yield* Effect.promise(() =>
640 launcher.run().then(
641 () => Promise.reject(new Error("launcher unexpectedly completed")),
642 () => Promise.resolve(),
643 ),
644 );
645
646 return {
647 reason: yield* fs.readFileString(replyPath),
648 trialStarted: yield* fs.exists(trialMarker),
649 state: yield* Effect.promise(() => readServiceState(statePath)),
650 };
651 });
652
653 it.effect("refuses a backup that cannot fit and leaves the server running", () =>
654 Effect.gen(function* () {
655 const { reason, trialStarted, state } = yield* requestRejectedUpdate({
656 readFreeBytes: () => Promise.resolve(0),
657 canClone: () => Promise.resolve(true),
658 });
659
660 assert.include(reason, "Not enough free disk space");
661 assert.include(reason, "The server was not stopped");
662 assert.isFalse(trialStarted);
663 assert.equal(state.activeVersion, "1.0.0");
664 assert.isUndefined(state.update);
665 }),
666 );
667
668 it.effect("refuses the update when free space cannot be checked", () =>
669 Effect.gen(function* () {
670 const { reason, trialStarted, state } = yield* requestRejectedUpdate({
671 readFreeBytes: () => Promise.reject(new Error("statfs unavailable")),
672 });
673
674 assert.include(
675 reason,
676 "Could not check that the database backup fits before updating: statfs unavailable",
677 );
678 assert.isFalse(trialStarted);
679 assert.equal(state.activeVersion, "1.0.0");
680 assert.isUndefined(state.update);
681 }),
682 );
683
684 it.effect("records no update when the server exits during the backup check", () =>
685 Effect.gen(function* () {
686 const fs = yield* FileSystem.FileSystem;
687 const path = yield* Path.Path;
688 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-exit-" });
689 const statePath = path.join(root, "runtime", "service-state.json");
690 const databasePath = path.join(root, "userdata", "state.sqlite");
691 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
692 yield* fs.writeFileString(databasePath, "database");
693 const encoded = JSON.stringify({ databasePath });
694 const childSource = `
695const paths = ${encoded};
696process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath }, () =>
697 process.exit(3),
698);
699setInterval(() => {}, 1_000);
700`;
701 for (const version of ["1.0.0", "1.1.0"]) {
702 yield* writeFakeRuntime(
703 fs,
704 path,
705 path.join(root, "runtime", "versions", version),
706 childSource,
707 );
708 }
709 yield* Effect.promise(() =>
710 writeServiceState(statePath, {
711 protocol: SERVICE_LAUNCHER_PROTOCOL,
712 activeVersion: "1.0.0",
713 }),
714 );
715 const launcher = new Launcher(
716 root,
717 yield* Effect.promise(() => readServiceState(statePath)),
718 {
719 backupSpaceProbe: {
720 readFreeBytes: () => {
721 const child = spawnedChildren.at(-1)!;
722 return new Promise((resolve) => {
723 if (!child.connected) resolve(Number.MAX_SAFE_INTEGER);
724 else child.once("disconnect", () => resolve(Number.MAX_SAFE_INTEGER));
725 });
726 },
727 },
728 },
729 );
730 const failure = yield* Effect.promise(() =>
731 launcher.run().then(
732 () => new Error("launcher unexpectedly completed"),
733 (cause: unknown) => cause as Error,
734 ),
735 );
736
737 assert.include(failure.message, "Active child exited unexpectedly (3)");
738 const state = yield* Effect.promise(() => readServiceState(statePath));
739 assert.equal(state.activeVersion, "1.0.0");
740 assert.isUndefined(state.update);
741 }),
742 );
743
744 it.effect("reclaims partial backups left by killed updates before checking space", () =>
745 Effect.gen(function* () {
746 const fs = yield* FileSystem.FileSystem;
747 const path = yield* Path.Path;
748 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-orphan-" });
749 const databasePath = path.join(root, "state.sqlite");
750 yield* writeSparseFile(databasePath, 10 * 1024 ** 3);
751 const backupRoot = path.join(root, "runtime", "db-backup");
752 const orphan = path.join(backupRoot, "earlier-update.staging");
753 const completed = path.join(backupRoot, "completed-update");
754 yield* fs.makeDirectory(orphan, { recursive: true });
755 yield* fs.writeFileString(path.join(orphan, "database"), "partial copy");
756 yield* fs.makeDirectory(completed);
757 yield* fs.writeFileString(path.join(completed, "database"), "complete copy");
758
759 // The orphan is what keeps this disk too full for a full copy.
760 const blocker = yield* Effect.promise(() =>
761 databaseBackupBlocker(root, databasePath, {
762 readFreeBytes: () => Promise.resolve((NodeFS.existsSync(orphan) ? 8 : 11) * 1024 ** 3),
763 canClone: () => Promise.resolve(false),
764 }),
765 );
766
767 assert.isUndefined(blocker);
768 assert.isFalse(yield* fs.exists(orphan));
769 assert.isTrue(yield* fs.exists(path.join(completed, "database")));
770 }),
771 );
772
773 it.effect("checks database backup space against clone or full-copy needs", () =>
774 Effect.gen(function* () {
775 const fs = yield* FileSystem.FileSystem;
776 const path = yield* Path.Path;
777 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-blocker-" });
778 const databasePath = path.join(root, "state.sqlite");
779 yield* writeSparseFile(databasePath, 10 * 1024 ** 3);
780 const check = (free: number, cloneable: boolean) =>
781 Effect.promise(() =>
782 databaseBackupBlocker(root, databasePath, {
783 readFreeBytes: () => Promise.resolve(free),
784 canClone: () => Promise.resolve(cloneable),
785 }),
786 );
787
788 assert.isUndefined(yield* check(11 * 1024 ** 3, false));
789 assert.isUndefined(yield* check(1.5 * 1024 ** 3, true));
790 assert.include((yield* check(0.5 * 1024 ** 3, true)) ?? "", "1.0 GB needed, 0.5 GB free");
791 const blocker = yield* check(8 * 1024 ** 3, false);
792 assert.include(blocker ?? "", "Not enough free disk space");
793 assert.include(blocker ?? "", "10.8 GB needed, 8.0 GB free");
794 assert.include(blocker ?? "", "The server was not stopped");
795 }),
796 );
797});