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