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

serviceLauncher.test.ts

1,041 lines39.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, 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 { renderBootServicePlist, renderBootServiceUnit } from "./cloud/bootService.ts";
19import {
20 databaseBackupBlocker,
21 Launcher,
22 readServiceEnvironment,
23 type BackupSpaceProbe,
24 readServiceState,
25 writeServiceState,
26} from "./serviceLauncher.ts";
27import {
28 compareExactServiceVersions,
29 decodeServiceState,
30 isExactServiceVersion,
31 SERVICE_ENV_FILE,
32 SERVICE_LAUNCHER_PROTOCOL,
33 SERVICE_RESTART_PENDING_FILE,
34} from "./cloud/serviceProtocol.ts";
35​
36const spawnedChildren = vi.hoisted((): Array<NodeChildProcess.ChildProcess> => []);
37​
38vi.mock("node:child_process", async (importOriginal) => {
39 const actual = await importOriginal<typeof NodeChildProcess>();
40 const spawn = (...args: Parameters<typeof actual.spawn>) => {
41 const child = actual.spawn(...args);
42 spawnedChildren.push(child);
43 return child;
44 };
45 return { ...actual, spawn: spawn as typeof actual.spawn };
46});
47​
48const writeSparseFile = (filePath: string, size: number) =>
49 Effect.gen(function* () {
50 const fileSystem = yield* FileSystem.FileSystem;
51 yield* fileSystem.writeFileString(filePath, "");
52 yield* fileSystem.truncate(filePath, size);
53 });
54​
55it("accepts only exact semantic versions", () => {
56 for (const version of ["0.0.0", "1.2.3", "1.2.3-alpha.1", "1.2.3-0", "1.2.3+001"]) {
57 assert.isTrue(isExactServiceVersion(version), version);
58 }
59 for (const version of ["latest", "01.2.3", "1.2.3-01", "1.2.3-alpha..1", "1.2.3+."]) {
60 assert.isFalse(isExactServiceVersion(version), version);
61 }
62});
63​
64it("orders exact semantic versions without treating build metadata as precedence", () => {
65 assert.equal(compareExactServiceVersions("1.2.3", "1.2.3"), 0);
66 assert.equal(compareExactServiceVersions("1.2.4", "1.2.3"), 1);
67 assert.equal(compareExactServiceVersions("2.0.0-alpha.1", "2.0.0-alpha.2"), -1);
68 assert.equal(compareExactServiceVersions("2.0.0-alpha.2", "2.0.0-alpha.beta"), -1);
69 assert.equal(compareExactServiceVersions("2.0.0-alpha-beta", "2.0.0-alpha-alpha"), 1);
70 assert.equal(compareExactServiceVersions("2.0.0", "2.0.0-rc.1"), 1);
71 assert.equal(compareExactServiceVersions("2.0.0+one", "2.0.0+two"), 0);
72});
73​
74it("rejects contradictory service state", () => {
75 assert.isUndefined(
76 decodeServiceState({
77 protocol: SERVICE_LAUNCHER_PROTOCOL,
78 activeVersion: "0.0.31",
79 update: {
80 id: "update-1",
81 fromVersion: "0.0.30",
82 targetVersion: "0.0.32",
83 dbPath: "/tmp/state.sqlite",
84 status: "pending",
85 },
86 }),
87 );
88​
89 assert.isUndefined(
90 decodeServiceState({
91 protocol: SERVICE_LAUNCHER_PROTOCOL,
92 activeVersion: "1.0.0",
93 update: {
94 id: "update-3",
95 fromVersion: "1.0.0",
96 targetVersion: "1.1.0",
97 status: "pending",
98 },
99 }),
100 );
101​
102 assert.isUndefined(
103 decodeServiceState({
104 protocol: SERVICE_LAUNCHER_PROTOCOL,
105 activeVersion: "1.0.0",
106 update: {
107 id: "update-2",
108 fromVersion: "1.0.0",
109 targetVersion: "0.9.0",
110 dbPath: "/tmp/state.sqlite",
111 status: "pending",
112 },
113 }),
114 );
115});
116​
117const unitPlan = (root: string, version: string) => ({
118 program: [`${root}/runtime/versions/${version}/t3`, "__service-launcher"],
119 baseDir: root,
120 logPath: `${root}/logs/boot-service.log`,
121 unitPath: `${root}/unit/t3code.service`,
122});
123​
124const writeFakeRuntime = (
125 fs: FileSystem.FileSystem,
126 path: Path.Path,
127 versionDir: string,
128 childSource: string,
129) =>
130 Effect.gen(function* () {
131 const entryPath = path.join(versionDir, "t3");
132 yield* fs.makeDirectory(versionDir, { recursive: true });
133 yield* fs.writeFileString(entryPath, `#!${process.execPath}\n${childSource}`);
134 yield* fs.chmod(entryPath, 0o755);
135 yield* fs.writeFileString(
136 path.join(versionDir, ".install-complete"),
137 `${path.basename(versionDir)}\n`,
138 );
139 return entryPath;
140 });
141​
142const fakeServiceUnit = (
143 fs: FileSystem.FileSystem,
144 path: Path.Path,
145 root: string,
146 version: string,
147 render = renderBootServiceUnit,
148) =>
149 Effect.gen(function* () {
150 const plan = unitPlan(root, version);
151 yield* fs.makeDirectory(path.dirname(plan.unitPath), { recursive: true });
152 const contents = render(plan);
153 yield* fs.writeFileString(plan.unitPath, contents);
154 const unit = {
155 path: plan.unitPath,
156 reloads: 0,
157 loadedContents: contents,
158 failReload: false,
159 reload: async () => {
160 unit.reloads += 1;
161 if (unit.failReload) throw new Error("daemon-reload failed");
162 unit.loadedContents = await NodeFSP.readFile(unit.path, "utf8");
163 },
164 };
165 return unit;
166 });
167​
168it.layer(NodeServices.layer)("service state persistence", (it) => {
169 it.effect(
170 "loads optional service.env literally without changing inherited or managed variables",
171 () =>
172 Effect.gen(function* () {
173 const fs = yield* FileSystem.FileSystem;
174 const path = yield* Path.Path;
175 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-env-" });
176 const inherited = Object.freeze({
177 PATH: "inherited-path",
178 T3CODE_HOME: root,
179 T3_BOOT_SERVICE_UNIT: "managed-unit",
180 T3_SERVICE_LAUNCHER_CONTEXT: "managed-context",
181 T3CODE_PORT: "ambient",
182 });
183 assert.deepEqual(
184 yield* Effect.promise(() => readServiceEnvironment(root, inherited)),
185 inherited,
186 );
187 yield* fs.writeFileString(
188 path.join(root, SERVICE_ENV_FILE),
189 [
190 "# service configuration",
191 "export T3CODE_PORT=1234 # inline comment",
192 'T3CODE_TOKEN="literal $HOME ${USER} $(whoami) # token"',
193 'MULTILINE="first\nsecond"',
194 "EMPTY=",
195 "PATH=/bad",
196 "Path=/bad",
197 "T3CODE_HOME=/bad",
198 "t3code_home=/bad",
199 "T3_BOOT_SERVICE_UNIT=bad",
200 "t3_boot_service_unit=bad",
201 "T3_SERVICE_LAUNCHER_CONTEXT=bad",
202 "t3_service_launcher_context=bad",
203 ].join("\n"),
204 );
205 assert.deepEqual(yield* Effect.promise(() => readServiceEnvironment(root, inherited)), {
206 ...inherited,
207 T3CODE_PORT: "1234",
208 T3CODE_TOKEN: "literal $HOME ${USER} $(whoami) # token",
209 MULTILINE: "first\nsecond",
210 EMPTY: "",
211 });
212 }),
213 );
214​
215 it.effect("a fresh launcher clears a restart deferred by t3 update", () =>
216 Effect.gen(function* () {
217 const fs = yield* FileSystem.FileSystem;
218 const path = yield* Path.Path;
219 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-restart-" });
220 const statePath = path.join(root, "runtime", "service-state.json");
221 const restartPending = path.join(root, "runtime", SERVICE_RESTART_PENDING_FILE);
222 yield* writeFakeRuntime(
223 fs,
224 path,
225 path.join(root, "runtime", "versions", "1.0.0"),
226 "setInterval(() => {}, 1_000);\n",
227 );
228 yield* Effect.promise(() =>
229 writeServiceState(statePath, {
230 protocol: SERVICE_LAUNCHER_PROTOCOL,
231 activeVersion: "1.0.0",
232 }),
233 );
234 const run = () =>
235 Effect.gen(function* () {
236 const launcher = new Launcher(
237 root,
238 yield* Effect.promise(() => readServiceState(statePath)),
239 );
240 const running = launcher.run();
241 yield* Effect.promise(() => launcher.stop("SIGTERM"));
242 yield* Effect.promise(() => running);
243 });
244​
245 yield* fs.writeFileString(restartPending, "1.0.1\n");
246 yield* run();
247 assert.isTrue(yield* fs.exists(restartPending));
248​
249 yield* fs.writeFileString(restartPending, "1.0.0\n");
250 yield* run();
251 assert.isFalse(yield* fs.exists(restartPending));
252 }),
253 );
254​
255 it.effect.each([
256 { unitVersion: "1.0.0", replacement: "an intentional downgrade" },
257 { unitVersion: "1.2.0", replacement: "another T3 home" },
258 ])(
259 "recovers a rolled-back update with unit $unitVersion and preserves $replacement",
260 ({ unitVersion, replacement }) =>
261 Effect.gen(function* () {
262 const fs = yield* FileSystem.FileSystem;
263 const path = yield* Path.Path;
264 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-repoint-" });
265 const statePath = path.join(root, "runtime", "service-state.json");
266 yield* writeFakeRuntime(
267 fs,
268 path,
269 path.join(root, "runtime", "versions", "1.1.0"),
270 "setInterval(() => {}, 1_000);\n",
271 );
272 yield* Effect.promise(() =>
273 writeServiceState(statePath, {
274 protocol: SERVICE_LAUNCHER_PROTOCOL,
275 activeVersion: "1.1.0",
276 update: {
277 id: "update-1",
278 fromVersion: "1.1.0",
279 targetVersion: "1.2.0",
280 status: "rolled-back",
281 },
282 }),
283 );
284 const unit = yield* fakeServiceUnit(fs, path, root, unitVersion);
285 const expected = renderBootServiceUnit(
286 unitPlan(root, unitVersion === "1.0.0" ? "1.1.0" : unitVersion),
287 );
288 const createLauncher = Effect.gen(function* () {
289 return new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)), {
290 serviceUnit: unit,
291 });
292 });
293 const run = (launcher: Launcher) =>
294 Effect.gen(function* () {
295 const running = launcher.run();
296 yield* Effect.promise(() => launcher.stop("SIGTERM"));
297 yield* Effect.promise(() => running);
298 });
299​
300 yield* run(yield* createLauncher);
301 assert.equal(yield* fs.readFileString(unit.path), expected);
302 assert.equal(unit.loadedContents, expected);
303​
304 yield* run(yield* createLauncher);
305 assert.equal(yield* fs.readFileString(unit.path), expected);
306 assert.equal(unit.loadedContents, expected);
307​
308 yield* Effect.promise(() =>
309 writeServiceState(statePath, {
310 protocol: SERVICE_LAUNCHER_PROTOCOL,
311 activeVersion: "1.1.0",
312 update: {
313 id: "update-2",
314 fromVersion: "1.0.0",
315 targetVersion: "1.1.0",
316 status: "committed",
317 },
318 }),
319 );
320 const staleLauncher = yield* createLauncher;
321 // A local install can replace the selection or service owner without stopping this launcher.
322 const selectedRoot =
323 replacement === "another T3 home" ? path.join(root, "other-home") : root;
324 yield* writeFakeRuntime(
325 fs,
326 path,
327 path.join(selectedRoot, "runtime", "versions", "1.0.0"),
328 "setInterval(() => {}, 1_000);\n",
329 );
330 const selectedStatePath = path.join(selectedRoot, "runtime", "service-state.json");
331 yield* Effect.promise(() =>
332 writeServiceState(selectedStatePath, {
333 protocol: SERVICE_LAUNCHER_PROTOCOL,
334 activeVersion: "1.0.0",
335 }),
336 );
337 const selectedUnit = renderBootServiceUnit({
338 ...unitPlan(selectedRoot, "1.0.0"),
339 unitPath: unit.path,
340 });
341 yield* fs.writeFileString(unit.path, selectedUnit);
342 yield* Effect.promise(() => unit.reload());
343 const oldHomeState = yield* fs.readFileString(statePath);
344 const selectedState = yield* fs.readFileString(selectedStatePath);
345​
346 yield* run(staleLauncher);
347 assert.equal(yield* fs.readFileString(statePath), oldHomeState);
348 assert.equal(yield* fs.readFileString(selectedStatePath), selectedState);
349 assert.equal(yield* fs.readFileString(unit.path), selectedUnit, replacement);
350 assert.equal(unit.loadedContents, selectedUnit, replacement);
351 }),
352 );
353​
354 it.effect("stays idle instead of exiting when another server owns the T3 home", () =>
355 Effect.gen(function* () {
356 const fs = yield* FileSystem.FileSystem;
357 const path = yield* Path.Path;
358 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-refused-" });
359 const statePath = path.join(root, "runtime", "service-state.json");
360 yield* writeFakeRuntime(
361 fs,
362 path,
363 path.join(root, "runtime", "versions", "1.0.0"),
364 `process.exit(${SERVER_EXIT_CODE_STATE_DIR_OWNED});\n`,
365 );
366 yield* Effect.promise(() =>
367 writeServiceState(statePath, {
368 protocol: SERVICE_LAUNCHER_PROTOCOL,
369 activeVersion: "1.0.0",
370 }),
371 );
372 const refused = Promise.withResolvers<void>();
373 yield* Effect.acquireRelease(
374 Effect.sync(() =>
375 vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
376 if (String(chunk).includes("owns this T3 home")) refused.resolve();
377 return true;
378 }),
379 ),
380 (spy) => Effect.sync(() => spy.mockRestore()),
381 );
382 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
383 let completed = false;
384 const running = launcher.run().finally(() => {
385 completed = true;
386 });
387 yield* Effect.promise(() => refused.promise);
388 assert.isFalse(completed);
389 yield* Effect.promise(() => launcher.stop("SIGTERM"));
390 yield* Effect.promise(() => running);
391 }),
392 );
393​
394 const commitUpdate = (
395 render = renderBootServiceUnit,
396 missingUnit = false,
397 legacyInstall = false,
398 ) =>
399 Effect.gen(function* () {
400 const fs = yield* FileSystem.FileSystem;
401 const path = yield* Path.Path;
402 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service 100% & <test>-" });
403 const statePath = path.join(root, "runtime", "service-state.json");
404 const databasePath = path.join(root, "userdata", "state.sqlite");
405 const activatedPath = path.join(root, "activated");
406 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
407 yield* fs.writeFileString(databasePath, "before trial");
408 const unit = yield* fakeServiceUnit(fs, path, root, "1.0.0", render);
409 if (missingUnit) yield* fs.remove(unit.path);
410 const childSource = `
411import assert from "node:assert/strict";
412import { existsSync, readFileSync, writeFileSync } from "node:fs";
413const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
414assert.equal(context.protocol, ${SERVICE_LAUNCHER_PROTOCOL});
415if (context.update?.status === "pending") {
416 const state = JSON.parse(readFileSync(${JSON.stringify(statePath)}, "utf8"));
417 assert.equal(state.activeVersion, "1.0.0");
418 assert.equal(state.update.status, "pending");
419 ${
420 missingUnit
421 ? `assert.equal(existsSync(${JSON.stringify(unit.path)}), false);`
422 : `assert.equal(readFileSync(${JSON.stringify(unit.path)}, "utf8"), ${JSON.stringify(unit.loadedContents)});`
423 }
424 process.on("message", (message) => {
425 if (message.type === "committed") {
426 const state = JSON.parse(readFileSync(${JSON.stringify(statePath)}, "utf8"));
427 assert.equal(state.protocol, ${SERVICE_LAUNCHER_PROTOCOL});
428 assert.equal(state.activeVersion, "1.1.0");
429 assert.equal(state.update.status, "committed");
430 writeFileSync(${JSON.stringify(activatedPath)}, message.updateId);
431 process.exit(0);
432 }
433 });
434 process.send({ type: "prepared", updateId: context.update.id });
435} else if (context.update === undefined) {
436 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${JSON.stringify(databasePath)} });
437 setInterval(() => {}, 1_000);
438} else {
439 process.exit(0);
441`;
442 for (const version of ["1.0.0", "1.1.0"]) {
443 yield* writeFakeRuntime(
444 fs,
445 path,
446 path.join(root, "runtime", "versions", version),
447 childSource,
448 );
449 }
450 // The old CLI installs the new runtime but writes state with its own protocol.
451 yield* fs.writeFileString(
452 statePath,
453 `${JSON.stringify(
454 {
455 protocol: legacyInstall ? 3 : SERVICE_LAUNCHER_PROTOCOL,
456 activeVersion: "1.0.0",
457 },
458 null,
459 2,
460 )}\n`,
461 );
462 const launcher = new Launcher(
463 root,
464 yield* Effect.promise(() => readServiceState(statePath)),
465 { serviceUnit: unit },
466 );
467 const failure = yield* Effect.promise(() =>
468 launcher.run().then(
469 () => "launcher unexpectedly completed",
470 (cause: unknown) => String(cause),
471 ),
472 );
473 assert.include(failure, "Active child exited unexpectedly (0)");
474 const state = yield* Effect.promise(() => readServiceState(statePath));
475 assert.equal(state.activeVersion, "1.1.0");
476 assert.equal(state.update?.status, "committed");
477 assert.equal(yield* fs.readFileString(activatedPath), state.update?.id);
478 const recover = () =>
479 Effect.gen(function* () {
480 const fresh = new Launcher(
481 root,
482 yield* Effect.promise(() => readServiceState(statePath)),
483 { serviceUnit: unit },
484 );
485 const running = fresh.run();
486 yield* Effect.promise(() => fresh.stop("SIGTERM"));
487 yield* Effect.promise(() => running);
488 });
489 return { fs, root, unit, recover };
490 });
491​
492 it.effect.each([
493 {
494 name: "systemd after a protocol-3 local upgrade",
495 render: renderBootServiceUnit,
496 legacyInstall: true,
497 },
498 {
499 name: "launchd",
500 legacyInstall: false,
501 render: (plan: Parameters<typeof renderBootServicePlist>[0]) =>
502 renderBootServicePlist(plan, {
503 homeDir: "/Users/test & <user>",
504 environmentPath: "/usr/bin:/custom/runtime/versions/1.0.0",
505 }),
506 },
507 ])(
508 "commits and repoints $name only after the trial reports prepared",
509 ({ render, legacyInstall }) =>
510 Effect.gen(function* () {
511 const { fs, root, unit } = yield* commitUpdate(render, false, legacyInstall);
512 const expected = render(unitPlan(root, "1.1.0"));
513 assert.equal(yield* fs.readFileString(unit.path), expected);
514 assert.equal(unit.loadedContents, expected);
515 assert.equal(unit.reloads, 1);
516 }),
517 );
518​
519 it.effect(
520 "keeps a durable commit through unit failure and retries a failed reload on restart",
521 () =>
522 Effect.gen(function* () {
523 const { fs, root, unit, recover } = yield* commitUpdate(renderBootServiceUnit, true);
524 assert.equal(unit.reloads, 0);
525 const original = renderBootServiceUnit(unitPlan(root, "1.0.0"));
526 const expected = renderBootServiceUnit(unitPlan(root, "1.1.0"));
527 assert.equal(unit.loadedContents, original);
528 yield* fs.writeFileString(unit.path, original);
529 unit.failReload = true;
530 yield* recover();
531 assert.equal(yield* fs.readFileString(unit.path), expected);
532 assert.equal(unit.reloads, 1);
533 assert.equal(unit.loadedContents, original);
534​
535 unit.failReload = false;
536 yield* recover();
537 assert.equal(yield* fs.readFileString(unit.path), expected);
538 assert.equal(unit.loadedContents, expected);
539 assert.equal(unit.reloads, 2);
540 }),
541 );
542​
543 it.effect("rolls back invalid trials with the startup environment", () =>
544 Effect.gen(function* () {
545 const fs = yield* FileSystem.FileSystem;
546 const path = yield* Path.Path;
547 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
548 const statePath = path.join(root, "runtime", "service-state.json");
549 const databasePath = path.join(root, "userdata", "state.sqlite");
550 const observationsPath = path.join(root, "environment-observations.jsonl");
551 const envPath = path.join(root, SERVICE_ENV_FILE);
552 yield* fs.writeFileString(envPath, "T3CODE_TEST_SERVICE_TOKEN=initial\n");
553 vi.stubEnv("T3CODE_HOME", root);
554 vi.stubEnv("T3CODE_TEST_SERVICE_TOKEN", "inherited");
555 yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs()));
556 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
557 yield* fs.writeFileString(databasePath, "before trial");
558 const encodedDatabasePath = JSON.stringify(databasePath);
559 const childSource = `
560import { appendFileSync, writeFileSync } from "node:fs";
561const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
562appendFileSync(${JSON.stringify(observationsPath)}, JSON.stringify({
563 token: process.env.T3CODE_TEST_SERVICE_TOKEN,
564 update: context.update?.status ?? "active",
565}) + "\\n");
566if (context.update?.status === "pending") {
567 process.send({ type: "prepared", updateId: "wrong-update" });
568} else if (context.update === undefined) {
569 writeFileSync(${JSON.stringify(envPath)}, "T3CODE_TEST_SERVICE_TOKEN=changed\\n");
570 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
571 setInterval(() => {}, 1_000);
572} else {
573 process.exit(0);
575`;
576 for (const version of ["1.0.0", "1.1.0"]) {
577 yield* writeFakeRuntime(
578 fs,
579 path,
580 path.join(root, "runtime", "versions", version),
581 childSource,
582 );
583 }
584 yield* Effect.promise(() =>
585 writeServiceState(statePath, {
586 protocol: SERVICE_LAUNCHER_PROTOCOL,
587 activeVersion: "1.0.0",
588 }),
589 );
590 const unit = yield* fakeServiceUnit(fs, path, root, "0.9.0");
591​
592 const launcher = new Launcher(
593 root,
594 yield* Effect.promise(() => readServiceState(statePath)),
595 {
596 serviceUnit: unit,
597 environment: yield* Effect.promise(() => readServiceEnvironment(root)),
598 },
599 );
600 yield* Effect.promise(() =>
601 launcher.run().then(
602 () => Promise.reject(new Error("launcher unexpectedly completed")),
603 () => Promise.resolve(),
604 ),
605 );
606​
607 const state = yield* Effect.promise(() => readServiceState(statePath));
608 assert.equal(state.activeVersion, "1.0.0");
609 assert.equal(state.update?.status, "rolled-back");
610 assert.equal(
611 yield* fs.readFileString(unit.path),
612 renderBootServiceUnit(unitPlan(root, "1.0.0")),
613 );
614 assert.equal(unit.reloads, 1);
615 assert.equal(
616 state.update?.status === "rolled-back" ? state.update.reason : undefined,
617 "invalid-prepared",
618 );
619 const observations = (yield* fs.readFileString(observationsPath))
620 .trim()
621 .split("\n")
622 .map((line) => JSON.parse(line));
623 assert.deepEqual(observations, [
624 { token: "initial", update: "active" },
625 { token: "initial", update: "pending" },
626 { token: "initial", update: "rolled-back" },
627 ]);
628 assert.equal((yield* HostProcess.Environment).T3CODE_TEST_SERVICE_TOKEN, "inherited");
629 assert.equal(yield* fs.readFileString(envPath), "T3CODE_TEST_SERVICE_TOKEN=changed\n");
630 }),
631 );
632​
633 it.effect.each(["file", "symlink", "dangling symlink"] as const)(
634 "restores the database when a migrating trial exits, with the database a %s",
635 (kind) =>
636 Effect.gen(function* () {
637 const fs = yield* FileSystem.FileSystem;
638 const path = yield* Path.Path;
639 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-db-" });
640 const statePath = path.join(root, "runtime", "service-state.json");
641 const databasePath = path.join(root, "userdata", "state.sqlite");
642 const databaseFile =
643 kind === "file" ? databasePath : path.join(root, "data", "original.sqlite");
644 const linkTarget = kind === "dangling symlink" ? "../original.sqlite" : databaseFile;
645 const original = "database before migration";
646 yield* fs.makeDirectory(path.dirname(databaseFile), { recursive: true });
647 if (kind === "dangling symlink") {
648 yield* fs.makeDirectory(path.join(root, "data", "sub"));
649 yield* fs.symlink(path.join(root, "data", "sub"), path.dirname(databasePath));
650 } else {
651 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
652 }
653 yield* fs.writeFileString(databaseFile, original);
654 if (kind !== "file") yield* fs.symlink(linkTarget, databasePath);
655 const encodedDatabasePath = JSON.stringify(databasePath);
656 const childSource = `
657import { realpathSync, unlinkSync, writeFileSync } from "node:fs";
658const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
659if (context.update?.status === "pending") {
660 writeFileSync(context.update.dbPath, "database after migration");
661 writeFileSync(context.update.dbPath + "-wal", "trial wal");
662 writeFileSync(context.update.dbPath + "-shm", "trial shm");
663 ${kind === "dangling symlink" ? "unlinkSync(realpathSync(context.update.dbPath));" : ""}
664 process.exit(1);
665} else if (context.update === undefined) {
666 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
667 setInterval(() => {}, 1_000);
668} else {
669 process.exit(0);
671`;
672 for (const version of ["1.0.0", "1.1.0"]) {
673 yield* writeFakeRuntime(
674 fs,
675 path,
676 path.join(root, "runtime", "versions", version),
677 childSource,
678 );
679 }
680 yield* Effect.promise(() =>
681 writeServiceState(statePath, {
682 protocol: SERVICE_LAUNCHER_PROTOCOL,
683 activeVersion: "1.0.0",
684 }),
685 );
686​
687 const launcher = new Launcher(
688 root,
689 yield* Effect.promise(() => readServiceState(statePath)),
690 );
691 yield* Effect.promise(() =>
692 launcher.run().then(
693 () => Promise.reject(new Error("launcher unexpectedly completed")),
694 () => Promise.resolve(),
695 ),
696 );
697​
698 const state = yield* Effect.promise(() => readServiceState(statePath));
699 assert.equal(state.activeVersion, "1.0.0");
700 assert.equal(state.update?.status, "rolled-back");
701 assert.equal(yield* fs.readFileString(databaseFile), original);
702 if (kind !== "file") assert.equal(yield* fs.readLink(databasePath), linkTarget);
703 assert.isFalse(yield* fs.exists(path.join(root, "original.sqlite")));
704 assert.isFalse(yield* fs.exists(`${databasePath}-wal`));
705 assert.isFalse(yield* fs.exists(`${databasePath}-shm`));
706 const updateId = state.update?.id;
707 assert.isDefined(updateId);
708 assert.isFalse(yield* fs.exists(path.join(root, "runtime", "db-backup", updateId)));
709 }),
710 );
711​
712 it.effect.each(["wal", "delete"] as const)(
713 "backs up a %s-mode database (online when WAL) and restores its final state",
714 (journalMode) =>
715 Effect.gen(function* () {
716 const fs = yield* FileSystem.FileSystem;
717 const path = yield* Path.Path;
718 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-online-" });
719 const statePath = path.join(root, "runtime", "service-state.json");
720 const databasePath = path.join(root, "userdata", "state.sqlite");
721 const observationsPath = path.join(root, "observations.json");
722 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
723 // SQLite keeps -wal beside the symlink's target, so the backup must restore it there.
724 yield* fs.symlink("actual.sqlite", databasePath);
725 const seed = new NodeSqlite.DatabaseSync(databasePath);
726 seed.exec(`
727 PRAGMA journal_mode = ${journalMode};
728 CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT NOT NULL);
729 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 500)
730 INSERT INTO events (payload) SELECT 'before the update ' || i FROM n;
731 `);
732 seed.close();
733​
734 const encoded = JSON.stringify({ root, databasePath, observationsPath, journalMode });
735 const childSource = `
736import { readdirSync, writeFileSync } from "node:fs";
737import { DatabaseSync } from "node:sqlite";
738const paths = ${encoded};
739const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
740if (context.update?.status === "pending") {
741 writeFileSync(paths.observationsPath + ".trial", JSON.stringify(
742 readdirSync(paths.root + "/runtime/db-backup/" + context.update.id).sort(),
743 ));
744 const trial = new DatabaseSync(context.update.dbPath);
745 trial.exec("PRAGMA journal_mode = " + paths.journalMode + "; INSERT INTO events (payload) VALUES ('trial');");
746 trial.close();
747 process.exit(1);
748} else if (context.update === undefined) {
749 const db = new DatabaseSync(paths.databasePath);
750 db.exec("PRAGMA busy_timeout = 5000;");
751 db.exec("PRAGMA journal_mode = " + paths.journalMode + ";");
752 const insert = db.prepare("INSERT INTO events (payload) VALUES (?)");
753 const writer = setInterval(() => insert.run("written while serving"), 1);
754 process.once("SIGTERM", () => {
755 clearInterval(writer);
756 insert.run("last write before stopping");
757 const backupRoot = paths.root + "/runtime/db-backup";
758 writeFileSync(paths.observationsPath, JSON.stringify({
759 backupsAtStop: readdirSync(backupRoot).map((entry) => readdirSync(backupRoot + "/" + entry)),
760 rows: db.prepare("SELECT count(*) AS n FROM events").get().n,
761 }));
762 db.close();
763 process.exit(0);
764 });
765 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
766} else {
767 process.exit(0);
769`;
770 for (const version of ["1.0.0", "1.1.0"]) {
771 yield* writeFakeRuntime(
772 fs,
773 path,
774 path.join(root, "runtime", "versions", version),
775 childSource,
776 );
777 }
778 yield* Effect.promise(() =>
779 writeServiceState(statePath, {
780 protocol: SERVICE_LAUNCHER_PROTOCOL,
781 activeVersion: "1.0.0",
782 }),
783 );
784​
785 const launcher = new Launcher(
786 root,
787 yield* Effect.promise(() => readServiceState(statePath)),
788 {
789 backupSpaceProbe: { canClone: async () => false },
790 },
791 );
792 yield* Effect.promise(() =>
793 launcher.run().then(
794 () => Promise.reject(new Error("launcher unexpectedly completed")),
795 () => Promise.resolve(),
796 ),
797 );
798​
799 const state = yield* Effect.promise(() => readServiceState(statePath));
800 assert.equal(state.update?.status, "rolled-back");
801 const observed = JSON.parse(yield* fs.readFileString(observationsPath));
802 // A WAL database's main file is copied before the server is asked to stop; others fall back offline.
803 assert.deepEqual(observed.backupsAtStop, journalMode === "wal" ? [["database"]] : []);
804 assert.isAbove(observed.rows, 501);
805 // Only the online copy holds no -shm: the offline fallback copies the one the server left.
806 assert.deepEqual(
807 JSON.parse(yield* fs.readFileString(`${observationsPath}.trial`)),
808 journalMode === "wal" ? ["database", "database-wal"] : ["database"],
809 );
810 const restored = new NodeSqlite.DatabaseSync(databasePath);
811 try {
812 assert.equal(restored.prepare("PRAGMA integrity_check").get()?.integrity_check, "ok");
813 assert.equal(
814 restored.prepare("SELECT count(*) AS n FROM events").get()?.n,
815 observed.rows,
816 );
817 assert.equal(
818 restored
819 .prepare(
820 "SELECT count(*) AS n FROM events WHERE payload = 'last write before stopping'",
821 )
822 .get()?.n,
823 1,
824 );
825 } finally {
826 restored.close();
827 }
828 }),
829 );
830​
831 const requestRejectedUpdate = (backupSpaceProbe: Partial<BackupSpaceProbe>) =>
832 Effect.gen(function* () {
833 const fs = yield* FileSystem.FileSystem;
834 const path = yield* Path.Path;
835 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-space-" });
836 const statePath = path.join(root, "runtime", "service-state.json");
837 const databasePath = path.join(root, "userdata", "state.sqlite");
838 const replyPath = path.join(root, "rejection.txt");
839 const trialMarker = path.join(root, "trial-started");
840 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
841 yield* fs.writeFileString(databasePath, "database");
842 const encoded = JSON.stringify({ databasePath, replyPath, trialMarker });
843 const childSource = `
844import { writeFileSync } from "node:fs";
845const paths = ${encoded};
846const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
847if (context.update?.status === "pending") {
848 writeFileSync(paths.trialMarker, "started");
849 process.exit(1);
850} else if (context.update === undefined) {
851 process.on("message", (message) => {
852 if (message.type === "update-rejected") {
853 writeFileSync(paths.replyPath, message.reason);
854 process.exit(0);
855 }
856 });
857 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
858 setInterval(() => {}, 1_000);
859} else {
860 process.exit(0);
862`;
863 for (const version of ["1.0.0", "1.1.0"]) {
864 yield* writeFakeRuntime(
865 fs,
866 path,
867 path.join(root, "runtime", "versions", version),
868 childSource,
869 );
870 }
871 yield* Effect.promise(() =>
872 writeServiceState(statePath, {
873 protocol: SERVICE_LAUNCHER_PROTOCOL,
874 activeVersion: "1.0.0",
875 }),
876 );
877​
878 const launcher = new Launcher(
879 root,
880 yield* Effect.promise(() => readServiceState(statePath)),
881 { backupSpaceProbe },
882 );
883 yield* Effect.promise(() =>
884 launcher.run().then(
885 () => Promise.reject(new Error("launcher unexpectedly completed")),
886 () => Promise.resolve(),
887 ),
888 );
889​
890 return {
891 reason: yield* fs.readFileString(replyPath),
892 trialStarted: yield* fs.exists(trialMarker),
893 state: yield* Effect.promise(() => readServiceState(statePath)),
894 };
895 });
896​
897 it.effect("refuses a backup that cannot fit and leaves the server running", () =>
898 Effect.gen(function* () {
899 const { reason, trialStarted, state } = yield* requestRejectedUpdate({
900 readFreeBytes: () => Promise.resolve(0),
901 canClone: () => Promise.resolve(true),
902 });
903​
904 assert.include(reason, "Not enough free disk space");
905 assert.include(reason, "The server was not stopped");
906 assert.isFalse(trialStarted);
907 assert.equal(state.activeVersion, "1.0.0");
908 assert.isUndefined(state.update);
909 }),
910 );
911​
912 it.effect("refuses the update when free space cannot be checked", () =>
913 Effect.gen(function* () {
914 const { reason, trialStarted, state } = yield* requestRejectedUpdate({
915 readFreeBytes: () => Promise.reject(new Error("statfs unavailable")),
916 });
917​
918 assert.include(
919 reason,
920 "Could not check that the database backup fits before updating: statfs unavailable",
921 );
922 assert.isFalse(trialStarted);
923 assert.equal(state.activeVersion, "1.0.0");
924 assert.isUndefined(state.update);
925 }),
926 );
927​
928 it.effect("records no update when the server exits during the backup check", () =>
929 Effect.gen(function* () {
930 const fs = yield* FileSystem.FileSystem;
931 const path = yield* Path.Path;
932 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-exit-" });
933 const statePath = path.join(root, "runtime", "service-state.json");
934 const databasePath = path.join(root, "userdata", "state.sqlite");
935 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
936 yield* fs.writeFileString(databasePath, "database");
937 const encoded = JSON.stringify({ databasePath });
938 const childSource = `
939const paths = ${encoded};
940process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath }, () =>
941 process.exit(3),
942);
943setInterval(() => {}, 1_000);
944`;
945 for (const version of ["1.0.0", "1.1.0"]) {
946 yield* writeFakeRuntime(
947 fs,
948 path,
949 path.join(root, "runtime", "versions", version),
950 childSource,
951 );
952 }
953 yield* Effect.promise(() =>
954 writeServiceState(statePath, {
955 protocol: SERVICE_LAUNCHER_PROTOCOL,
956 activeVersion: "1.0.0",
957 }),
958 );
959 const launcher = new Launcher(
960 root,
961 yield* Effect.promise(() => readServiceState(statePath)),
962 {
963 backupSpaceProbe: {
964 readFreeBytes: () => {
965 const child = spawnedChildren.at(-1)!;
966 return new Promise((resolve) => {
967 if (!child.connected) resolve(Number.MAX_SAFE_INTEGER);
968 else child.once("disconnect", () => resolve(Number.MAX_SAFE_INTEGER));
969 });
970 },
971 },
972 },
973 );
974 const failure = yield* Effect.promise(() =>
975 launcher.run().then(
976 () => new Error("launcher unexpectedly completed"),
977 (cause: unknown) => cause as Error,
978 ),
979 );
980​
981 assert.include(failure.message, "Active child exited unexpectedly (3)");
982 const state = yield* Effect.promise(() => readServiceState(statePath));
983 assert.equal(state.activeVersion, "1.0.0");
984 assert.isUndefined(state.update);
985 }),
986 );
987​
988 it.effect("reclaims partial backups left by killed updates before checking space", () =>
989 Effect.gen(function* () {
990 const fs = yield* FileSystem.FileSystem;
991 const path = yield* Path.Path;
992 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-orphan-" });
993 const databasePath = path.join(root, "state.sqlite");
994 yield* writeSparseFile(databasePath, 10 * 1024 ** 3);
995 const backupRoot = path.join(root, "runtime", "db-backup");
996 const orphan = path.join(backupRoot, "earlier-update.staging");
997 const completed = path.join(backupRoot, "completed-update");
998 yield* fs.makeDirectory(orphan, { recursive: true });
999 yield* fs.writeFileString(path.join(orphan, "database"), "partial copy");
1000 yield* fs.makeDirectory(completed);
1001 yield* fs.writeFileString(path.join(completed, "database"), "complete copy");
1002​
1003 // The orphan is what keeps this disk too full for a full copy.
1004 const blocker = yield* Effect.promise(() =>
1005 databaseBackupBlocker(root, databasePath, {
1006 readFreeBytes: () => Promise.resolve((NodeFS.existsSync(orphan) ? 8 : 11) * 1024 ** 3),
1007 canClone: () => Promise.resolve(false),
1008 }),
1009 );
1010​
1011 assert.isUndefined(blocker);
1012 assert.isFalse(yield* fs.exists(orphan));
1013 assert.isTrue(yield* fs.exists(path.join(completed, "database")));
1014 }),
1015 );
1016​
1017 it.effect("checks database backup space against clone or full-copy needs", () =>
1018 Effect.gen(function* () {
1019 const fs = yield* FileSystem.FileSystem;
1020 const path = yield* Path.Path;
1021 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-blocker-" });
1022 const databasePath = path.join(root, "state.sqlite");
1023 yield* writeSparseFile(databasePath, 10 * 1024 ** 3);
1024 const check = (free: number, cloneable: boolean) =>
1025 Effect.promise(() =>
1026 databaseBackupBlocker(root, databasePath, {
1027 readFreeBytes: () => Promise.resolve(free),
1028 canClone: () => Promise.resolve(cloneable),
1029 }),
1030 );
1031​
1032 assert.isUndefined(yield* check(11 * 1024 ** 3, false));
1033 assert.isUndefined(yield* check(1.5 * 1024 ** 3, true));
1034 assert.include((yield* check(0.5 * 1024 ** 3, true)) ?? "", "1.0 GB needed, 0.5 GB free");
1035 const blocker = yield* check(8 * 1024 ** 3, false);
1036 assert.include(blocker ?? "", "Not enough free disk space");
1037 assert.include(blocker ?? "", "10.8 GB needed, 8.0 GB free");
1038 assert.include(blocker ?? "", "The server was not stopped");
1039 }),
1040 );
1041});