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