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