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

serviceLauncher.test.ts

1,378 lines52.9 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off - observes the children the launcher spawns with Node built-ins.
2import type * as NodeChildProcess from "node:child_process";
3// @effect-diagnostics-next-line nodeBuiltinImport:off - the free-space probe is a plain Promise callback.
4import * as NodeFS from "node:fs";
5// @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("keeps the service manager's append log bounded when it starts", () =>
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-log-" });
310 const home = path.join(root, "home");
311 const unitPath = path.join(home, "Library", "LaunchAgents", "t3code.plist");
312 const plan = unitPlan(root, "1.0.0");
313 yield* fs.makeDirectory(path.dirname(unitPath), { recursive: true });
314 yield* fs.writeFileString(
315 unitPath,
316 renderBootServicePlist(plan, { homeDir: home, environmentPath: "" }),
317 );
318 const oversized = 64 * 1024 * 1024;
319 yield* fs.makeDirectory(path.dirname(plan.logPath), { recursive: true });
320 yield* fs.writeFileString(plan.logPath, "");
321 yield* fs.truncate(plan.logPath, oversized);
322 yield* writeFakeRuntime(
323 fs,
324 path,
325 path.join(root, "runtime", "versions", "1.0.0"),
326 "process.exit(0);\n",
327 );
328 yield* Effect.promise(() =>
329 writeServiceState(path.join(root, "runtime", "service-state.json"), {
330 protocol: SERVICE_LAUNCHER_PROTOCOL,
331 activeVersion: "1.0.0",
332 }),
333 );
334 vi.stubEnv("HOME", home);
335 vi.stubEnv("T3_BOOT_SERVICE_UNIT", "t3code.plist");
336​
337 yield* Effect.promise(() =>
338 expect(runLauncher(root)).rejects.toThrow("Active child exited unexpectedly (0)."),
339 );
340​
341 const { size } = yield* fs.stat(plan.logPath);
342 expect(Number(size)).toBeLessThan(oversized);
343 }),
344 );
345​
346 it.effect("adopts a legacy install record without rewriting it", () =>
347 Effect.gen(function* () {
348 const fs = yield* FileSystem.FileSystem;
349 const path = yield* Path.Path;
350 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-migrate-" });
351 const statePath = path.join(root, "runtime", "service-state.json");
352 const activeVersion = "0.0.43-nightly.20260919.1962+build.1";
353 const versionDir = path.join(root, "runtime", "versions", activeVersion);
354 yield* writeFakeRuntime(
355 fs,
356 path,
357 versionDir,
358 `
359import { writeFileSync } from "node:fs";
360writeFileSync(new URL("./started", import.meta.url), "");
361process.exit(0);
362`,
363 );
364 const legacyContents = `{ "protocol": 2, "activeVersion": "${activeVersion}" }`;
365 yield* fs.writeFileString(statePath, legacyContents);
366 const restartPending = path.join(root, "runtime", ".restart-pending");
367 yield* fs.writeFileString(restartPending, `${activeVersion}\n`);
368​
369 yield* Effect.promise(() =>
370 expect(runLauncher(root)).rejects.toThrow("Active child exited unexpectedly (0)."),
371 );
372​
373 assert.isTrue(yield* fs.exists(path.join(versionDir, "started")));
374 assert.isFalse(yield* fs.exists(restartPending));
375 assert.equal(yield* fs.readFileString(statePath), legacyContents);
376 }),
377 );
378​
379 it.effect("refuses non-install legacy documents without rewriting or spawning", () =>
380 Effect.gen(function* () {
381 const fs = yield* FileSystem.FileSystem;
382 const path = yield* Path.Path;
383 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-reject-" });
384 const statePath = path.join(root, "runtime", "service-state.json");
385 yield* writeFakeRuntime(
386 fs,
387 path,
388 path.join(root, "runtime", "versions", "1.0.0"),
389 "process.exit(0);\n",
390 );
391 const legacy = { protocol: 2, activeVersion: "1.0.0" };
392 const childCount = spawnedChildren.length;
393 for (const contents of [
394 JSON.stringify({
395 ...legacy,
396 update: {
397 id: "u",
398 fromVersion: "1.0.0",
399 targetVersion: "1.1.0",
400 dbPath: "/tmp/state.sqlite",
401 status: "pending",
402 },
403 }),
404 JSON.stringify({ ...legacy, update: null }),
405 JSON.stringify({ ...legacy, extra: true }),
406 JSON.stringify({ ...legacy, protocol: 1 }),
407 JSON.stringify({ ...legacy, protocol: 5 }),
408 JSON.stringify({ ...legacy, activeVersion: "latest" }),
409 "{ invalid JSON",
410 ]) {
411 yield* fs.writeFileString(statePath, contents);
412 yield* Effect.promise(() =>
413 expect(runLauncher(root)).rejects.toThrow("Service state is invalid or unsupported."),
414 );
415 assert.equal(yield* fs.readFileString(statePath), contents);
416 assert.equal(spawnedChildren.length, childCount);
417 }
418 }),
419 );
420​
421 it.effect("refuses a legacy state whose runtime is missing without rewriting or spawning", () =>
422 Effect.gen(function* () {
423 const fs = yield* FileSystem.FileSystem;
424 const path = yield* Path.Path;
425 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-layout-" });
426 const statePath = path.join(root, "runtime", "service-state.json");
427 const contents = '{ "protocol": 2, "activeVersion": "1.0.0" }';
428 yield* fs.makeDirectory(path.dirname(statePath), { recursive: true });
429 yield* fs.writeFileString(statePath, contents);
430 const childCount = spawnedChildren.length;
431​
432 yield* Effect.promise(() =>
433 expect(runLauncher(root)).rejects.toThrow(
434 "Selected t3@1.0.0 runtime is missing or incomplete.",
435 ),
436 );
437 assert.equal(yield* fs.readFileString(statePath), contents);
438 assert.equal(spawnedChildren.length, childCount);
439 }),
440 );
441​
442 it.effect("a fresh launcher clears a restart deferred by t3 update", () =>
443 Effect.gen(function* () {
444 const fs = yield* FileSystem.FileSystem;
445 const path = yield* Path.Path;
446 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-restart-" });
447 const statePath = path.join(root, "runtime", "service-state.json");
448 const restartPending = path.join(root, "runtime", SERVICE_RESTART_PENDING_FILE);
449 yield* writeFakeRuntime(
450 fs,
451 path,
452 path.join(root, "runtime", "versions", "1.0.0"),
453 "setInterval(() => {}, 1_000);\n",
454 );
455 yield* Effect.promise(() =>
456 writeServiceState(statePath, {
457 protocol: SERVICE_LAUNCHER_PROTOCOL,
458 activeVersion: "1.0.0",
459 }),
460 );
461 const run = () =>
462 Effect.gen(function* () {
463 const launcher = new Launcher(
464 root,
465 yield* Effect.promise(() => readServiceState(statePath)),
466 );
467 const running = launcher.run();
468 yield* Effect.promise(() => launcher.stop("SIGTERM"));
469 yield* Effect.promise(() => running);
470 });
471​
472 yield* fs.writeFileString(restartPending, "1.0.1\n");
473 yield* run();
474 assert.isTrue(yield* fs.exists(restartPending));
475​
476 yield* fs.writeFileString(restartPending, "1.0.0\n");
477 yield* run();
478 assert.isFalse(yield* fs.exists(restartPending));
479 }),
480 );
481​
482 it.effect.each([
483 { unitVersion: "1.0.0", replacement: "an intentional downgrade" },
484 { unitVersion: "1.2.0", replacement: "another T3 home" },
485 ])(
486 "recovers a rolled-back update with unit $unitVersion and preserves $replacement",
487 ({ unitVersion, replacement }) =>
488 Effect.gen(function* () {
489 const fs = yield* FileSystem.FileSystem;
490 const path = yield* Path.Path;
491 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-repoint-" });
492 const statePath = path.join(root, "runtime", "service-state.json");
493 yield* writeFakeRuntime(
494 fs,
495 path,
496 path.join(root, "runtime", "versions", "1.1.0"),
497 "setInterval(() => {}, 1_000);\n",
498 );
499 yield* Effect.promise(() =>
500 writeServiceState(statePath, {
501 protocol: SERVICE_LAUNCHER_PROTOCOL,
502 activeVersion: "1.1.0",
503 update: {
504 id: "update-1",
505 fromVersion: "1.1.0",
506 targetVersion: "1.2.0",
507 status: "rolled-back",
508 },
509 }),
510 );
511 const unit = yield* fakeServiceUnit(fs, path, root, unitVersion);
512 const expected = renderBootServiceUnit(
513 unitPlan(root, unitVersion === "1.0.0" ? "1.1.0" : unitVersion),
514 );
515 const createLauncher = Effect.gen(function* () {
516 return new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)), {
517 serviceUnit: unit,
518 });
519 });
520 const run = (launcher: Launcher) =>
521 Effect.gen(function* () {
522 const running = launcher.run();
523 yield* Effect.promise(() => launcher.stop("SIGTERM"));
524 yield* Effect.promise(() => running);
525 });
526​
527 yield* run(yield* createLauncher);
528 assert.equal(yield* fs.readFileString(unit.path), expected);
529 assert.equal(unit.loadedContents, expected);
530​
531 yield* run(yield* createLauncher);
532 assert.equal(yield* fs.readFileString(unit.path), expected);
533 assert.equal(unit.loadedContents, expected);
534​
535 yield* Effect.promise(() =>
536 writeServiceState(statePath, {
537 protocol: SERVICE_LAUNCHER_PROTOCOL,
538 activeVersion: "1.1.0",
539 update: {
540 id: "update-2",
541 fromVersion: "1.0.0",
542 targetVersion: "1.1.0",
543 status: "committed",
544 },
545 }),
546 );
547 const staleLauncher = yield* createLauncher;
548 // A local install can replace the selection or service owner without stopping this launcher.
549 const selectedRoot =
550 replacement === "another T3 home" ? path.join(root, "other-home") : root;
551 yield* writeFakeRuntime(
552 fs,
553 path,
554 path.join(selectedRoot, "runtime", "versions", "1.0.0"),
555 "setInterval(() => {}, 1_000);\n",
556 );
557 const selectedStatePath = path.join(selectedRoot, "runtime", "service-state.json");
558 yield* Effect.promise(() =>
559 writeServiceState(selectedStatePath, {
560 protocol: SERVICE_LAUNCHER_PROTOCOL,
561 activeVersion: "1.0.0",
562 }),
563 );
564 const selectedUnit = renderBootServiceUnit({
565 ...unitPlan(selectedRoot, "1.0.0"),
566 unitPath: unit.path,
567 });
568 yield* fs.writeFileString(unit.path, selectedUnit);
569 yield* Effect.promise(() => unit.reload());
570 const oldHomeState = yield* fs.readFileString(statePath);
571 const selectedState = yield* fs.readFileString(selectedStatePath);
572​
573 yield* run(staleLauncher);
574 assert.equal(yield* fs.readFileString(statePath), oldHomeState);
575 assert.equal(yield* fs.readFileString(selectedStatePath), selectedState);
576 assert.equal(yield* fs.readFileString(unit.path), selectedUnit, replacement);
577 assert.equal(unit.loadedContents, selectedUnit, replacement);
578 }),
579 );
580​
581 it.effect("stays idle instead of exiting when another server owns the T3 home", () =>
582 Effect.gen(function* () {
583 const fs = yield* FileSystem.FileSystem;
584 const path = yield* Path.Path;
585 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-refused-" });
586 const statePath = path.join(root, "runtime", "service-state.json");
587 yield* writeFakeRuntime(
588 fs,
589 path,
590 path.join(root, "runtime", "versions", "1.0.0"),
591 `process.exit(${SERVER_EXIT_CODE_STATE_DIR_OWNED});\n`,
592 );
593 yield* Effect.promise(() =>
594 writeServiceState(statePath, {
595 protocol: SERVICE_LAUNCHER_PROTOCOL,
596 activeVersion: "1.0.0",
597 }),
598 );
599 const refused = Promise.withResolvers<void>();
600 yield* Effect.acquireRelease(
601 Effect.sync(() =>
602 vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
603 if (String(chunk).includes("owns this T3 home")) refused.resolve();
604 return true;
605 }),
606 ),
607 (spy) => Effect.sync(() => spy.mockRestore()),
608 );
609 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
610 let completed = false;
611 const running = launcher.run().finally(() => {
612 completed = true;
613 });
614 yield* Effect.promise(() => refused.promise);
615 assert.isFalse(completed);
616 yield* Effect.promise(() => launcher.stop("SIGTERM"));
617 yield* Effect.promise(() => running);
618 }),
619 );
620​
621 const commitUpdate = (
622 render = renderBootServiceUnit,
623 missingUnit = false,
624 legacyInstall = false,
625 ) =>
626 Effect.gen(function* () {
627 const fs = yield* FileSystem.FileSystem;
628 const path = yield* Path.Path;
629 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service 100% & <test>-" });
630 const statePath = path.join(root, "runtime", "service-state.json");
631 const databasePath = path.join(root, "userdata", "state.sqlite");
632 const activatedPath = path.join(root, "activated");
633 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
634 yield* fs.writeFileString(databasePath, "before trial");
635 const unit = yield* fakeServiceUnit(fs, path, root, "1.0.0", render);
636 if (missingUnit) yield* fs.remove(unit.path);
637 const childSource = `
638import assert from "node:assert/strict";
639import { existsSync, readFileSync, writeFileSync } from "node:fs";
640const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
641assert.equal(context.protocol, ${SERVICE_LAUNCHER_PROTOCOL});
642if (context.update?.status === "pending") {
643 const state = JSON.parse(readFileSync(${JSON.stringify(statePath)}, "utf8"));
644 assert.equal(state.activeVersion, "1.0.0");
645 assert.equal(state.update.status, "pending");
646 ${
647 missingUnit
648 ? `assert.equal(existsSync(${JSON.stringify(unit.path)}), false);`
649 : `assert.equal(readFileSync(${JSON.stringify(unit.path)}, "utf8"), ${JSON.stringify(unit.loadedContents)});`
650 }
651 process.on("message", (message) => {
652 if (message.type === "committed") {
653 const state = JSON.parse(readFileSync(${JSON.stringify(statePath)}, "utf8"));
654 assert.equal(state.protocol, ${SERVICE_LAUNCHER_PROTOCOL});
655 assert.equal(state.activeVersion, "1.1.0");
656 assert.equal(state.update.status, "committed");
657 writeFileSync(${JSON.stringify(activatedPath)}, message.updateId);
658 process.exit(0);
659 }
660 });
661 process.send({ type: "prepared", updateId: context.update.id });
662} else if (context.update === undefined) {
663 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${JSON.stringify(databasePath)} });
664 setInterval(() => {}, 1_000);
665} else {
666 process.exit(0);
668`;
669 for (const version of ["1.0.0", "1.1.0"]) {
670 yield* writeFakeRuntime(
671 fs,
672 path,
673 path.join(root, "runtime", "versions", version),
674 childSource,
675 );
676 }
677 // The old CLI installs the new runtime but writes state with its own protocol.
678 yield* fs.writeFileString(
679 statePath,
680 `${JSON.stringify(
681 {
682 protocol: legacyInstall ? 3 : SERVICE_LAUNCHER_PROTOCOL,
683 activeVersion: "1.0.0",
684 },
685 null,
686 2,
687 )}\n`,
688 );
689 const launcher = new Launcher(
690 root,
691 yield* Effect.promise(() => readServiceState(statePath)),
692 { serviceUnit: unit },
693 );
694 const failure = yield* Effect.promise(() =>
695 launcher.run().then(
696 () => "launcher unexpectedly completed",
697 (cause: unknown) => String(cause),
698 ),
699 );
700 assert.include(failure, "Active child exited unexpectedly (0)");
701 const state = yield* Effect.promise(() => readServiceState(statePath));
702 assert.equal(state.activeVersion, "1.1.0");
703 assert.equal(state.update?.status, "committed");
704 assert.equal(yield* fs.readFileString(activatedPath), state.update?.id);
705 const recover = () =>
706 Effect.gen(function* () {
707 const fresh = new Launcher(
708 root,
709 yield* Effect.promise(() => readServiceState(statePath)),
710 { serviceUnit: unit },
711 );
712 const running = fresh.run();
713 yield* Effect.promise(() => fresh.stop("SIGTERM"));
714 yield* Effect.promise(() => running);
715 });
716 return { fs, root, unit, recover };
717 });
718​
719 it.effect.each([
720 {
721 name: "systemd after a protocol-3 local upgrade",
722 render: renderBootServiceUnit,
723 legacyInstall: true,
724 },
725 {
726 name: "launchd",
727 legacyInstall: false,
728 render: (plan: Parameters<typeof renderBootServicePlist>[0]) =>
729 renderBootServicePlist(plan, {
730 homeDir: "/Users/test & <user>",
731 environmentPath: "/usr/bin:/custom/runtime/versions/1.0.0",
732 }),
733 },
734 {
735 name: "Task Scheduler",
736 legacyInstall: false,
737 render: (plan: Parameters<typeof renderBootServiceTask>[0]) =>
738 renderBootServiceTask(
739 { ...plan, program: [`${plan.program[0]}.exe`, "__service-launcher"] },
740 { userId: "PC\\theo", homeDir: "C:\\Users\\theo", conhostPath: "conhost.exe" },
741 ),
742 },
743 ])(
744 "commits and repoints $name only after the trial reports prepared",
745 ({ render, legacyInstall }) =>
746 Effect.gen(function* () {
747 const { fs, root, unit } = yield* commitUpdate(render, false, legacyInstall);
748 const expected = render(unitPlan(root, "1.1.0"));
749 assert.equal(yield* fs.readFileString(unit.path), expected);
750 assert.equal(unit.loadedContents, expected);
751 assert.equal(unit.reloads, 1);
752 }),
753 );
754​
755 it.effect(
756 "keeps a durable commit through unit failure and retries a failed reload on restart",
757 () =>
758 Effect.gen(function* () {
759 const { fs, root, unit, recover } = yield* commitUpdate(renderBootServiceUnit, true);
760 assert.equal(unit.reloads, 0);
761 const original = renderBootServiceUnit(unitPlan(root, "1.0.0"));
762 const expected = renderBootServiceUnit(unitPlan(root, "1.1.0"));
763 assert.equal(unit.loadedContents, original);
764 yield* fs.writeFileString(unit.path, original);
765 unit.failReload = true;
766 yield* recover();
767 assert.equal(yield* fs.readFileString(unit.path), expected);
768 assert.equal(unit.reloads, 1);
769 assert.equal(unit.loadedContents, original);
770​
771 unit.failReload = false;
772 yield* recover();
773 assert.equal(yield* fs.readFileString(unit.path), expected);
774 assert.equal(unit.loadedContents, expected);
775 assert.equal(unit.reloads, 2);
776 }),
777 );
778​
779 it.effect("rolls back invalid trials with the startup environment", () =>
780 Effect.gen(function* () {
781 const fs = yield* FileSystem.FileSystem;
782 const path = yield* Path.Path;
783 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
784 const statePath = path.join(root, "runtime", "service-state.json");
785 const databasePath = path.join(root, "userdata", "state.sqlite");
786 const observationsPath = path.join(root, "environment-observations.jsonl");
787 const envPath = path.join(root, SERVICE_ENV_FILE);
788 yield* fs.writeFileString(envPath, "T3CODE_TEST_SERVICE_TOKEN=initial\n");
789 vi.stubEnv("T3CODE_HOME", root);
790 vi.stubEnv("T3CODE_TEST_SERVICE_TOKEN", "inherited");
791 yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs()));
792 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
793 yield* fs.writeFileString(databasePath, "before trial");
794 const encodedDatabasePath = JSON.stringify(databasePath);
795 const childSource = `
796import { appendFileSync, writeFileSync } from "node:fs";
797const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
798appendFileSync(${JSON.stringify(observationsPath)}, JSON.stringify({
799 token: process.env.T3CODE_TEST_SERVICE_TOKEN,
800 update: context.update?.status ?? "active",
801}) + "\\n");
802if (context.update?.status === "pending") {
803 process.send({ type: "prepared", updateId: "wrong-update" });
804} else if (context.update === undefined) {
805 writeFileSync(${JSON.stringify(envPath)}, "T3CODE_TEST_SERVICE_TOKEN=changed\\n");
806 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
807 setInterval(() => {}, 1_000);
808} else {
809 process.exit(0);
811`;
812 for (const version of ["1.0.0", "1.1.0"]) {
813 yield* writeFakeRuntime(
814 fs,
815 path,
816 path.join(root, "runtime", "versions", version),
817 childSource,
818 );
819 }
820 yield* Effect.promise(() =>
821 writeServiceState(statePath, {
822 protocol: SERVICE_LAUNCHER_PROTOCOL,
823 activeVersion: "1.0.0",
824 }),
825 );
826 const unit = yield* fakeServiceUnit(fs, path, root, "0.9.0");
827​
828 const launcher = new Launcher(
829 root,
830 yield* Effect.promise(() => readServiceState(statePath)),
831 {
832 serviceUnit: unit,
833 environment: yield* Effect.promise(() => readServiceEnvironment(root)),
834 },
835 );
836 yield* Effect.promise(() =>
837 launcher.run().then(
838 () => Promise.reject(new Error("launcher unexpectedly completed")),
839 () => Promise.resolve(),
840 ),
841 );
842​
843 const state = yield* Effect.promise(() => readServiceState(statePath));
844 assert.equal(state.activeVersion, "1.0.0");
845 assert.equal(state.update?.status, "rolled-back");
846 assert.equal(
847 yield* fs.readFileString(unit.path),
848 renderBootServiceUnit(unitPlan(root, "1.0.0")),
849 );
850 assert.equal(unit.reloads, 1);
851 assert.equal(
852 state.update?.status === "rolled-back" ? state.update.reason : undefined,
853 "invalid-prepared",
854 );
855 const observations = (yield* fs.readFileString(observationsPath))
856 .trim()
857 .split("\n")
858 .map((line) => JSON.parse(line));
859 assert.deepEqual(observations, [
860 { token: "initial", update: "active" },
861 { token: "initial", update: "pending" },
862 { token: "initial", update: "rolled-back" },
863 ]);
864 assert.equal((yield* HostProcess.Environment).T3CODE_TEST_SERVICE_TOKEN, "inherited");
865 assert.equal(yield* fs.readFileString(envPath), "T3CODE_TEST_SERVICE_TOKEN=changed\n");
866 }),
867 );
868​
869 it.effect.each(["file", "symlink", "dangling symlink"] as const)(
870 "restores the database when a migrating trial exits, with the database a %s",
871 (kind) =>
872 Effect.gen(function* () {
873 const fs = yield* FileSystem.FileSystem;
874 const path = yield* Path.Path;
875 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-db-" });
876 const statePath = path.join(root, "runtime", "service-state.json");
877 const databasePath = path.join(root, "userdata", "state.sqlite");
878 const databaseFile =
879 kind === "file" ? databasePath : path.join(root, "data", "original.sqlite");
880 const linkTarget = kind === "dangling symlink" ? "../original.sqlite" : databaseFile;
881 const original = "database before migration";
882 yield* fs.makeDirectory(path.dirname(databaseFile), { recursive: true });
883 if (kind === "dangling symlink") {
884 yield* fs.makeDirectory(path.join(root, "data", "sub"));
885 yield* fs.symlink(path.join(root, "data", "sub"), path.dirname(databasePath));
886 } else {
887 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
888 }
889 yield* fs.writeFileString(databaseFile, original);
890 if (kind !== "file") yield* fs.symlink(linkTarget, databasePath);
891 const encodedDatabasePath = JSON.stringify(databasePath);
892 const childSource = `
893import { realpathSync, unlinkSync, writeFileSync } from "node:fs";
894const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
895if (context.update?.status === "pending") {
896 writeFileSync(context.update.dbPath, "database after migration");
897 writeFileSync(context.update.dbPath + "-wal", "trial wal");
898 writeFileSync(context.update.dbPath + "-shm", "trial shm");
899 ${kind === "dangling symlink" ? "unlinkSync(realpathSync(context.update.dbPath));" : ""}
900 process.exit(1);
901} else if (context.update === undefined) {
902 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
903 setInterval(() => {}, 1_000);
904} else {
905 process.exit(0);
907`;
908 for (const version of ["1.0.0", "1.1.0"]) {
909 yield* writeFakeRuntime(
910 fs,
911 path,
912 path.join(root, "runtime", "versions", version),
913 childSource,
914 );
915 }
916 yield* Effect.promise(() =>
917 writeServiceState(statePath, {
918 protocol: SERVICE_LAUNCHER_PROTOCOL,
919 activeVersion: "1.0.0",
920 }),
921 );
922​
923 const launcher = new Launcher(
924 root,
925 yield* Effect.promise(() => readServiceState(statePath)),
926 );
927 yield* Effect.promise(() =>
928 launcher.run().then(
929 () => Promise.reject(new Error("launcher unexpectedly completed")),
930 () => Promise.resolve(),
931 ),
932 );
933​
934 const state = yield* Effect.promise(() => readServiceState(statePath));
935 assert.equal(state.activeVersion, "1.0.0");
936 assert.equal(state.update?.status, "rolled-back");
937 assert.equal(yield* fs.readFileString(databaseFile), original);
938 if (kind !== "file") assert.equal(yield* fs.readLink(databasePath), linkTarget);
939 assert.isFalse(yield* fs.exists(path.join(root, "original.sqlite")));
940 assert.isFalse(yield* fs.exists(`${databasePath}-wal`));
941 assert.isFalse(yield* fs.exists(`${databasePath}-shm`));
942 const updateId = state.update?.id;
943 assert.isDefined(updateId);
944 assert.isFalse(yield* fs.exists(path.join(root, "runtime", "db-backup", updateId)));
945 }),
946 );
947​
948 it.effect.each(["wal", "delete"] as const)(
949 "backs up a %s-mode database (online when WAL) and restores its final state",
950 (journalMode) =>
951 Effect.gen(function* () {
952 const fs = yield* FileSystem.FileSystem;
953 const path = yield* Path.Path;
954 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-online-" });
955 const statePath = path.join(root, "runtime", "service-state.json");
956 const databasePath = path.join(root, "userdata", "state.sqlite");
957 const observationsPath = path.join(root, "observations.json");
958 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
959 // SQLite keeps -wal beside the symlink's target, so the backup must restore it there.
960 yield* fs.symlink("actual.sqlite", databasePath);
961 const seed = new NodeSqlite.DatabaseSync(databasePath);
962 seed.exec(`
963 PRAGMA journal_mode = ${journalMode};
964 CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT NOT NULL);
965 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 500)
966 INSERT INTO events (payload) SELECT 'before the update ' || i FROM n;
967 `);
968 seed.close();
969​
970 const encoded = JSON.stringify({ root, databasePath, observationsPath, journalMode });
971 const childSource = `
972import { readdirSync, writeFileSync } from "node:fs";
973import { DatabaseSync } from "node:sqlite";
974const paths = ${encoded};
975const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
976if (context.update?.status === "pending") {
977 writeFileSync(paths.observationsPath + ".trial", JSON.stringify(
978 readdirSync(paths.root + "/runtime/db-backup/" + context.update.id).sort(),
979 ));
980 const trial = new DatabaseSync(context.update.dbPath);
981 trial.exec("PRAGMA journal_mode = " + paths.journalMode + "; INSERT INTO events (payload) VALUES ('trial');");
982 trial.close();
983 process.exit(1);
984} else if (context.update === undefined) {
985 const db = new DatabaseSync(paths.databasePath);
986 db.exec("PRAGMA busy_timeout = 5000;");
987 db.exec("PRAGMA journal_mode = " + paths.journalMode + ";");
988 const insert = db.prepare("INSERT INTO events (payload) VALUES (?)");
989 const writer = setInterval(() => insert.run("written while serving"), 1);
990 process.once("SIGTERM", () => {
991 clearInterval(writer);
992 insert.run("last write before stopping");
993 const backupRoot = paths.root + "/runtime/db-backup";
994 writeFileSync(paths.observationsPath, JSON.stringify({
995 backupsAtStop: readdirSync(backupRoot).map((entry) => readdirSync(backupRoot + "/" + entry)),
996 rows: db.prepare("SELECT count(*) AS n FROM events").get().n,
997 }));
998 db.close();
999 process.exit(0);
1000 });
1001 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
1002} else {
1003 process.exit(0);
1006 for (const version of ["1.0.0", "1.1.0"]) {
1007 yield* writeFakeRuntime(
1008 fs,
1009 path,
1010 path.join(root, "runtime", "versions", version),
1011 childSource,
1012 );
1014 yield* Effect.promise(() =>
1015 writeServiceState(statePath, {
1016 protocol: SERVICE_LAUNCHER_PROTOCOL,
1017 activeVersion: "1.0.0",
1018 }),
1019 );
1020​
1021 const launcher = new Launcher(
1022 root,
1023 yield* Effect.promise(() => readServiceState(statePath)),
1025 backupSpaceProbe: { canClone: async () => false },
1026 },
1027 );
1028 yield* Effect.promise(() =>
1029 launcher.run().then(
1030 () => Promise.reject(new Error("launcher unexpectedly completed")),
1031 () => Promise.resolve(),
1032 ),
1033 );
1034​
1035 const state = yield* Effect.promise(() => readServiceState(statePath));
1036 assert.equal(state.update?.status, "rolled-back");
1037 const observed = JSON.parse(yield* fs.readFileString(observationsPath));
1038 // A WAL database's main file is copied before the server is asked to stop; others fall back offline.
1039 assert.deepEqual(observed.backupsAtStop, journalMode === "wal" ? [["database"]] : []);
1040 assert.isAbove(observed.rows, 501);
1041 // Only the online copy holds no -shm: the offline fallback copies the one the server left.
1042 assert.deepEqual(
1043 JSON.parse(yield* fs.readFileString(`${observationsPath}.trial`)),
1044 journalMode === "wal" ? ["database", "database-wal"] : ["database"],
1045 );
1046 const restored = new NodeSqlite.DatabaseSync(databasePath);
1047 try {
1048 assert.equal(restored.prepare("PRAGMA integrity_check").get()?.integrity_check, "ok");
1049 assert.equal(
1050 restored.prepare("SELECT count(*) AS n FROM events").get()?.n,
1051 observed.rows,
1052 );
1053 assert.equal(
1054 restored
1055 .prepare(
1056 "SELECT count(*) AS n FROM events WHERE payload = 'last write before stopping'",
1058 .get()?.n,
1059 1,
1060 );
1061 } finally {
1062 restored.close();
1064 }),
1065 );
1066​
1067 const requestRejectedUpdate = (backupSpaceProbe: Partial<BackupSpaceProbe>) =>
1068 Effect.gen(function* () {
1069 const fs = yield* FileSystem.FileSystem;
1070 const path = yield* Path.Path;
1071 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-space-" });
1072 const statePath = path.join(root, "runtime", "service-state.json");
1073 const databasePath = path.join(root, "userdata", "state.sqlite");
1074 const replyPath = path.join(root, "rejection.txt");
1075 const trialMarker = path.join(root, "trial-started");
1076 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
1077 yield* fs.writeFileString(databasePath, "database");
1078 const encoded = JSON.stringify({ databasePath, replyPath, trialMarker });
1079 const childSource = `
1080import { writeFileSync } from "node:fs";
1081const paths = ${encoded};
1082const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
1083if (context.update?.status === "pending") {
1084 writeFileSync(paths.trialMarker, "started");
1085 process.exit(1);
1086} else if (context.update === undefined) {
1087 process.on("message", (message) => {
1088 if (message.type === "update-rejected") {
1089 writeFileSync(paths.replyPath, message.reason);
1090 process.exit(0);
1092 });
1093 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
1094 setInterval(() => {}, 1_000);
1095} else {
1096 process.exit(0);
1099 for (const version of ["1.0.0", "1.1.0"]) {
1100 yield* writeFakeRuntime(
1101 fs,
1102 path,
1103 path.join(root, "runtime", "versions", version),
1104 childSource,
1105 );
1107 yield* Effect.promise(() =>
1108 writeServiceState(statePath, {
1109 protocol: SERVICE_LAUNCHER_PROTOCOL,
1110 activeVersion: "1.0.0",
1111 }),
1112 );
1113​
1114 const launcher = new Launcher(
1115 root,
1116 yield* Effect.promise(() => readServiceState(statePath)),
1117 { backupSpaceProbe },
1118 );
1119 yield* Effect.promise(() =>
1120 launcher.run().then(
1121 () => Promise.reject(new Error("launcher unexpectedly completed")),
1122 () => Promise.resolve(),
1123 ),
1124 );
1125​
1126 return {
1127 reason: yield* fs.readFileString(replyPath),
1128 trialStarted: yield* fs.exists(trialMarker),
1129 state: yield* Effect.promise(() => readServiceState(statePath)),
1130 };
1131 });
1132​
1133 it.effect("refuses a backup that cannot fit and leaves the server running", () =>
1134 Effect.gen(function* () {
1135 const { reason, trialStarted, state } = yield* requestRejectedUpdate({
1136 readFreeBytes: () => Promise.resolve(0),
1137 canClone: () => Promise.resolve(true),
1138 });
1139​
1140 assert.include(reason, "Not enough free disk space");
1141 assert.include(reason, "The server was not stopped");
1142 assert.isFalse(trialStarted);
1143 assert.equal(state.activeVersion, "1.0.0");
1144 assert.isUndefined(state.update);
1145 }),
1146 );
1147​
1148 it.effect("refuses the update when free space cannot be checked", () =>
1149 Effect.gen(function* () {
1150 const { reason, trialStarted, state } = yield* requestRejectedUpdate({
1151 readFreeBytes: () => Promise.reject(new Error("statfs unavailable")),
1152 });
1153​
1154 assert.include(
1155 reason,
1156 "Could not check that the database backup fits before updating: statfs unavailable",
1157 );
1158 assert.isFalse(trialStarted);
1159 assert.equal(state.activeVersion, "1.0.0");
1160 assert.isUndefined(state.update);
1161 }),
1162 );
1163​
1164 it.effect("holds its lock while it serves and stops the server over IPC, marker set", () =>
1165 Effect.gen(function* () {
1166 const fs = yield* FileSystem.FileSystem;
1167 const path = yield* Path.Path;
1168 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-control-" });
1169 const statePath = path.join(root, "runtime", "service-state.json");
1170 const databasePath = path.join(root, "userdata", "state.sqlite");
1171 const reportPath = path.join(root, "stopped-with-marker");
1172 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
1173 yield* fs.writeFileString(databasePath, "database");
1174 const encoded = JSON.stringify({
1175 databasePath,
1176 reportPath,
1177 markerPath: path.join(root, "runtime", SERVICE_STOP_MARKER_FILE),
1178 });
1179 const childSource = `
1180const fs = require("node:fs");
1181const paths = ${encoded};
1182process.on("message", (message) => {
1183 if (message.type !== "stop") return;
1184 fs.writeFileSync(paths.reportPath, String(fs.existsSync(paths.markerPath)));
1185 process.exit(0);
1186});
1187process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
1189 for (const version of ["1.0.0", "1.1.0"]) {
1190 yield* writeFakeRuntime(
1191 fs,
1192 path,
1193 path.join(root, "runtime", "versions", version),
1194 childSource,
1195 );
1197 yield* Effect.promise(() =>
1198 writeServiceState(statePath, {
1199 protocol: SERVICE_LAUNCHER_PROTOCOL,
1200 activeVersion: "1.0.0",
1201 }),
1202 );
1203 const lockPath = serviceLauncherLockPath(root);
1204 const serving = Promise.withResolvers<void>();
1205 const launcher = new Launcher(
1206 root,
1207 yield* Effect.promise(() => readServiceState(statePath)),
1209 lockPath,
1210 stopChildOverIpc: true,
1211 // The update request proves the child is up; refusing it leaves the server running.
1212 backupSpaceProbe: {
1213 readFreeBytes: () => {
1214 serving.resolve();
1215 return Promise.resolve(0);
1216 },
1217 canClone: () => Promise.resolve(false),
1218 },
1219 },
1220 );
1221 const running = launcher.run();
1222 yield* Effect.promise(() => Promise.race([serving.promise, running]));
1223​
1224 assert.isTrue(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath)));
1225 // What losing the task's console does.
1226 yield* Effect.promise(() => launcher.stop("SIGTERM"));
1227 yield* Effect.promise(() => running);
1228 assert.equal(yield* fs.readFileString(reportPath), "true");
1229 assert.isFalse(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath)));
1230 }),
1231 );
1232​
1233 it.effect("leaves a pending update alone when stopped while it starts up", () =>
1234 Effect.gen(function* () {
1235 const fs = yield* FileSystem.FileSystem;
1236 const path = yield* Path.Path;
1237 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-startup-stop-" });
1238 const statePath = path.join(root, "runtime", "service-state.json");
1239 // Recovery would roll this back: the target runtime is missing.
1240 const pending = {
1241 protocol: SERVICE_LAUNCHER_PROTOCOL,
1242 activeVersion: "1.0.0",
1243 update: {
1244 id: "update-1",
1245 fromVersion: "1.0.0",
1246 targetVersion: "1.1.0",
1247 dbPath: path.join(root, "userdata", "state.sqlite"),
1248 status: "pending",
1249 },
1250 } as const;
1251 yield* Effect.promise(() => writeServiceState(statePath, pending));
1252 const lockPath = serviceLauncherLockPath(root);
1253 const launcher = new Launcher(root, pending, { lockPath });
1254​
1255 const running = launcher.run();
1256 yield* Effect.promise(() => launcher.stop("SIGTERM"));
1257 yield* Effect.promise(() => running);
1258​
1259 // The lock is released only once the launcher is done with the home.
1260 assert.isFalse(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath)));
1261 assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), pending);
1262 }),
1263 );
1264​
1265 it.effect("records no update when the server exits during the backup check", () =>
1266 Effect.gen(function* () {
1267 const fs = yield* FileSystem.FileSystem;
1268 const path = yield* Path.Path;
1269 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-exit-" });
1270 const statePath = path.join(root, "runtime", "service-state.json");
1271 const databasePath = path.join(root, "userdata", "state.sqlite");
1272 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
1273 yield* fs.writeFileString(databasePath, "database");
1274 const encoded = JSON.stringify({ databasePath });
1275 const childSource = `
1276const paths = ${encoded};
1277process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath }, () =>
1278 process.exit(3),
1280setInterval(() => {}, 1_000);
1282 for (const version of ["1.0.0", "1.1.0"]) {
1283 yield* writeFakeRuntime(
1284 fs,
1285 path,
1286 path.join(root, "runtime", "versions", version),
1287 childSource,
1288 );
1290 yield* Effect.promise(() =>
1291 writeServiceState(statePath, {
1292 protocol: SERVICE_LAUNCHER_PROTOCOL,
1293 activeVersion: "1.0.0",
1294 }),
1295 );
1296 const launcher = new Launcher(
1297 root,
1298 yield* Effect.promise(() => readServiceState(statePath)),
1300 backupSpaceProbe: {
1301 readFreeBytes: () => {
1302 const child = spawnedChildren.at(-1)!;
1303 return new Promise((resolve) => {
1304 if (!child.connected) resolve(Number.MAX_SAFE_INTEGER);
1305 else child.once("disconnect", () => resolve(Number.MAX_SAFE_INTEGER));
1306 });
1307 },
1308 },
1309 },
1310 );
1311 const failure = yield* Effect.promise(() =>
1312 launcher.run().then(
1313 () => new Error("launcher unexpectedly completed"),
1314 (cause: unknown) => cause as Error,
1315 ),
1316 );
1317​
1318 assert.include(failure.message, "Active child exited unexpectedly (3)");
1319 const state = yield* Effect.promise(() => readServiceState(statePath));
1320 assert.equal(state.activeVersion, "1.0.0");
1321 assert.isUndefined(state.update);
1322 }),
1323 );
1324​
1325 it.effect("reclaims partial backups left by killed updates before checking space", () =>
1326 Effect.gen(function* () {
1327 const fs = yield* FileSystem.FileSystem;
1328 const path = yield* Path.Path;
1329 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-orphan-" });
1330 const databasePath = path.join(root, "state.sqlite");
1331 yield* writeSparseFile(databasePath, 10 * 1024 ** 3);
1332 const backupRoot = path.join(root, "runtime", "db-backup");
1333 const orphan = path.join(backupRoot, "earlier-update.staging");
1334 const completed = path.join(backupRoot, "completed-update");
1335 yield* fs.makeDirectory(orphan, { recursive: true });
1336 yield* fs.writeFileString(path.join(orphan, "database"), "partial copy");
1337 yield* fs.makeDirectory(completed);
1338 yield* fs.writeFileString(path.join(completed, "database"), "complete copy");
1339​
1340 // The orphan is what keeps this disk too full for a full copy.
1341 const blocker = yield* Effect.promise(() =>
1342 databaseBackupBlocker(root, databasePath, {
1343 readFreeBytes: () => Promise.resolve((NodeFS.existsSync(orphan) ? 8 : 11) * 1024 ** 3),
1344 canClone: () => Promise.resolve(false),
1345 }),
1346 );
1347​
1348 assert.isUndefined(blocker);
1349 assert.isFalse(yield* fs.exists(orphan));
1350 assert.isTrue(yield* fs.exists(path.join(completed, "database")));
1351 }),
1352 );
1353​
1354 it.effect("checks database backup space against clone or full-copy needs", () =>
1355 Effect.gen(function* () {
1356 const fs = yield* FileSystem.FileSystem;
1357 const path = yield* Path.Path;
1358 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-blocker-" });
1359 const databasePath = path.join(root, "state.sqlite");
1360 yield* writeSparseFile(databasePath, 10 * 1024 ** 3);
1361 const check = (free: number, cloneable: boolean) =>
1362 Effect.promise(() =>
1363 databaseBackupBlocker(root, databasePath, {
1364 readFreeBytes: () => Promise.resolve(free),
1365 canClone: () => Promise.resolve(cloneable),
1366 }),
1367 );
1368​
1369 assert.isUndefined(yield* check(11 * 1024 ** 3, false));
1370 assert.isUndefined(yield* check(1.5 * 1024 ** 3, true));
1371 assert.include((yield* check(0.5 * 1024 ** 3, true)) ?? "", "1.0 GB needed, 0.5 GB free");
1372 const blocker = yield* check(8 * 1024 ** 3, false);
1373 assert.include(blocker ?? "", "Not enough free disk space");
1374 assert.include(blocker ?? "", "10.8 GB needed, 8.0 GB free");
1375 assert.include(blocker ?? "", "The server was not stopped");
1376 }),
1377 );
1378});