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