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

serviceLauncher.test.ts

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