Open History to see the last commit
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>;
27}
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=T3CODE_HOME=/home/theo/.t3",
112 "Environment=T3_BOOT_SERVICE_UNIT=t3code.service",
113 "ExecStart=/usr/local/bin/node /home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs serve",
114 "Restart=always",
115 "RestartSec=5",
116 "StandardOutput=append:/home/theo/.t3/userdata/logs/boot-service.log",
117 "StandardError=append:/home/theo/.t3/userdata/logs/boot-service.log",
118 "",
119 "[Install]",
120 "WantedBy=default.target",
121 "",
122 ].join("\n"),
123 );
124});
125
126it("quotes systemd values containing spaces and escapes percent specifiers", () => {
127 assert.equal(BootService.quoteSystemdValue("/plain/path"), "/plain/path");
128 assert.equal(BootService.quoteSystemdValue("/home/me/T3 Data"), '"/home/me/T3 Data"');
129 assert.equal(BootService.quoteSystemdValue("/opt/100%cpu"), "/opt/100%%cpu");
130
131 const unit = BootService.renderBootServiceUnit({
132 nodePath: "/home/me/my tools/node",
133 t3EntryPath: "/home/me/T3 Data/bin.mjs",
134 baseDir: "/home/me/T3 Data",
135 logPath: "/home/me/100%logs/boot.log",
136 unitPath: "/home/me/.config/systemd/user/t3code.service",
137 });
138 assert.include(unit, 'ExecStart="/home/me/my tools/node" "/home/me/T3 Data/bin.mjs" serve');
139 assert.include(unit, 'Environment=T3CODE_HOME="/home/me/T3 Data"');
140 // append: paths take the rest of the line literally (spaces are fine,
141 // quoting is not), but % still goes through specifier expansion.
142 assert.include(unit, "StandardOutput=append:/home/me/100%%logs/boot.log");
143 assert.include(unit, "StandardError=append:/home/me/100%%logs/boot.log");
144});
145
146it("flags package-manager cache entry points as ephemeral", () => {
147 assert.isTrue(
148 BootService.isEphemeralCacheEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
149 );
150 assert.isTrue(
151 BootService.isEphemeralCacheEntry("C:\\Users\\theo\\AppData\\npm-cache\\_npx\\abc\\bin.mjs"),
152 );
153 assert.isTrue(
154 BootService.isEphemeralCacheEntry(
155 "/home/theo/.cache/pnpm/dlx/abc/node_modules/t3/dist/bin.mjs",
156 ),
157 );
158 assert.isTrue(
159 BootService.isEphemeralCacheEntry("/home/theo/.bun/install/cache/t3@0.0.27/dist/bin.mjs"),
160 );
161 assert.isFalse(BootService.isEphemeralCacheEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
162 assert.isFalse(
163 BootService.isEphemeralCacheEntry(
164 "/home/theo/dev/pnpm/dlx-tools/t3/node_modules/t3/dist/bin.mjs",
165 ),
166 );
167 assert.isFalse(
168 BootService.isEphemeralCacheEntry(
169 "/home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs",
170 ),
171 );
172});
173
174it.layer(NodeServices.layer)("BootService", (it) => {
175 it.effect("reconciles the standalone service once and is then idempotent", () =>
176 Effect.gen(function* () {
177 const { dirs } = yield* makeTestContext();
178 const commands: Array<RecordedCommand> = [];
179 const service = yield* BootService.make({
180 baseDir: dirs.baseDir,
181 logsDir: dirs.logsDir,
182 cliVersion: "0.0.27",
183 host: makeHost(dirs.stableEntry),
184 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
185
186 const first = yield* reconcileService().pipe(
187 Effect.provideService(BootService.BootService, service),
188 );
189 assert.isTrue(first.changed);
190 if (!first.changed) return;
191 assert.isFalse(first.previouslyInstalled);
192
193 const commandCount = commands.length;
194 const second = yield* reconcileService().pipe(
195 Effect.provideService(BootService.BootService, service),
196 );
197 assert.isFalse(second.changed);
198 assert.lengthOf(commands, commandCount);
199 }),
200 );
201
202 it.effect("installs the unit, enables the service, and enables linger", () =>
203 Effect.gen(function* () {
204 const { dirs, fs, path } = yield* makeTestContext();
205 const commands: Array<RecordedCommand> = [];
206 const service = yield* BootService.make({
207 baseDir: dirs.baseDir,
208 logsDir: dirs.logsDir,
209 cliVersion: "0.0.27",
210 host: makeHost(dirs.stableEntry),
211 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
212
213 const plan = yield* service.install;
214
215 // A stable entry point is reused directly — no npm install.
216 assert.equal(plan.t3EntryPath, dirs.stableEntry);
217 assert.deepEqual(
218 commands.map((entry) => [entry.command, ...entry.args].join(" ")),
219 [
220 "systemctl --user daemon-reload",
221 "systemctl --user enable t3code.service",
222 // restart (not enable --now) so repairing a stale unit replaces a
223 // running process instead of leaving the old one until reboot.
224 "systemctl --user restart t3code.service",
225 "loginctl enable-linger",
226 ],
227 );
228
229 const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service");
230 const unit = yield* fs.readFileString(unitPath);
231 assert.include(unit, `ExecStart=/usr/local/bin/node ${dirs.stableEntry} serve`);
232 assert.include(unit, `Environment=T3CODE_HOME=${dirs.baseDir}`);
233
234 const status = yield* service.status;
235 assert.isTrue(status.supported);
236 assert.isTrue(status.installed);
237 assert.isTrue(status.current);
238
239 const removed = yield* service.uninstall;
240 assert.isTrue(removed);
241 assert.isFalse(yield* fs.exists(unitPath));
242 const statusAfter = yield* service.status;
243 assert.isFalse(statusAfter.installed);
244 const removedAgain = yield* service.uninstall;
245 assert.isFalse(removedAgain);
246 }),
247 );
248
249 it.effect("pins a runtime via npm install when running from the npx cache", () =>
250 Effect.gen(function* () {
251 const { dirs, fs, path } = yield* makeTestContext();
252 const commands: Array<RecordedCommand> = [];
253 const service = yield* BootService.make({
254 baseDir: dirs.baseDir,
255 logsDir: dirs.logsDir,
256 cliVersion: "0.0.27",
257 host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
258 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
259
260 const plan = yield* service.install;
261
262 const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
263 assert.equal(
264 plan.t3EntryPath,
265 path.join(runtimeDir, "node_modules", "t3", "dist", "bin.mjs"),
266 );
267 assert.deepEqual(commands[0], {
268 command: "npm",
269 args: ["install", "--prefix", runtimeDir, "--no-fund", "--no-audit", "t3@0.0.27"],
270 });
271 // Success is recorded via a sentinel so interrupted installs re-run.
272 assert.isTrue(yield* fs.exists(path.join(runtimeDir, ".install-complete")));
273 }),
274 );
275
276 it.effect("reinstalls a pinned runtime when its entry point is missing", () =>
277 Effect.gen(function* () {
278 const { dirs, fs, path } = yield* makeTestContext();
279 const commands: Array<RecordedCommand> = [];
280 const service = yield* BootService.make({
281 baseDir: dirs.baseDir,
282 logsDir: dirs.logsDir,
283 cliVersion: "0.0.27",
284 host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
285 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
286
287 const plan = yield* service.install;
288 yield* fs.makeDirectory(path.dirname(plan.t3EntryPath), { recursive: true });
289 yield* fs.writeFileString(plan.t3EntryPath, "#!/usr/bin/env node\n");
290 yield* fs.remove(plan.t3EntryPath);
291 commands.length = 0;
292
293 yield* service.install;
294
295 assert.isTrue(commands.some(({ command }) => command === "npm"));
296 }),
297 );
298
299 it.effect("reads executable metadata from host process references", () =>
300 Effect.gen(function* () {
301 const { dirs } = yield* makeTestContext();
302 const commands: Array<RecordedCommand> = [];
303 const service = yield* BootService.make({
304 baseDir: dirs.baseDir,
305 logsDir: dirs.logsDir,
306 cliVersion: "0.0.27",
307 }).pipe(
308 Effect.provide(makeRecordingRunnerLayer(commands)),
309 provideHostRefs(dirs.home),
310 Effect.provideService(HostProcessExecutablePath, "/opt/node/bin/node"),
311 Effect.provideService(HostProcessArguments, ["/opt/node/bin/node", dirs.stableEntry]),
312 );
313
314 const plan = yield* service.install;
315 assert.equal(plan.nodePath, "/opt/node/bin/node");
316 assert.equal(plan.t3EntryPath, dirs.stableEntry);
317 }),
318 );
319
320 it.effect("cleans up and fails when the pinned runtime install fails", () =>
321 Effect.gen(function* () {
322 const { dirs, fs, path } = yield* makeTestContext();
323 const commands: Array<RecordedCommand> = [];
324 const service = yield* BootService.make({
325 baseDir: dirs.baseDir,
326 logsDir: dirs.logsDir,
327 cliVersion: "0.0.27",
328 host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
329 }).pipe(
330 Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "npm" })),
331 provideHostRefs(dirs.home),
332 );
333
334 const error = yield* service.install.pipe(Effect.flip);
335 assert.isTrue(isCommandError(error));
336 const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
337 // The half-installed tree must not be reused by the next attempt.
338 assert.isFalse(yield* fs.exists(runtimeDir));
339 assert.isFalse(yield* fs.exists(path.join(runtimeDir, ".install-complete")));
340 }),
341 );
342
343 it.effect("reports an installed-but-stale unit so the lifecycle can offer a repair", () =>
344 Effect.gen(function* () {
345 const { dirs, fs, path } = yield* makeTestContext();
346 const commands: Array<RecordedCommand> = [];
347 const service = yield* BootService.make({
348 baseDir: dirs.baseDir,
349 logsDir: dirs.logsDir,
350 cliVersion: "0.0.27",
351 host: makeHost(dirs.stableEntry),
352 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
353
354 const unitDir = path.join(dirs.home, ".config", "systemd", "user");
355 yield* fs.makeDirectory(unitDir, { recursive: true });
356 yield* fs.writeFileString(
357 path.join(unitDir, "t3code.service"),
358 "[Service]\nExecStart=/old/node /old/t3 serve\n",
359 );
360
361 const status = yield* service.status;
362 assert.isTrue(status.supported);
363 assert.isTrue(status.installed);
364 assert.isFalse(status.current);
365 }),
366 );
367
368 it.effect("reports a current unit as stale when its entry point is gone", () =>
369 Effect.gen(function* () {
370 const { dirs, fs } = yield* makeTestContext();
371 const commands: Array<RecordedCommand> = [];
372 const service = yield* BootService.make({
373 baseDir: dirs.baseDir,
374 logsDir: dirs.logsDir,
375 cliVersion: "0.0.27",
376 host: makeHost(dirs.stableEntry),
377 }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
378
379 yield* service.install;
380 assert.isTrue((yield* service.status).current);
381
382 // The pinned runtime (or global bin) was deleted to reclaim space; the
383 // unit still matches byte-for-byte but would crashloop at boot.
384 yield* fs.remove(dirs.stableEntry);
385 const status = yield* service.status;
386 assert.isTrue(status.installed);
387 assert.isFalse(status.current);
388 }),
389 );
390
391 it.effect("fails on non-Linux platforms without touching the filesystem", () =>
392 Effect.gen(function* () {
393 const { dirs, fs, path } = yield* makeTestContext();
394 const commands: Array<RecordedCommand> = [];
395 const service = yield* BootService.make({
396 baseDir: dirs.baseDir,
397 logsDir: dirs.logsDir,
398 cliVersion: "0.0.27",
399 host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
400 }).pipe(
401 Effect.provide(makeRecordingRunnerLayer(commands)),
402 provideHostRefs(dirs.home, "darwin"),
403 );
404
405 const error = yield* service.install.pipe(Effect.flip);
406 assert.isTrue(isUnsupportedError(error));
407 assert.lengthOf(commands, 0);
408 assert.isFalse(
409 yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
410 );
411
412 const status = yield* service.status;
413 assert.isFalse(status.supported);
414 assert.isFalse(status.installed);
415 }),
416 );
417
418 it.effect("removes the unit file when an activation step fails", () =>
419 Effect.gen(function* () {
420 const { dirs, fs, path } = yield* makeTestContext();
421 const commands: Array<RecordedCommand> = [];
422 const service = yield* BootService.make({
423 baseDir: dirs.baseDir,
424 logsDir: dirs.logsDir,
425 cliVersion: "0.0.27",
426 host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
427 }).pipe(
428 Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "loginctl" })),
429 provideHostRefs(dirs.home),
430 );
431
432 const error = yield* service.install.pipe(Effect.flip);
433 assert.isTrue(isCommandError(error));
434 // A leftover unit would make status report "installed" even though
435 // linger never happened.
436 assert.isFalse(
437 yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
438 );
439 const status = yield* service.status;
440 assert.isFalse(status.installed);
441 assert.isTrue(
442 commands.some(
443 ({ command, args }) =>
444 command === "systemctl" && args.join(" ") === "--user disable --now t3code.service",
445 ),
446 );
447 }),
448 );
449
450 it.effect("restores the previous unit when a repair cannot activate", () =>
451 Effect.gen(function* () {
452 const { dirs, fs, path } = yield* makeTestContext();
453 const initialCommands: Array<RecordedCommand> = [];
454 const initialService = yield* BootService.make({
455 baseDir: dirs.baseDir,
456 logsDir: dirs.logsDir,
457 cliVersion: "0.0.27",
458 host: makeHost(dirs.stableEntry),
459 }).pipe(
460 Effect.provide(makeRecordingRunnerLayer(initialCommands)),
461 provideHostRefs(dirs.home),
462 );
463 yield* initialService.install;
464
465 const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service");
466 const previousUnit = yield* fs.readFileString(unitPath);
467 const replacementEntry = path.join(dirs.home, "replacement-bin.mjs");
468 yield* fs.writeFileString(replacementEntry, "#!/usr/bin/env node\n");
469 const repairCommands: Array<RecordedCommand> = [];
470 const repairService = yield* BootService.make({
471 baseDir: dirs.baseDir,
472 logsDir: dirs.logsDir,
473 cliVersion: "0.0.28",
474 host: makeHost(replacementEntry),
475 }).pipe(
476 Effect.provide(makeRecordingRunnerLayer(repairCommands, { failCommand: "loginctl" })),
477 provideHostRefs(dirs.home),
478 );
479
480 const error = yield* repairService.install.pipe(Effect.flip);
481
482 assert.isTrue(isCommandError(error));
483 assert.equal(yield* fs.readFileString(unitPath), previousUnit);
484 assert.isTrue(
485 repairCommands.some(
486 ({ command, args }) =>
487 command === "systemctl" && args.join(" ") === "--user restart t3code.service",
488 ),
489 );
490 }),
491 );
492
493 it.effect("keeps the unit when stopping it during uninstall fails", () =>
494 Effect.gen(function* () {
495 const { dirs, fs, path } = yield* makeTestContext();
496 const installCommands: Array<RecordedCommand> = [];
497 const installedService = yield* BootService.make({
498 baseDir: dirs.baseDir,
499 logsDir: dirs.logsDir,
500 cliVersion: "0.0.27",
501 host: makeHost(dirs.stableEntry),
502 }).pipe(
503 Effect.provide(makeRecordingRunnerLayer(installCommands)),
504 provideHostRefs(dirs.home),
505 );
506 yield* installedService.install;
507
508 const uninstallCommands: Array<RecordedCommand> = [];
509 const failingService = yield* BootService.make({
510 baseDir: dirs.baseDir,
511 logsDir: dirs.logsDir,
512 cliVersion: "0.0.27",
513 host: makeHost(dirs.stableEntry),
514 }).pipe(
515 Effect.provide(
516 makeRecordingRunnerLayer(uninstallCommands, {
517 failWhen: (command, args) =>
518 command === "systemctl" && args.includes("disable") && args.includes("--now"),
519 }),
520 ),
521 provideHostRefs(dirs.home),
522 );
523
524 const error = yield* failingService.uninstall.pipe(Effect.flip);
525
526 assert.isTrue(isCommandError(error));
527 assert.isTrue(
528 yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
529 );
530 }),
531 );
532
533 it.effect("appends failed steps to the boot-service log", () =>
534 Effect.gen(function* () {
535 const { dirs, fs, path } = yield* makeTestContext();
536 const commands: Array<RecordedCommand> = [];
537 const service = yield* BootService.make({
538 baseDir: dirs.baseDir,
539 logsDir: dirs.logsDir,
540 cliVersion: "0.0.27",
541 host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
542 }).pipe(
543 Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "systemctl" })),
544 provideHostRefs(dirs.home),
545 );
546
547 const error = yield* service.install.pipe(Effect.flip);
548 assert.isTrue(isCommandError(error));
549 if (!isCommandError(error)) return;
550 assert.equal(error.exitCode, 1);
551 assert.equal(error.stderrLength, "systemctl exploded".length);
552
553 const logPath = path.join(dirs.logsDir, "boot-service.log");
554 assert.isTrue(yield* fs.exists(logPath));
555 assert.include(yield* fs.readFileString(logPath), "exit code 1");
556 }),
557 );
558});