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// @effect-diagnostics-next-line nodeBuiltinImport:off - models the service manager reading disk through the launcher's Promise callback.
6import * as NodeFSP from "node:fs/promises";
7import * as NodeSqlite from "node:sqlite";
8
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import { assert, expect, it } from "@effect/vitest";
11import { SERVER_EXIT_CODE_STATE_DIR_OWNED } from "@t3tools/contracts";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Path from "effect/Path";
16import { vi } from "vite-plus/test";
17
18import {
19 renderBootServicePlist,
20 renderBootServiceTask,
21 renderBootServiceUnit,
22} from "./cloud/bootService.ts";
23import {
24 databaseBackupBlocker,
25 Launcher,
26 main,
27 readServiceEnvironment,
28 type BackupSpaceProbe,
29 readServiceState,
30 registerServiceTask,
31 serviceLauncherIsRunning,
32 serviceLauncherLockPath,
33 writeServiceState,
34} from "./serviceLauncher.ts";
35import {
36 compareExactServiceVersions,
37 decodeServiceState,
38 isExactServiceVersion,
39 disabledServiceTask,
40 SERVICE_ENV_FILE,
41 SERVICE_LAUNCHER_PROTOCOL,
42 SERVICE_RESTART_PENDING_FILE,
43 SERVICE_STOP_MARKER_FILE,
44} from "./cloud/serviceProtocol.ts";
45
46const spawnedChildren = vi.hoisted((): Array<NodeChildProcess.ChildProcess> => []);
47
48vi.mock("node:child_process", async (importOriginal) => {
49 const actual = await importOriginal<typeof NodeChildProcess>();
50 const spawn = (...args: Parameters<typeof actual.spawn>) => {
51 const child = actual.spawn(...args);
52 spawnedChildren.push(child);
53 return child;
54 };
55 return { ...actual, spawn: spawn as typeof actual.spawn };
56});
57
58const writeSparseFile = (filePath: string, size: number) =>
59 Effect.gen(function* () {
60 const fileSystem = yield* FileSystem.FileSystem;
61 yield* fileSystem.writeFileString(filePath, "");
62 yield* fileSystem.truncate(filePath, size);
63 });
64
65it("accepts only exact semantic versions", () => {
66 for (const version of ["0.0.0", "1.2.3", "1.2.3-alpha.1", "1.2.3-0", "1.2.3+001"]) {
67 assert.isTrue(isExactServiceVersion(version), version);
68 }
69 for (const version of ["latest", "01.2.3", "1.2.3-01", "1.2.3-alpha..1", "1.2.3+."]) {
70 assert.isFalse(isExactServiceVersion(version), version);
71 }
72});
73
74it("orders exact semantic versions without treating build metadata as precedence", () => {
75 assert.equal(compareExactServiceVersions("1.2.3", "1.2.3"), 0);
76 assert.equal(compareExactServiceVersions("1.2.4", "1.2.3"), 1);
77 assert.equal(compareExactServiceVersions("2.0.0-alpha.1", "2.0.0-alpha.2"), -1);
78 assert.equal(compareExactServiceVersions("2.0.0-alpha.2", "2.0.0-alpha.beta"), -1);
79 assert.equal(compareExactServiceVersions("2.0.0-alpha-beta", "2.0.0-alpha-alpha"), 1);
80 assert.equal(compareExactServiceVersions("2.0.0", "2.0.0-rc.1"), 1);
81 assert.equal(compareExactServiceVersions("2.0.0+one", "2.0.0+two"), 0);
82});
83
84it("rejects contradictory service state", () => {
85 assert.isUndefined(
86 decodeServiceState({
87 protocol: SERVICE_LAUNCHER_PROTOCOL,
88 activeVersion: "0.0.31",
89 update: {
90 id: "update-1",
91 fromVersion: "0.0.30",
92 targetVersion: "0.0.32",
93 dbPath: "/tmp/state.sqlite",
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-3",
105 fromVersion: "1.0.0",
106 targetVersion: "1.1.0",
107 status: "pending",
108 },
109 }),
110 );
111
112 assert.isUndefined(
113 decodeServiceState({
114 protocol: SERVICE_LAUNCHER_PROTOCOL,
115 activeVersion: "1.0.0",
116 update: {
117 id: "update-2",
118 fromVersion: "1.0.0",
119 targetVersion: "0.9.0",
120 dbPath: "/tmp/state.sqlite",
121 status: "pending",
122 },
123 }),
124 );
125});
126
127const unitPlan = (root: string, version: string) => ({
128 program: [`${root}/runtime/versions/${version}/t3`, "__service-launcher"],
129 baseDir: root,
130 logPath: `${root}/logs/boot-service.log`,
131 unitPath: `${root}/unit/t3code.service`,
132});
133
134const writeFakeRuntime = (
135 fs: FileSystem.FileSystem,
136 path: Path.Path,
137 versionDir: string,
138 childSource: string,
139) =>
140 Effect.gen(function* () {
141 const entryPath = path.join(versionDir, "t3");
142 yield* fs.makeDirectory(versionDir, { recursive: true });
143 yield* fs.writeFileString(entryPath, `#!${process.execPath}\n${childSource}`);
144 yield* fs.chmod(entryPath, 0o755);
145 yield* fs.writeFileString(
146 path.join(versionDir, ".install-complete"),
147 `${path.basename(versionDir)}\n`,
148 );
149 return entryPath;
150 });
151
152const runLauncher = async (root: string) => {
153 vi.stubEnv("T3CODE_HOME", root);
154 try {
155 await main();
156 } finally {
157 vi.unstubAllEnvs();
158 }
159};
160
161const fakeServiceUnit = (
162 fs: FileSystem.FileSystem,
163 path: Path.Path,
164 root: string,
165 version: string,
166 render = renderBootServiceUnit,
167) =>
168 Effect.gen(function* () {
169 const plan = unitPlan(root, version);
170 yield* fs.makeDirectory(path.dirname(plan.unitPath), { recursive: true });
171 const contents = render(plan);
172 yield* fs.writeFileString(plan.unitPath, contents);
173 const unit = {
174 path: plan.unitPath,
175 reloads: 0,
176 loadedContents: contents,
177 failReload: false,
178 reload: async () => {
179 unit.reloads += 1;
180 if (unit.failReload) throw new Error("daemon-reload failed");
181 unit.loadedContents = await NodeFSP.readFile(unit.path, "utf8");
182 },
183 };
184 return unit;
185 });
186
187it.layer(NodeServices.layer)("service state persistence", (it) => {
188 it.effect(
189 "loads optional service.env literally without changing inherited or managed variables",
190 () =>
191 Effect.gen(function* () {
192 const fs = yield* FileSystem.FileSystem;
193 const path = yield* Path.Path;
194 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-env-" });
195 const inherited = Object.freeze({
196 PATH: "inherited-path",
197 T3CODE_HOME: root,
198 T3_BOOT_SERVICE_UNIT: "managed-unit",
199 T3_SERVICE_LAUNCHER_CONTEXT: "managed-context",
200 T3CODE_PORT: "ambient",
201 });
202 assert.deepEqual(
203 yield* Effect.promise(() => readServiceEnvironment(root, inherited)),
204 inherited,
205 );
206 yield* fs.writeFileString(
207 path.join(root, SERVICE_ENV_FILE),
208 [
209 "# service configuration",
210 "export T3CODE_PORT=1234 # inline comment",
211 'T3CODE_TOKEN="literal $HOME ${USER} $(whoami) # token"',
212 'MULTILINE="first\nsecond"',
213 "EMPTY=",
214 "PATH=/bad",
215 "Path=/bad",
216 "T3CODE_HOME=/bad",
217 "t3code_home=/bad",
218 "T3_BOOT_SERVICE_UNIT=bad",
219 "t3_boot_service_unit=bad",
220 "T3_SERVICE_LAUNCHER_CONTEXT=bad",
221 "t3_service_launcher_context=bad",
222 ].join("\n"),
223 );
224 assert.deepEqual(yield* Effect.promise(() => readServiceEnvironment(root, inherited)), {
225 ...inherited,
226 T3CODE_PORT: "1234",
227 T3CODE_TOKEN: "literal $HOME ${USER} $(whoami) # token",
228 MULTILINE: "first\nsecond",
229 EMPTY: "",
230 });
231 }),
232 );
233
234 it.effect("registers its task again without enabling one the CLI disabled", () =>
235 Effect.gen(function* () {
236 const fs = yield* FileSystem.FileSystem;
237 const path = yield* Path.Path;
238 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-task-" });
239 const unitPath = path.join(root, "t3code-task.xml");
240 const unit = renderBootServiceTask(unitPlan(root, "1.1.0"), {
241 userId: "PC\\theo",
242 homeDir: "C:\\Users\\theo",
243 conhostPath: "conhost.exe",
244 });
245 yield* fs.writeFileString(unitPath, unit);
246 // Task Scheduler's copy: `t3 doctor` disabled it to keep the service stopped.
247 let task = disabledServiceTask(unit.replace("1.1.0", "1.0.0"));
248 const schtasks = async (...args: ReadonlyArray<string>) => {
249 if (args[0] === "/Create") task = await NodeFSP.readFile(args[2] ?? "", "utf8");
250 return { stdout: task };
251 };
252
253 yield* Effect.promise(() => registerServiceTask(unitPath, "t3code-PC-theo", schtasks));
254 assert.equal(task, disabledServiceTask(unit));
255 assert.deepEqual(yield* fs.readDirectory(root), ["t3code-task.xml"]);
256
257 task = unit.replace("1.1.0", "1.0.0");
258 yield* Effect.promise(() => registerServiceTask(unitPath, "t3code-PC-theo", schtasks));
259 assert.equal(task, unit);
260 }),
261 );
262
263 it.effect("finds its unit through the manager's environment, not service.env", () =>
264 Effect.gen(function* () {
265 const fs = yield* FileSystem.FileSystem;
266 const path = yield* Path.Path;
267 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-unit-" });
268 const home = path.join(root, "home");
269 const unitPath = path.join(home, "Library", "LaunchAgents", "t3code.plist");
270 const render = (version: string) =>
271 renderBootServicePlist(unitPlan(root, version), { homeDir: home, environmentPath: "" });
272 yield* fs.makeDirectory(path.dirname(unitPath), { recursive: true });
273 yield* fs.writeFileString(unitPath, render("1.0.0"));
274 // The server may run with another HOME; the launch agent still lives in the manager's.
275 yield* fs.writeFileString(path.join(root, SERVICE_ENV_FILE), "HOME=/elsewhere\n");
276 yield* writeFakeRuntime(
277 fs,
278 path,
279 path.join(root, "runtime", "versions", "1.1.0"),
280 "process.exit(0);\n",
281 );
282 yield* Effect.promise(() =>
283 writeServiceState(path.join(root, "runtime", "service-state.json"), {
284 protocol: SERVICE_LAUNCHER_PROTOCOL,
285 activeVersion: "1.1.0",
286 update: {
287 id: "update-1",
288 fromVersion: "1.0.0",
289 targetVersion: "1.1.0",
290 status: "committed",
291 },
292 }),
293 );
294 vi.stubEnv("HOME", home);
295 vi.stubEnv("T3_BOOT_SERVICE_UNIT", "t3code.plist");
296
297 yield* Effect.promise(() =>
298 expect(runLauncher(root)).rejects.toThrow("Active child exited unexpectedly (0)."),
299 );
300
301 assert.equal(yield* fs.readFileString(unitPath), render("1.1.0"));
302 }),
303 );
304
305 it.effect("adopts a legacy install record without rewriting it", () =>
306 Effect.gen(function* () {
307 const fs = yield* FileSystem.FileSystem;
308 const path = yield* Path.Path;
309 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-migrate-" });
310 const statePath = path.join(root, "runtime", "service-state.json");
311 const activeVersion = "0.0.43-nightly.20260919.1962+build.1";
312 const versionDir = path.join(root, "runtime", "versions", activeVersion);
313 yield* writeFakeRuntime(
314 fs,
315 path,
316 versionDir,
317 `
318import { writeFileSync } from "node:fs";
319writeFileSync(new URL("./started", import.meta.url), "");
320process.exit(0);
321`,
322 );
323 const legacyContents = `{ "protocol": 2, "activeVersion": "${activeVersion}" }`;
324 yield* fs.writeFileString(statePath, legacyContents);
325 const restartPending = path.join(root, "runtime", ".restart-pending");
326 yield* fs.writeFileString(restartPending, `${activeVersion}\n`);
327
328 yield* Effect.promise(() =>
329 expect(runLauncher(root)).rejects.toThrow("Active child exited unexpectedly (0)."),
330 );
331
332 assert.isTrue(yield* fs.exists(path.join(versionDir, "started")));
333 assert.isFalse(yield* fs.exists(restartPending));
334 assert.equal(yield* fs.readFileString(statePath), legacyContents);
335 }),
336 );
337
338 it.effect("refuses non-install legacy documents without rewriting or spawning", () =>
339 Effect.gen(function* () {
340 const fs = yield* FileSystem.FileSystem;
341 const path = yield* Path.Path;
342 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-reject-" });
343 const statePath = path.join(root, "runtime", "service-state.json");
344 yield* writeFakeRuntime(
345 fs,
346 path,
347 path.join(root, "runtime", "versions", "1.0.0"),
348 "process.exit(0);\n",
349 );
350 const legacy = { protocol: 2, activeVersion: "1.0.0" };
351 const childCount = spawnedChildren.length;
352 for (const contents of [
353 JSON.stringify({
354 ...legacy,
355 update: {
356 id: "u",
357 fromVersion: "1.0.0",
358 targetVersion: "1.1.0",
359 dbPath: "/tmp/state.sqlite",
360 status: "pending",
361 },
362 }),
363 JSON.stringify({ ...legacy, update: null }),
364 JSON.stringify({ ...legacy, extra: true }),
365 JSON.stringify({ ...legacy, protocol: 1 }),
366 JSON.stringify({ ...legacy, protocol: 5 }),
367 JSON.stringify({ ...legacy, activeVersion: "latest" }),
368 "{ invalid JSON",
369 ]) {
370 yield* fs.writeFileString(statePath, contents);
371 yield* Effect.promise(() =>
372 expect(runLauncher(root)).rejects.toThrow("Service state is invalid or unsupported."),
373 );
374 assert.equal(yield* fs.readFileString(statePath), contents);
375 assert.equal(spawnedChildren.length, childCount);
376 }
377 }),
378 );
379
380 it.effect("refuses a legacy state whose runtime is missing without rewriting or spawning", () =>
381 Effect.gen(function* () {
382 const fs = yield* FileSystem.FileSystem;
383 const path = yield* Path.Path;
384 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-layout-" });
385 const statePath = path.join(root, "runtime", "service-state.json");
386 const contents = '{ "protocol": 2, "activeVersion": "1.0.0" }';
387 yield* fs.makeDirectory(path.dirname(statePath), { recursive: true });
388 yield* fs.writeFileString(statePath, contents);
389 const childCount = spawnedChildren.length;
390
391 yield* Effect.promise(() =>
392 expect(runLauncher(root)).rejects.toThrow(
393 "Selected t3@1.0.0 runtime is missing or incomplete.",
394 ),
395 );
396 assert.equal(yield* fs.readFileString(statePath), contents);
397 assert.equal(spawnedChildren.length, childCount);
398 }),
399 );
400
401 it.effect("a fresh launcher clears a restart deferred by t3 update", () =>
402 Effect.gen(function* () {
403 const fs = yield* FileSystem.FileSystem;
404 const path = yield* Path.Path;
405 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-restart-" });
406 const statePath = path.join(root, "runtime", "service-state.json");
407 const restartPending = path.join(root, "runtime", SERVICE_RESTART_PENDING_FILE);
408 yield* writeFakeRuntime(
409 fs,
410 path,
411 path.join(root, "runtime", "versions", "1.0.0"),
412 "setInterval(() => {}, 1_000);\n",
413 );
414 yield* Effect.promise(() =>
415 writeServiceState(statePath, {
416 protocol: SERVICE_LAUNCHER_PROTOCOL,
417 activeVersion: "1.0.0",
418 }),
419 );
420 const run = () =>
421 Effect.gen(function* () {
422 const launcher = new Launcher(
423 root,
424 yield* Effect.promise(() => readServiceState(statePath)),
425 );
426 const running = launcher.run();
427 yield* Effect.promise(() => launcher.stop("SIGTERM"));
428 yield* Effect.promise(() => running);
429 });
430
431 yield* fs.writeFileString(restartPending, "1.0.1\n");
432 yield* run();
433 assert.isTrue(yield* fs.exists(restartPending));
434
435 yield* fs.writeFileString(restartPending, "1.0.0\n");
436 yield* run();
437 assert.isFalse(yield* fs.exists(restartPending));
438 }),
439 );
440
441 it.effect.each([
442 { unitVersion: "1.0.0", replacement: "an intentional downgrade" },
443 { unitVersion: "1.2.0", replacement: "another T3 home" },
444 ])(
445 "recovers a rolled-back update with unit $unitVersion and preserves $replacement",
446 ({ unitVersion, replacement }) =>
447 Effect.gen(function* () {
448 const fs = yield* FileSystem.FileSystem;
449 const path = yield* Path.Path;
450 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-repoint-" });
451 const statePath = path.join(root, "runtime", "service-state.json");
452 yield* writeFakeRuntime(
453 fs,
454 path,
455 path.join(root, "runtime", "versions", "1.1.0"),
456 "setInterval(() => {}, 1_000);\n",
457 );
458 yield* Effect.promise(() =>
459 writeServiceState(statePath, {
460 protocol: SERVICE_LAUNCHER_PROTOCOL,
461 activeVersion: "1.1.0",
462 update: {
463 id: "update-1",
464 fromVersion: "1.1.0",
465 targetVersion: "1.2.0",
466 status: "rolled-back",
467 },
468 }),
469 );
470 const unit = yield* fakeServiceUnit(fs, path, root, unitVersion);
471 const expected = renderBootServiceUnit(
472 unitPlan(root, unitVersion === "1.0.0" ? "1.1.0" : unitVersion),
473 );
474 const createLauncher = Effect.gen(function* () {
475 return new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)), {
476 serviceUnit: unit,
477 });
478 });
479 const run = (launcher: Launcher) =>
480 Effect.gen(function* () {
481 const running = launcher.run();
482 yield* Effect.promise(() => launcher.stop("SIGTERM"));
483 yield* Effect.promise(() => running);
484 });
485
486 yield* run(yield* createLauncher);
487 assert.equal(yield* fs.readFileString(unit.path), expected);
488 assert.equal(unit.loadedContents, expected);
489
490 yield* run(yield* createLauncher);
491 assert.equal(yield* fs.readFileString(unit.path), expected);
492 assert.equal(unit.loadedContents, expected);
493
494 yield* Effect.promise(() =>
495 writeServiceState(statePath, {
496 protocol: SERVICE_LAUNCHER_PROTOCOL,
497 activeVersion: "1.1.0",
498 update: {
499 id: "update-2",
500 fromVersion: "1.0.0",
501 targetVersion: "1.1.0",
502 status: "committed",
503 },
504 }),
505 );
506 const staleLauncher = yield* createLauncher;
507 // A local install can replace the selection or service owner without stopping this launcher.
508 const selectedRoot =
509 replacement === "another T3 home" ? path.join(root, "other-home") : root;
510 yield* writeFakeRuntime(
511 fs,
512 path,
513 path.join(selectedRoot, "runtime", "versions", "1.0.0"),
514 "setInterval(() => {}, 1_000);\n",
515 );
516 const selectedStatePath = path.join(selectedRoot, "runtime", "service-state.json");
517 yield* Effect.promise(() =>
518 writeServiceState(selectedStatePath, {
519 protocol: SERVICE_LAUNCHER_PROTOCOL,
520 activeVersion: "1.0.0",
521 }),
522 );
523 const selectedUnit = renderBootServiceUnit({
524 ...unitPlan(selectedRoot, "1.0.0"),
525 unitPath: unit.path,
526 });
527 yield* fs.writeFileString(unit.path, selectedUnit);
528 yield* Effect.promise(() => unit.reload());
529 const oldHomeState = yield* fs.readFileString(statePath);
530 const selectedState = yield* fs.readFileString(selectedStatePath);
531
532 yield* run(staleLauncher);
533 assert.equal(yield* fs.readFileString(statePath), oldHomeState);
534 assert.equal(yield* fs.readFileString(selectedStatePath), selectedState);
535 assert.equal(yield* fs.readFileString(unit.path), selectedUnit, replacement);
536 assert.equal(unit.loadedContents, selectedUnit, replacement);
537 }),
538 );
539
540 it.effect("stays idle instead of exiting when another server owns the T3 home", () =>
541 Effect.gen(function* () {
542 const fs = yield* FileSystem.FileSystem;
543 const path = yield* Path.Path;
544 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-refused-" });
545 const statePath = path.join(root, "runtime", "service-state.json");
546 yield* writeFakeRuntime(
547 fs,
548 path,
549 path.join(root, "runtime", "versions", "1.0.0"),
550 `process.exit(${SERVER_EXIT_CODE_STATE_DIR_OWNED});\n`,
551 );
552 yield* Effect.promise(() =>
553 writeServiceState(statePath, {
554 protocol: SERVICE_LAUNCHER_PROTOCOL,
555 activeVersion: "1.0.0",
556 }),
557 );
558 const refused = Promise.withResolvers<void>();
559 yield* Effect.acquireRelease(
560 Effect.sync(() =>
561 vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
562 if (String(chunk).includes("owns this T3 home")) refused.resolve();
563 return true;
564 }),
565 ),
566 (spy) => Effect.sync(() => spy.mockRestore()),
567 );
568 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
569 let completed = false;
570 const running = launcher.run().finally(() => {
571 completed = true;
572 });
573 yield* Effect.promise(() => refused.promise);
574 assert.isFalse(completed);
575 yield* Effect.promise(() => launcher.stop("SIGTERM"));
576 yield* Effect.promise(() => running);
577 }),
578 );
579
580 const commitUpdate = (
581 render = renderBootServiceUnit,
582 missingUnit = false,
583 legacyInstall = false,
584 ) =>
585 Effect.gen(function* () {
586 const fs = yield* FileSystem.FileSystem;
587 const path = yield* Path.Path;
588 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service 100% & <test>-" });
589 const statePath = path.join(root, "runtime", "service-state.json");
590 const databasePath = path.join(root, "userdata", "state.sqlite");
591 const activatedPath = path.join(root, "activated");
592 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
593 yield* fs.writeFileString(databasePath, "before trial");
594 const unit = yield* fakeServiceUnit(fs, path, root, "1.0.0", render);
595 if (missingUnit) yield* fs.remove(unit.path);
596 const childSource = `
597import assert from "node:assert/strict";
598import { existsSync, readFileSync, writeFileSync } from "node:fs";
599const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
600assert.equal(context.protocol, ${SERVICE_LAUNCHER_PROTOCOL});
601if (context.update?.status === "pending") {
602 const state = JSON.parse(readFileSync(${JSON.stringify(statePath)}, "utf8"));
603 assert.equal(state.activeVersion, "1.0.0");
604 assert.equal(state.update.status, "pending");
605 ${
606 missingUnit
607 ? `assert.equal(existsSync(${JSON.stringify(unit.path)}), false);`
608 : `assert.equal(readFileSync(${JSON.stringify(unit.path)}, "utf8"), ${JSON.stringify(unit.loadedContents)});`
609 }
610 process.on("message", (message) => {
611 if (message.type === "committed") {
612 const state = JSON.parse(readFileSync(${JSON.stringify(statePath)}, "utf8"));
613 assert.equal(state.protocol, ${SERVICE_LAUNCHER_PROTOCOL});
614 assert.equal(state.activeVersion, "1.1.0");
615 assert.equal(state.update.status, "committed");
616 writeFileSync(${JSON.stringify(activatedPath)}, message.updateId);
617 process.exit(0);
618 }
619 });
620 process.send({ type: "prepared", updateId: context.update.id });
621} else if (context.update === undefined) {
622 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${JSON.stringify(databasePath)} });
623 setInterval(() => {}, 1_000);
624} else {
625 process.exit(0);
626}
627`;
628 for (const version of ["1.0.0", "1.1.0"]) {
629 yield* writeFakeRuntime(
630 fs,
631 path,
632 path.join(root, "runtime", "versions", version),
633 childSource,
634 );
635 }
636 // The old CLI installs the new runtime but writes state with its own protocol.
637 yield* fs.writeFileString(
638 statePath,
639 `${JSON.stringify(
640 {
641 protocol: legacyInstall ? 3 : SERVICE_LAUNCHER_PROTOCOL,
642 activeVersion: "1.0.0",
643 },
644 null,
645 2,
646 )}\n`,
647 );
648 const launcher = new Launcher(
649 root,
650 yield* Effect.promise(() => readServiceState(statePath)),
651 { serviceUnit: unit },
652 );
653 const failure = yield* Effect.promise(() =>
654 launcher.run().then(
655 () => "launcher unexpectedly completed",
656 (cause: unknown) => String(cause),
657 ),
658 );
659 assert.include(failure, "Active child exited unexpectedly (0)");
660 const state = yield* Effect.promise(() => readServiceState(statePath));
661 assert.equal(state.activeVersion, "1.1.0");
662 assert.equal(state.update?.status, "committed");
663 assert.equal(yield* fs.readFileString(activatedPath), state.update?.id);
664 const recover = () =>
665 Effect.gen(function* () {
666 const fresh = new Launcher(
667 root,
668 yield* Effect.promise(() => readServiceState(statePath)),
669 { serviceUnit: unit },
670 );
671 const running = fresh.run();
672 yield* Effect.promise(() => fresh.stop("SIGTERM"));
673 yield* Effect.promise(() => running);
674 });
675 return { fs, root, unit, recover };
676 });
677
678 it.effect.each([
679 {
680 name: "systemd after a protocol-3 local upgrade",
681 render: renderBootServiceUnit,
682 legacyInstall: true,
683 },
684 {
685 name: "launchd",
686 legacyInstall: false,
687 render: (plan: Parameters<typeof renderBootServicePlist>[0]) =>
688 renderBootServicePlist(plan, {
689 homeDir: "/Users/test & <user>",
690 environmentPath: "/usr/bin:/custom/runtime/versions/1.0.0",
691 }),
692 },
693 {
694 name: "Task Scheduler",
695 legacyInstall: false,
696 render: (plan: Parameters<typeof renderBootServiceTask>[0]) =>
697 renderBootServiceTask(
698 { ...plan, program: [`${plan.program[0]}.exe`, "__service-launcher"] },
699 { userId: "PC\\theo", homeDir: "C:\\Users\\theo", conhostPath: "conhost.exe" },
700 ),
701 },
702 ])(
703 "commits and repoints $name only after the trial reports prepared",
704 ({ render, legacyInstall }) =>
705 Effect.gen(function* () {
706 const { fs, root, unit } = yield* commitUpdate(render, false, legacyInstall);
707 const expected = render(unitPlan(root, "1.1.0"));
708 assert.equal(yield* fs.readFileString(unit.path), expected);
709 assert.equal(unit.loadedContents, expected);
710 assert.equal(unit.reloads, 1);
711 }),
712 );
713
714 it.effect(
715 "keeps a durable commit through unit failure and retries a failed reload on restart",
716 () =>
717 Effect.gen(function* () {
718 const { fs, root, unit, recover } = yield* commitUpdate(renderBootServiceUnit, true);
719 assert.equal(unit.reloads, 0);
720 const original = renderBootServiceUnit(unitPlan(root, "1.0.0"));
721 const expected = renderBootServiceUnit(unitPlan(root, "1.1.0"));
722 assert.equal(unit.loadedContents, original);
723 yield* fs.writeFileString(unit.path, original);
724 unit.failReload = true;
725 yield* recover();
726 assert.equal(yield* fs.readFileString(unit.path), expected);
727 assert.equal(unit.reloads, 1);
728 assert.equal(unit.loadedContents, original);
729
730 unit.failReload = false;
731 yield* recover();
732 assert.equal(yield* fs.readFileString(unit.path), expected);
733 assert.equal(unit.loadedContents, expected);
734 assert.equal(unit.reloads, 2);
735 }),
736 );
737
738 it.effect("rolls back invalid trials with the startup environment", () =>
739 Effect.gen(function* () {
740 const fs = yield* FileSystem.FileSystem;
741 const path = yield* Path.Path;
742 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
743 const statePath = path.join(root, "runtime", "service-state.json");
744 const databasePath = path.join(root, "userdata", "state.sqlite");
745 const observationsPath = path.join(root, "environment-observations.jsonl");
746 const envPath = path.join(root, SERVICE_ENV_FILE);
747 yield* fs.writeFileString(envPath, "T3CODE_TEST_SERVICE_TOKEN=initial\n");
748 vi.stubEnv("T3CODE_HOME", root);
749 vi.stubEnv("T3CODE_TEST_SERVICE_TOKEN", "inherited");
750 yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs()));
751 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
752 yield* fs.writeFileString(databasePath, "before trial");
753 const encodedDatabasePath = JSON.stringify(databasePath);
754 const childSource = `
755import { appendFileSync, writeFileSync } from "node:fs";
756const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
757appendFileSync(${JSON.stringify(observationsPath)}, JSON.stringify({
758 token: process.env.T3CODE_TEST_SERVICE_TOKEN,
759 update: context.update?.status ?? "active",
760}) + "\\n");
761if (context.update?.status === "pending") {
762 process.send({ type: "prepared", updateId: "wrong-update" });
763} else if (context.update === undefined) {
764 writeFileSync(${JSON.stringify(envPath)}, "T3CODE_TEST_SERVICE_TOKEN=changed\\n");
765 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
766 setInterval(() => {}, 1_000);
767} else {
768 process.exit(0);
769}
770`;
771 for (const version of ["1.0.0", "1.1.0"]) {
772 yield* writeFakeRuntime(
773 fs,
774 path,
775 path.join(root, "runtime", "versions", version),
776 childSource,
777 );
778 }
779 yield* Effect.promise(() =>
780 writeServiceState(statePath, {
781 protocol: SERVICE_LAUNCHER_PROTOCOL,
782 activeVersion: "1.0.0",
783 }),
784 );
785 const unit = yield* fakeServiceUnit(fs, path, root, "0.9.0");
786
787 const launcher = new Launcher(
788 root,
789 yield* Effect.promise(() => readServiceState(statePath)),
790 {
791 serviceUnit: unit,
792 environment: yield* Effect.promise(() => readServiceEnvironment(root)),
793 },
794 );
795 yield* Effect.promise(() =>
796 launcher.run().then(
797 () => Promise.reject(new Error("launcher unexpectedly completed")),
798 () => Promise.resolve(),
799 ),
800 );
801
802 const state = yield* Effect.promise(() => readServiceState(statePath));
803 assert.equal(state.activeVersion, "1.0.0");
804 assert.equal(state.update?.status, "rolled-back");
805 assert.equal(
806 yield* fs.readFileString(unit.path),
807 renderBootServiceUnit(unitPlan(root, "1.0.0")),
808 );
809 assert.equal(unit.reloads, 1);
810 assert.equal(
811 state.update?.status === "rolled-back" ? state.update.reason : undefined,
812 "invalid-prepared",
813 );
814 const observations = (yield* fs.readFileString(observationsPath))
815 .trim()
816 .split("\n")
817 .map((line) => JSON.parse(line));
818 assert.deepEqual(observations, [
819 { token: "initial", update: "active" },
820 { token: "initial", update: "pending" },
821 { token: "initial", update: "rolled-back" },
822 ]);
823 assert.equal((yield* HostProcess.Environment).T3CODE_TEST_SERVICE_TOKEN, "inherited");
824 assert.equal(yield* fs.readFileString(envPath), "T3CODE_TEST_SERVICE_TOKEN=changed\n");
825 }),
826 );
827
828 it.effect.each(["file", "symlink", "dangling symlink"] as const)(
829 "restores the database when a migrating trial exits, with the database a %s",
830 (kind) =>
831 Effect.gen(function* () {
832 const fs = yield* FileSystem.FileSystem;
833 const path = yield* Path.Path;
834 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-db-" });
835 const statePath = path.join(root, "runtime", "service-state.json");
836 const databasePath = path.join(root, "userdata", "state.sqlite");
837 const databaseFile =
838 kind === "file" ? databasePath : path.join(root, "data", "original.sqlite");
839 const linkTarget = kind === "dangling symlink" ? "../original.sqlite" : databaseFile;
840 const original = "database before migration";
841 yield* fs.makeDirectory(path.dirname(databaseFile), { recursive: true });
842 if (kind === "dangling symlink") {
843 yield* fs.makeDirectory(path.join(root, "data", "sub"));
844 yield* fs.symlink(path.join(root, "data", "sub"), path.dirname(databasePath));
845 } else {
846 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
847 }
848 yield* fs.writeFileString(databaseFile, original);
849 if (kind !== "file") yield* fs.symlink(linkTarget, databasePath);
850 const encodedDatabasePath = JSON.stringify(databasePath);
851 const childSource = `
852import { realpathSync, unlinkSync, writeFileSync } from "node:fs";
853const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
854if (context.update?.status === "pending") {
855 writeFileSync(context.update.dbPath, "database after migration");
856 writeFileSync(context.update.dbPath + "-wal", "trial wal");
857 writeFileSync(context.update.dbPath + "-shm", "trial shm");
858 ${kind === "dangling symlink" ? "unlinkSync(realpathSync(context.update.dbPath));" : ""}
859 process.exit(1);
860} else if (context.update === undefined) {
861 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
862 setInterval(() => {}, 1_000);
863} else {
864 process.exit(0);
865}
866`;
867 for (const version of ["1.0.0", "1.1.0"]) {
868 yield* writeFakeRuntime(
869 fs,
870 path,
871 path.join(root, "runtime", "versions", version),
872 childSource,
873 );
874 }
875 yield* Effect.promise(() =>
876 writeServiceState(statePath, {
877 protocol: SERVICE_LAUNCHER_PROTOCOL,
878 activeVersion: "1.0.0",
879 }),
880 );
881
882 const launcher = new Launcher(
883 root,
884 yield* Effect.promise(() => readServiceState(statePath)),
885 );
886 yield* Effect.promise(() =>
887 launcher.run().then(
888 () => Promise.reject(new Error("launcher unexpectedly completed")),
889 () => Promise.resolve(),
890 ),
891 );
892
893 const state = yield* Effect.promise(() => readServiceState(statePath));
894 assert.equal(state.activeVersion, "1.0.0");
895 assert.equal(state.update?.status, "rolled-back");
896 assert.equal(yield* fs.readFileString(databaseFile), original);
897 if (kind !== "file") assert.equal(yield* fs.readLink(databasePath), linkTarget);
898 assert.isFalse(yield* fs.exists(path.join(root, "original.sqlite")));
899 assert.isFalse(yield* fs.exists(`${databasePath}-wal`));
900 assert.isFalse(yield* fs.exists(`${databasePath}-shm`));
901 const updateId = state.update?.id;
902 assert.isDefined(updateId);
903 assert.isFalse(yield* fs.exists(path.join(root, "runtime", "db-backup", updateId)));
904 }),
905 );
906
907 it.effect.each(["wal", "delete"] as const)(
908 "backs up a %s-mode database (online when WAL) and restores its final state",
909 (journalMode) =>
910 Effect.gen(function* () {
911 const fs = yield* FileSystem.FileSystem;
912 const path = yield* Path.Path;
913 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-online-" });
914 const statePath = path.join(root, "runtime", "service-state.json");
915 const databasePath = path.join(root, "userdata", "state.sqlite");
916 const observationsPath = path.join(root, "observations.json");
917 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
918 // SQLite keeps -wal beside the symlink's target, so the backup must restore it there.
919 yield* fs.symlink("actual.sqlite", databasePath);
920 const seed = new NodeSqlite.DatabaseSync(databasePath);
921 seed.exec(`
922 PRAGMA journal_mode = ${journalMode};
923 CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT NOT NULL);
924 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 500)
925 INSERT INTO events (payload) SELECT 'before the update ' || i FROM n;
926 `);
927 seed.close();
928
929 const encoded = JSON.stringify({ root, databasePath, observationsPath, journalMode });
930 const childSource = `
931import { readdirSync, writeFileSync } from "node:fs";
932import { DatabaseSync } from "node:sqlite";
933const paths = ${encoded};
934const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
935if (context.update?.status === "pending") {
936 writeFileSync(paths.observationsPath + ".trial", JSON.stringify(
937 readdirSync(paths.root + "/runtime/db-backup/" + context.update.id).sort(),
938 ));
939 const trial = new DatabaseSync(context.update.dbPath);
940 trial.exec("PRAGMA journal_mode = " + paths.journalMode + "; INSERT INTO events (payload) VALUES ('trial');");
941 trial.close();
942 process.exit(1);
943} else if (context.update === undefined) {
944 const db = new DatabaseSync(paths.databasePath);
945 db.exec("PRAGMA busy_timeout = 5000;");
946 db.exec("PRAGMA journal_mode = " + paths.journalMode + ";");
947 const insert = db.prepare("INSERT INTO events (payload) VALUES (?)");
948 const writer = setInterval(() => insert.run("written while serving"), 1);
949 process.once("SIGTERM", () => {
950 clearInterval(writer);
951 insert.run("last write before stopping");
952 const backupRoot = paths.root + "/runtime/db-backup";
953 writeFileSync(paths.observationsPath, JSON.stringify({
954 backupsAtStop: readdirSync(backupRoot).map((entry) => readdirSync(backupRoot + "/" + entry)),
955 rows: db.prepare("SELECT count(*) AS n FROM events").get().n,
956 }));
957 db.close();
958 process.exit(0);
959 });
960 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
961} else {
962 process.exit(0);
963}
964`;
965 for (const version of ["1.0.0", "1.1.0"]) {
966 yield* writeFakeRuntime(
967 fs,
968 path,
969 path.join(root, "runtime", "versions", version),
970 childSource,
971 );
972 }
973 yield* Effect.promise(() =>
974 writeServiceState(statePath, {
975 protocol: SERVICE_LAUNCHER_PROTOCOL,
976 activeVersion: "1.0.0",
977 }),
978 );
979
980 const launcher = new Launcher(
981 root,
982 yield* Effect.promise(() => readServiceState(statePath)),
983 {
984 backupSpaceProbe: { canClone: async () => false },
985 },
986 );
987 yield* Effect.promise(() =>
988 launcher.run().then(
989 () => Promise.reject(new Error("launcher unexpectedly completed")),
990 () => Promise.resolve(),
991 ),
992 );
993
994 const state = yield* Effect.promise(() => readServiceState(statePath));
995 assert.equal(state.update?.status, "rolled-back");
996 const observed = JSON.parse(yield* fs.readFileString(observationsPath));
997 // A WAL database's main file is copied before the server is asked to stop; others fall back offline.
998 assert.deepEqual(observed.backupsAtStop, journalMode === "wal" ? [["database"]] : []);
999 assert.isAbove(observed.rows, 501);
1000 // Only the online copy holds no -shm: the offline fallback copies the one the server left.
1001 assert.deepEqual(
1002 JSON.parse(yield* fs.readFileString(`${observationsPath}.trial`)),
1003 journalMode === "wal" ? ["database", "database-wal"] : ["database"],
1004 );
1005 const restored = new NodeSqlite.DatabaseSync(databasePath);
1006 try {
1007 assert.equal(restored.prepare("PRAGMA integrity_check").get()?.integrity_check, "ok");
1008 assert.equal(
1009 restored.prepare("SELECT count(*) AS n FROM events").get()?.n,
1010 observed.rows,
1011 );
1012 assert.equal(
1013 restored
1014 .prepare(
1015 "SELECT count(*) AS n FROM events WHERE payload = 'last write before stopping'",
1016 )
1017 .get()?.n,
1018 1,
1019 );
1020 } finally {
1021 restored.close();
1022 }
1023 }),
1024 );
1025
1026 const requestRejectedUpdate = (backupSpaceProbe: Partial<BackupSpaceProbe>) =>
1027 Effect.gen(function* () {
1028 const fs = yield* FileSystem.FileSystem;
1029 const path = yield* Path.Path;
1030 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-space-" });
1031 const statePath = path.join(root, "runtime", "service-state.json");
1032 const databasePath = path.join(root, "userdata", "state.sqlite");
1033 const replyPath = path.join(root, "rejection.txt");
1034 const trialMarker = path.join(root, "trial-started");
1035 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
1036 yield* fs.writeFileString(databasePath, "database");
1037 const encoded = JSON.stringify({ databasePath, replyPath, trialMarker });
1038 const childSource = `
1039import { writeFileSync } from "node:fs";
1040const paths = ${encoded};
1041const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
1042if (context.update?.status === "pending") {
1043 writeFileSync(paths.trialMarker, "started");
1044 process.exit(1);
1045} else if (context.update === undefined) {
1046 process.on("message", (message) => {
1047 if (message.type === "update-rejected") {
1048 writeFileSync(paths.replyPath, message.reason);
1049 process.exit(0);
1050 }
1051 });
1052 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
1053 setInterval(() => {}, 1_000);
1054} else {
1055 process.exit(0);
1056}
1057`;
1058 for (const version of ["1.0.0", "1.1.0"]) {
1059 yield* writeFakeRuntime(
1060 fs,
1061 path,
1062 path.join(root, "runtime", "versions", version),
1063 childSource,
1064 );
1065 }
1066 yield* Effect.promise(() =>
1067 writeServiceState(statePath, {
1068 protocol: SERVICE_LAUNCHER_PROTOCOL,
1069 activeVersion: "1.0.0",
1070 }),
1071 );
1072
1073 const launcher = new Launcher(
1074 root,
1075 yield* Effect.promise(() => readServiceState(statePath)),
1076 { backupSpaceProbe },
1077 );
1078 yield* Effect.promise(() =>
1079 launcher.run().then(
1080 () => Promise.reject(new Error("launcher unexpectedly completed")),
1081 () => Promise.resolve(),
1082 ),
1083 );
1084
1085 return {
1086 reason: yield* fs.readFileString(replyPath),
1087 trialStarted: yield* fs.exists(trialMarker),
1088 state: yield* Effect.promise(() => readServiceState(statePath)),
1089 };
1090 });
1091
1092 it.effect("refuses a backup that cannot fit and leaves the server running", () =>
1093 Effect.gen(function* () {
1094 const { reason, trialStarted, state } = yield* requestRejectedUpdate({
1095 readFreeBytes: () => Promise.resolve(0),
1096 canClone: () => Promise.resolve(true),
1097 });
1098
1099 assert.include(reason, "Not enough free disk space");
1100 assert.include(reason, "The server was not stopped");
1101 assert.isFalse(trialStarted);
1102 assert.equal(state.activeVersion, "1.0.0");
1103 assert.isUndefined(state.update);
1104 }),
1105 );
1106
1107 it.effect("refuses the update when free space cannot be checked", () =>
1108 Effect.gen(function* () {
1109 const { reason, trialStarted, state } = yield* requestRejectedUpdate({
1110 readFreeBytes: () => Promise.reject(new Error("statfs unavailable")),
1111 });
1112
1113 assert.include(
1114 reason,
1115 "Could not check that the database backup fits before updating: statfs unavailable",
1116 );
1117 assert.isFalse(trialStarted);
1118 assert.equal(state.activeVersion, "1.0.0");
1119 assert.isUndefined(state.update);
1120 }),
1121 );
1122
1123 it.effect("holds its lock while it serves and stops the server over IPC, marker set", () =>
1124 Effect.gen(function* () {
1125 const fs = yield* FileSystem.FileSystem;
1126 const path = yield* Path.Path;
1127 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-control-" });
1128 const statePath = path.join(root, "runtime", "service-state.json");
1129 const databasePath = path.join(root, "userdata", "state.sqlite");
1130 const reportPath = path.join(root, "stopped-with-marker");
1131 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
1132 yield* fs.writeFileString(databasePath, "database");
1133 const encoded = JSON.stringify({
1134 databasePath,
1135 reportPath,
1136 markerPath: path.join(root, "runtime", SERVICE_STOP_MARKER_FILE),
1137 });
1138 const childSource = `
1139const fs = require("node:fs");
1140const paths = ${encoded};
1141process.on("message", (message) => {
1142 if (message.type !== "stop") return;
1143 fs.writeFileSync(paths.reportPath, String(fs.existsSync(paths.markerPath)));
1144 process.exit(0);
1145});
1146process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
1147`;
1148 for (const version of ["1.0.0", "1.1.0"]) {
1149 yield* writeFakeRuntime(
1150 fs,
1151 path,
1152 path.join(root, "runtime", "versions", version),
1153 childSource,
1154 );
1155 }
1156 yield* Effect.promise(() =>
1157 writeServiceState(statePath, {
1158 protocol: SERVICE_LAUNCHER_PROTOCOL,
1159 activeVersion: "1.0.0",
1160 }),
1161 );
1162 const lockPath = serviceLauncherLockPath(root);
1163 const serving = Promise.withResolvers<void>();
1164 const launcher = new Launcher(
1165 root,
1166 yield* Effect.promise(() => readServiceState(statePath)),
1167 {
1168 lockPath,
1169 stopChildOverIpc: true,
1170 // The update request proves the child is up; refusing it leaves the server running.
1171 backupSpaceProbe: {
1172 readFreeBytes: () => {
1173 serving.resolve();
1174 return Promise.resolve(0);
1175 },
1176 canClone: () => Promise.resolve(false),
1177 },
1178 },
1179 );
1180 const running = launcher.run();
1181 yield* Effect.promise(() => Promise.race([serving.promise, running]));
1182
1183 assert.isTrue(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath)));
1184 // What losing the task's console does.
1185 yield* Effect.promise(() => launcher.stop("SIGTERM"));
1186 yield* Effect.promise(() => running);
1187 assert.equal(yield* fs.readFileString(reportPath), "true");
1188 assert.isFalse(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath)));
1189 }),
1190 );
1191
1192 it.effect("leaves a pending update alone when stopped while it starts up", () =>
1193 Effect.gen(function* () {
1194 const fs = yield* FileSystem.FileSystem;
1195 const path = yield* Path.Path;
1196 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-startup-stop-" });
1197 const statePath = path.join(root, "runtime", "service-state.json");
1198 // Recovery would roll this back: the target runtime is missing.
1199 const pending = {
1200 protocol: SERVICE_LAUNCHER_PROTOCOL,
1201 activeVersion: "1.0.0",
1202 update: {
1203 id: "update-1",
1204 fromVersion: "1.0.0",
1205 targetVersion: "1.1.0",
1206 dbPath: path.join(root, "userdata", "state.sqlite"),
1207 status: "pending",
1208 },
1209 } as const;
1210 yield* Effect.promise(() => writeServiceState(statePath, pending));
1211 const lockPath = serviceLauncherLockPath(root);
1212 const launcher = new Launcher(root, pending, { lockPath });
1213
1214 const running = launcher.run();
1215 yield* Effect.promise(() => launcher.stop("SIGTERM"));
1216 yield* Effect.promise(() => running);
1217
1218 // The lock is released only once the launcher is done with the home.
1219 assert.isFalse(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath)));
1220 assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), pending);
1221 }),
1222 );
1223
1224 it.effect("records no update when the server exits during the backup check", () =>
1225 Effect.gen(function* () {
1226 const fs = yield* FileSystem.FileSystem;
1227 const path = yield* Path.Path;
1228 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-exit-" });
1229 const statePath = path.join(root, "runtime", "service-state.json");
1230 const databasePath = path.join(root, "userdata", "state.sqlite");
1231 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
1232 yield* fs.writeFileString(databasePath, "database");
1233 const encoded = JSON.stringify({ databasePath });
1234 const childSource = `
1235const paths = ${encoded};
1236process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath }, () =>
1237 process.exit(3),
1238);
1239setInterval(() => {}, 1_000);
1240`;
1241 for (const version of ["1.0.0", "1.1.0"]) {
1242 yield* writeFakeRuntime(
1243 fs,
1244 path,
1245 path.join(root, "runtime", "versions", version),
1246 childSource,
1247 );
1248 }
1249 yield* Effect.promise(() =>
1250 writeServiceState(statePath, {
1251 protocol: SERVICE_LAUNCHER_PROTOCOL,
1252 activeVersion: "1.0.0",
1253 }),
1254 );
1255 const launcher = new Launcher(
1256 root,
1257 yield* Effect.promise(() => readServiceState(statePath)),
1258 {
1259 backupSpaceProbe: {
1260 readFreeBytes: () => {
1261 const child = spawnedChildren.at(-1)!;
1262 return new Promise((resolve) => {
1263 if (!child.connected) resolve(Number.MAX_SAFE_INTEGER);
1264 else child.once("disconnect", () => resolve(Number.MAX_SAFE_INTEGER));
1265 });
1266 },
1267 },
1268 },
1269 );
1270 const failure = yield* Effect.promise(() =>
1271 launcher.run().then(
1272 () => new Error("launcher unexpectedly completed"),
1273 (cause: unknown) => cause as Error,
1274 ),
1275 );
1276
1277 assert.include(failure.message, "Active child exited unexpectedly (3)");
1278 const state = yield* Effect.promise(() => readServiceState(statePath));
1279 assert.equal(state.activeVersion, "1.0.0");
1280 assert.isUndefined(state.update);
1281 }),
1282 );
1283
1284 it.effect("reclaims partial backups left by killed updates before checking space", () =>
1285 Effect.gen(function* () {
1286 const fs = yield* FileSystem.FileSystem;
1287 const path = yield* Path.Path;
1288 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-orphan-" });
1289 const databasePath = path.join(root, "state.sqlite");
1290 yield* writeSparseFile(databasePath, 10 * 1024 ** 3);
1291 const backupRoot = path.join(root, "runtime", "db-backup");
1292 const orphan = path.join(backupRoot, "earlier-update.staging");
1293 const completed = path.join(backupRoot, "completed-update");
1294 yield* fs.makeDirectory(orphan, { recursive: true });
1295 yield* fs.writeFileString(path.join(orphan, "database"), "partial copy");
1296 yield* fs.makeDirectory(completed);
1297 yield* fs.writeFileString(path.join(completed, "database"), "complete copy");
1298
1299 // The orphan is what keeps this disk too full for a full copy.
1300 const blocker = yield* Effect.promise(() =>
1301 databaseBackupBlocker(root, databasePath, {
1302 readFreeBytes: () => Promise.resolve((NodeFS.existsSync(orphan) ? 8 : 11) * 1024 ** 3),
1303 canClone: () => Promise.resolve(false),
1304 }),
1305 );
1306
1307 assert.isUndefined(blocker);
1308 assert.isFalse(yield* fs.exists(orphan));
1309 assert.isTrue(yield* fs.exists(path.join(completed, "database")));
1310 }),
1311 );
1312
1313 it.effect("checks database backup space against clone or full-copy needs", () =>
1314 Effect.gen(function* () {
1315 const fs = yield* FileSystem.FileSystem;
1316 const path = yield* Path.Path;
1317 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-blocker-" });
1318 const databasePath = path.join(root, "state.sqlite");
1319 yield* writeSparseFile(databasePath, 10 * 1024 ** 3);
1320 const check = (free: number, cloneable: boolean) =>
1321 Effect.promise(() =>
1322 databaseBackupBlocker(root, databasePath, {
1323 readFreeBytes: () => Promise.resolve(free),
1324 canClone: () => Promise.resolve(cloneable),
1325 }),
1326 );
1327
1328 assert.isUndefined(yield* check(11 * 1024 ** 3, false));
1329 assert.isUndefined(yield* check(1.5 * 1024 ** 3, true));
1330 assert.include((yield* check(0.5 * 1024 ** 3, true)) ?? "", "1.0 GB needed, 0.5 GB free");
1331 const blocker = yield* check(8 * 1024 ** 3, false);
1332 assert.include(blocker ?? "", "Not enough free disk space");
1333 assert.include(blocker ?? "", "10.8 GB needed, 8.0 GB free");
1334 assert.include(blocker ?? "", "The server was not stopped");
1335 }),
1336 );
1337});