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

bootService.test.ts

561 lines20.9 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as ConfigProvider from "effect/ConfigProvider";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
10​
11import {
12 HostProcessArguments,
13 HostProcessExecutablePath,
14 HostProcessPlatform,
15} from "@t3tools/shared/hostProcess";
16​
17import { reconcileService } from "../cli/service.ts";
18import * as ProcessRunner from "../processRunner.ts";
19import * as BootService from "./bootService.ts";
20​
21const isUnsupportedError = Schema.is(BootService.BootServiceUnsupportedError);
22const isCommandError = Schema.is(BootService.BootServiceCommandError);
23​
24interface RecordedCommand {
25 readonly command: string;
26 readonly args: ReadonlyArray<string>;
28​
29const makeRecordingRunnerLayer = (
30 commands: Array<RecordedCommand>,
31 options?: {
32 readonly failCommand?: string;
33 readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
34 },
35) =>
36 Layer.succeed(
37 ProcessRunner.ProcessRunner,
38 ProcessRunner.ProcessRunner.of({
39 run: (input) =>
40 Effect.sync(() => {
41 assert.isUndefined(input.env);
42 commands.push({ command: input.command, args: input.args });
43 const failed =
44 input.command === options?.failCommand ||
45 options?.failWhen?.(input.command, input.args) === true;
46 return {
47 stdout: "",
48 stderr: failed ? `${input.command} exploded` : "",
49 code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
50 timedOut: false,
51 stdoutTruncated: false,
52 stderrTruncated: false,
53 };
54 }),
55 }),
56 );
57​
58const makeHost = (entry: string): BootService.BootServiceHost => ({
59 execPath: "/usr/local/bin/node",
60 cliEntryPath: entry,
61});
62​
63const provideHostRefs = (home: string, platform: NodeJS.Platform = "linux") =>
64 Effect.provide(
65 Layer.mergeAll(
66 Layer.succeed(HostProcessPlatform, platform),
67 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
68 ),
69 );
70​
71const makeTestContext = Effect.fn("test.makeTestContext")(function* () {
72 const fs = yield* FileSystem.FileSystem;
73 const path = yield* Path.Path;
74 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
75 // A real file for the stable-entry cases so status can confirm the entry
76 // point exists.
77 const stableEntry = path.join(root, "bin.mjs");
78 yield* fs.writeFileString(stableEntry, "#!/usr/bin/env node\n");
79 return {
80 fs,
81 path,
82 dirs: {
83 home: root,
84 baseDir: path.join(root, ".t3"),
85 logsDir: path.join(root, ".t3", "userdata", "logs"),
86 stableEntry,
87 },
88 };
89});
90​
91it("renders a systemd unit with absolute paths and append-mode logging", () => {
92 const unit = BootService.renderBootServiceUnit({
93 nodePath: "/usr/local/bin/node",
94 t3EntryPath: "/home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs",
95 baseDir: "/home/theo/.t3",
96 logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
97 unitPath: "/home/theo/.config/systemd/user/t3code.service",
98 });
99​
100 assert.equal(
101 unit,
102 [
103 "[Unit]",
104 "Description=T3 Code server",
105 "StartLimitIntervalSec=300",
106 "StartLimitBurst=5",
107 "",
108 "[Service]",
109 "Type=simple",
110 "WorkingDirectory=%h",
111 "Environment=PATH=%h/.local/bin:%h/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin",
112 "Environment=T3CODE_HOME=/home/theo/.t3",
113 "Environment=T3_BOOT_SERVICE_UNIT=t3code.service",
114 "ExecStart=/usr/local/bin/node /home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs serve",
115 "Restart=always",
116 "RestartSec=5",
117 "StandardOutput=append:/home/theo/.t3/userdata/logs/boot-service.log",
118 "StandardError=append:/home/theo/.t3/userdata/logs/boot-service.log",
119 "",
120 "[Install]",
121 "WantedBy=default.target",
122 "",
123 ].join("\n"),
124 );
125});
126​
127it("quotes systemd values containing spaces and escapes percent specifiers", () => {
128 assert.equal(BootService.quoteSystemdValue("/plain/path"), "/plain/path");
129 assert.equal(BootService.quoteSystemdValue("/home/me/T3 Data"), '"/home/me/T3 Data"');
130 assert.equal(BootService.quoteSystemdValue("/opt/100%cpu"), "/opt/100%%cpu");
131​
132 const unit = BootService.renderBootServiceUnit({
133 nodePath: "/home/me/my tools/node",
134 t3EntryPath: "/home/me/T3 Data/bin.mjs",
135 baseDir: "/home/me/T3 Data",
136 logPath: "/home/me/100%logs/boot.log",
137 unitPath: "/home/me/.config/systemd/user/t3code.service",
138 });
139 assert.include(unit, 'ExecStart="/home/me/my tools/node" "/home/me/T3 Data/bin.mjs" serve');
140 assert.include(unit, 'Environment=T3CODE_HOME="/home/me/T3 Data"');
141 // ~/.local/bin is prepended so user-scoped provider CLIs resolve.
142 assert.include(unit, "Environment=PATH=%h/.local/bin:%h/bin:");
143 // append: paths take the rest of the line literally (spaces are fine,
144 // quoting is not), but % still goes through specifier expansion.
145 assert.include(unit, "StandardOutput=append:/home/me/100%%logs/boot.log");
146 assert.include(unit, "StandardError=append:/home/me/100%%logs/boot.log");
147});
148​
149it("flags package-manager cache entry points as ephemeral", () => {
150 assert.isTrue(
151 BootService.isEphemeralCacheEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
152 );
153 assert.isTrue(
154 BootService.isEphemeralCacheEntry("C:\\Users\\theo\\AppData\\npm-cache\\_npx\\abc\\bin.mjs"),
155 );
156 assert.isTrue(
157 BootService.isEphemeralCacheEntry(
158 "/home/theo/.cache/pnpm/dlx/abc/node_modules/t3/dist/bin.mjs",
159 ),
160 );
161 assert.isTrue(
162 BootService.isEphemeralCacheEntry("/home/theo/.bun/install/cache/t3@0.0.27/dist/bin.mjs"),
163 );
164 assert.isFalse(BootService.isEphemeralCacheEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
165 assert.isFalse(
166 BootService.isEphemeralCacheEntry(
167 "/home/theo/dev/pnpm/dlx-tools/t3/node_modules/t3/dist/bin.mjs",
168 ),
169 );
170 assert.isFalse(
171 BootService.isEphemeralCacheEntry(
172 "/home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs",
173 ),
174 );
175});
176​
177it.layer(NodeServices.layer)("BootService", (it) => {
178 it.effect("reconciles the standalone service once and is then idempotent", () =>
179 Effect.gen(function* () {
180 const { dirs } = yield* makeTestContext();
181 const commands: Array<RecordedCommand> = [];
182 const service = yield* BootService.make({
183 baseDir: dirs.baseDir,
184 logsDir: dirs.logsDir,
185 cliVersion: "0.0.27",
186 host: makeHost(dirs.stableEntry),
187 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
188​
189 const first = yield* reconcileService().pipe(
190 Effect.provideService(BootService.BootService, service),
191 );
192 assert.isTrue(first.changed);
193 if (!first.changed) return;
194 assert.isFalse(first.previouslyInstalled);
195​
196 const commandCount = commands.length;
197 const second = yield* reconcileService().pipe(
198 Effect.provideService(BootService.BootService, service),
199 );
200 assert.isFalse(second.changed);
201 assert.lengthOf(commands, commandCount);
202 }),
203 );
204​
205 it.effect("installs the unit, enables the service, and enables linger", () =>
206 Effect.gen(function* () {
207 const { dirs, fs, path } = yield* makeTestContext();
208 const commands: Array<RecordedCommand> = [];
209 const service = yield* BootService.make({
210 baseDir: dirs.baseDir,
211 logsDir: dirs.logsDir,
212 cliVersion: "0.0.27",
213 host: makeHost(dirs.stableEntry),
214 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
215​
216 const plan = yield* service.install;
217​
218 // A stable entry point is reused directly — no npm install.
219 assert.equal(plan.t3EntryPath, dirs.stableEntry);
220 assert.deepEqual(
221 commands.map((entry) => [entry.command, ...entry.args].join(" ")),
222 [
223 "systemctl --user daemon-reload",
224 "systemctl --user enable t3code.service",
225 // restart (not enable --now) so repairing a stale unit replaces a
226 // running process instead of leaving the old one until reboot.
227 "systemctl --user restart t3code.service",
228 "loginctl enable-linger",
229 ],
230 );
231​
232 const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service");
233 const unit = yield* fs.readFileString(unitPath);
234 assert.include(unit, `ExecStart=/usr/local/bin/node ${dirs.stableEntry} serve`);
235 assert.include(unit, `Environment=T3CODE_HOME=${dirs.baseDir}`);
236​
237 const status = yield* service.status;
238 assert.isTrue(status.supported);
239 assert.isTrue(status.installed);
240 assert.isTrue(status.current);
241​
242 const removed = yield* service.uninstall;
243 assert.isTrue(removed);
244 assert.isFalse(yield* fs.exists(unitPath));
245 const statusAfter = yield* service.status;
246 assert.isFalse(statusAfter.installed);
247 const removedAgain = yield* service.uninstall;
248 assert.isFalse(removedAgain);
249 }),
250 );
251​
252 it.effect("pins a runtime via npm install when running from the npx cache", () =>
253 Effect.gen(function* () {
254 const { dirs, fs, path } = yield* makeTestContext();
255 const commands: Array<RecordedCommand> = [];
256 const service = yield* BootService.make({
257 baseDir: dirs.baseDir,
258 logsDir: dirs.logsDir,
259 cliVersion: "0.0.27",
260 host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
261 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
262​
263 const plan = yield* service.install;
264​
265 const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
266 assert.equal(
267 plan.t3EntryPath,
268 path.join(runtimeDir, "node_modules", "t3", "dist", "bin.mjs"),
269 );
270 assert.deepEqual(commands[0], {
271 command: "npm",
272 args: ["install", "--prefix", runtimeDir, "--no-fund", "--no-audit", "t3@0.0.27"],
273 });
274 // Success is recorded via a sentinel so interrupted installs re-run.
275 assert.isTrue(yield* fs.exists(path.join(runtimeDir, ".install-complete")));
276 }),
277 );
278​
279 it.effect("reinstalls a pinned runtime when its entry point is missing", () =>
280 Effect.gen(function* () {
281 const { dirs, fs, path } = yield* makeTestContext();
282 const commands: Array<RecordedCommand> = [];
283 const service = yield* BootService.make({
284 baseDir: dirs.baseDir,
285 logsDir: dirs.logsDir,
286 cliVersion: "0.0.27",
287 host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
288 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
289​
290 const plan = yield* service.install;
291 yield* fs.makeDirectory(path.dirname(plan.t3EntryPath), { recursive: true });
292 yield* fs.writeFileString(plan.t3EntryPath, "#!/usr/bin/env node\n");
293 yield* fs.remove(plan.t3EntryPath);
294 commands.length = 0;
295​
296 yield* service.install;
297​
298 assert.isTrue(commands.some(({ command }) => command === "npm"));
299 }),
300 );
301​
302 it.effect("reads executable metadata from host process references", () =>
303 Effect.gen(function* () {
304 const { dirs } = yield* makeTestContext();
305 const commands: Array<RecordedCommand> = [];
306 const service = yield* BootService.make({
307 baseDir: dirs.baseDir,
308 logsDir: dirs.logsDir,
309 cliVersion: "0.0.27",
310 }).pipe(
311 Effect.provide(makeRecordingRunnerLayer(commands)),
312 provideHostRefs(dirs.home),
313 Effect.provideService(HostProcessExecutablePath, "/opt/node/bin/node"),
314 Effect.provideService(HostProcessArguments, ["/opt/node/bin/node", dirs.stableEntry]),
315 );
316​
317 const plan = yield* service.install;
318 assert.equal(plan.nodePath, "/opt/node/bin/node");
319 assert.equal(plan.t3EntryPath, dirs.stableEntry);
320 }),
321 );
322​
323 it.effect("cleans up and fails when the pinned runtime install fails", () =>
324 Effect.gen(function* () {
325 const { dirs, fs, path } = yield* makeTestContext();
326 const commands: Array<RecordedCommand> = [];
327 const service = yield* BootService.make({
328 baseDir: dirs.baseDir,
329 logsDir: dirs.logsDir,
330 cliVersion: "0.0.27",
331 host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
332 }).pipe(
333 Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "npm" })),
334 provideHostRefs(dirs.home),
335 );
336​
337 const error = yield* service.install.pipe(Effect.flip);
338 assert.isTrue(isCommandError(error));
339 const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
340 // The half-installed tree must not be reused by the next attempt.
341 assert.isFalse(yield* fs.exists(runtimeDir));
342 assert.isFalse(yield* fs.exists(path.join(runtimeDir, ".install-complete")));
343 }),
344 );
345​
346 it.effect("reports an installed-but-stale unit so the lifecycle can offer a repair", () =>
347 Effect.gen(function* () {
348 const { dirs, fs, path } = yield* makeTestContext();
349 const commands: Array<RecordedCommand> = [];
350 const service = yield* BootService.make({
351 baseDir: dirs.baseDir,
352 logsDir: dirs.logsDir,
353 cliVersion: "0.0.27",
354 host: makeHost(dirs.stableEntry),
355 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
356​
357 const unitDir = path.join(dirs.home, ".config", "systemd", "user");
358 yield* fs.makeDirectory(unitDir, { recursive: true });
359 yield* fs.writeFileString(
360 path.join(unitDir, "t3code.service"),
361 "[Service]\nExecStart=/old/node /old/t3 serve\n",
362 );
363​
364 const status = yield* service.status;
365 assert.isTrue(status.supported);
366 assert.isTrue(status.installed);
367 assert.isFalse(status.current);
368 }),
369 );
370​
371 it.effect("reports a current unit as stale when its entry point is gone", () =>
372 Effect.gen(function* () {
373 const { dirs, fs } = yield* makeTestContext();
374 const commands: Array<RecordedCommand> = [];
375 const service = yield* BootService.make({
376 baseDir: dirs.baseDir,
377 logsDir: dirs.logsDir,
378 cliVersion: "0.0.27",
379 host: makeHost(dirs.stableEntry),
380 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
381​
382 yield* service.install;
383 assert.isTrue((yield* service.status).current);
384​
385 // The pinned runtime (or global bin) was deleted to reclaim space; the
386 // unit still matches byte-for-byte but would crashloop at boot.
387 yield* fs.remove(dirs.stableEntry);
388 const status = yield* service.status;
389 assert.isTrue(status.installed);
390 assert.isFalse(status.current);
391 }),
392 );
393​
394 it.effect("fails on non-Linux platforms without touching the filesystem", () =>
395 Effect.gen(function* () {
396 const { dirs, fs, path } = yield* makeTestContext();
397 const commands: Array<RecordedCommand> = [];
398 const service = yield* BootService.make({
399 baseDir: dirs.baseDir,
400 logsDir: dirs.logsDir,
401 cliVersion: "0.0.27",
402 host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
403 }).pipe(
404 Effect.provide(makeRecordingRunnerLayer(commands)),
405 provideHostRefs(dirs.home, "darwin"),
406 );
407​
408 const error = yield* service.install.pipe(Effect.flip);
409 assert.isTrue(isUnsupportedError(error));
410 assert.lengthOf(commands, 0);
411 assert.isFalse(
412 yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
413 );
414​
415 const status = yield* service.status;
416 assert.isFalse(status.supported);
417 assert.isFalse(status.installed);
418 }),
419 );
420​
421 it.effect("removes the unit file when an activation step fails", () =>
422 Effect.gen(function* () {
423 const { dirs, fs, path } = yield* makeTestContext();
424 const commands: Array<RecordedCommand> = [];
425 const service = yield* BootService.make({
426 baseDir: dirs.baseDir,
427 logsDir: dirs.logsDir,
428 cliVersion: "0.0.27",
429 host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
430 }).pipe(
431 Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "loginctl" })),
432 provideHostRefs(dirs.home),
433 );
434​
435 const error = yield* service.install.pipe(Effect.flip);
436 assert.isTrue(isCommandError(error));
437 // A leftover unit would make status report "installed" even though
438 // linger never happened.
439 assert.isFalse(
440 yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
441 );
442 const status = yield* service.status;
443 assert.isFalse(status.installed);
444 assert.isTrue(
445 commands.some(
446 ({ command, args }) =>
447 command === "systemctl" && args.join(" ") === "--user disable --now t3code.service",
448 ),
449 );
450 }),
451 );
452​
453 it.effect("restores the previous unit when a repair cannot activate", () =>
454 Effect.gen(function* () {
455 const { dirs, fs, path } = yield* makeTestContext();
456 const initialCommands: Array<RecordedCommand> = [];
457 const initialService = yield* BootService.make({
458 baseDir: dirs.baseDir,
459 logsDir: dirs.logsDir,
460 cliVersion: "0.0.27",
461 host: makeHost(dirs.stableEntry),
462 }).pipe(
463 Effect.provide(makeRecordingRunnerLayer(initialCommands)),
464 provideHostRefs(dirs.home),
465 );
466 yield* initialService.install;
467​
468 const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service");
469 const previousUnit = yield* fs.readFileString(unitPath);
470 const replacementEntry = path.join(dirs.home, "replacement-bin.mjs");
471 yield* fs.writeFileString(replacementEntry, "#!/usr/bin/env node\n");
472 const repairCommands: Array<RecordedCommand> = [];
473 const repairService = yield* BootService.make({
474 baseDir: dirs.baseDir,
475 logsDir: dirs.logsDir,
476 cliVersion: "0.0.28",
477 host: makeHost(replacementEntry),
478 }).pipe(
479 Effect.provide(makeRecordingRunnerLayer(repairCommands, { failCommand: "loginctl" })),
480 provideHostRefs(dirs.home),
481 );
482​
483 const error = yield* repairService.install.pipe(Effect.flip);
484​
485 assert.isTrue(isCommandError(error));
486 assert.equal(yield* fs.readFileString(unitPath), previousUnit);
487 assert.isTrue(
488 repairCommands.some(
489 ({ command, args }) =>
490 command === "systemctl" && args.join(" ") === "--user restart t3code.service",
491 ),
492 );
493 }),
494 );
495​
496 it.effect("keeps the unit when stopping it during uninstall fails", () =>
497 Effect.gen(function* () {
498 const { dirs, fs, path } = yield* makeTestContext();
499 const installCommands: Array<RecordedCommand> = [];
500 const installedService = yield* BootService.make({
501 baseDir: dirs.baseDir,
502 logsDir: dirs.logsDir,
503 cliVersion: "0.0.27",
504 host: makeHost(dirs.stableEntry),
505 }).pipe(
506 Effect.provide(makeRecordingRunnerLayer(installCommands)),
507 provideHostRefs(dirs.home),
508 );
509 yield* installedService.install;
510​
511 const uninstallCommands: Array<RecordedCommand> = [];
512 const failingService = yield* BootService.make({
513 baseDir: dirs.baseDir,
514 logsDir: dirs.logsDir,
515 cliVersion: "0.0.27",
516 host: makeHost(dirs.stableEntry),
517 }).pipe(
518 Effect.provide(
519 makeRecordingRunnerLayer(uninstallCommands, {
520 failWhen: (command, args) =>
521 command === "systemctl" && args.includes("disable") && args.includes("--now"),
522 }),
523 ),
524 provideHostRefs(dirs.home),
525 );
526​
527 const error = yield* failingService.uninstall.pipe(Effect.flip);
528​
529 assert.isTrue(isCommandError(error));
530 assert.isTrue(
531 yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
532 );
533 }),
534 );
535​
536 it.effect("appends failed steps to the boot-service log", () =>
537 Effect.gen(function* () {
538 const { dirs, fs, path } = yield* makeTestContext();
539 const commands: Array<RecordedCommand> = [];
540 const service = yield* BootService.make({
541 baseDir: dirs.baseDir,
542 logsDir: dirs.logsDir,
543 cliVersion: "0.0.27",
544 host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
545 }).pipe(
546 Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "systemctl" })),
547 provideHostRefs(dirs.home),
548 );
549​
550 const error = yield* service.install.pipe(Effect.flip);
551 assert.isTrue(isCommandError(error));
552 if (!isCommandError(error)) return;
553 assert.equal(error.exitCode, 1);
554 assert.equal(error.stderrLength, "systemctl exploded".length);
555​
556 const logPath = path.join(dirs.logsDir, "boot-service.log");
557 assert.isTrue(yield* fs.exists(logPath));
558 assert.include(yield* fs.readFileString(logPath), "exit code 1");
559 }),
560 );
561});