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

serviceLauncher.test.ts

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