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

bootService.test.ts

416 lines16.7 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import {
4 HostProcessArguments,
5 HostProcessExecutablePath,
6 HostProcessPlatform,
7 HostProcessUserId,
8} from "@t3tools/shared/hostProcess";
9import * as ConfigProvider from "effect/ConfigProvider";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Path from "effect/Path";
15import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
16​
17import * as ProcessRunner from "../processRunner.ts";
18import * as BootService from "./bootService.ts";
19import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
20import {
21 parseServiceState,
22 SERVICE_LAUNCHER_PROTOCOL,
23 serviceStateHasPendingUpdate,
24} from "./serviceProtocol.ts";
25​
26it("keeps systemd pinned to the stable launcher rather than a versioned server", () => {
27 const unit = BootService.renderBootServiceUnit({
28 nodePath: "/usr/bin/node",
29 launcherPath: "/home/theo/.t3/runtime/service-launcher.mjs",
30 baseDir: "/home/theo/.t3",
31 logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
32 unitPath: "/home/theo/.config/systemd/user/t3code.service",
33 });
34​
35 expect(unit).toContain("ExecStart=/usr/bin/node /home/theo/.t3/runtime/service-launcher.mjs");
36 expect(unit).toContain("KillMode=mixed");
37 expect(unit).not.toContain("versions/1.2.3");
38});
39​
40it("survives the kernel OOM-killing a greedy agent child", () => {
41 const unit = BootService.renderBootServiceUnit({
42 nodePath: "/usr/bin/node",
43 launcherPath: "/home/theo/.t3/runtime/service-launcher.mjs",
44 baseDir: "/home/theo/.t3",
45 logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
46 unitPath: "/home/theo/.config/systemd/user/t3code.service",
47 });
48​
49 expect(unit).toContain("OOMPolicy=continue");
50});
51​
52const macPlan = {
53 nodePath: "/opt/homebrew/bin/node",
54 launcherPath: "/Users/theo/.t3/runtime/service-launcher.mjs",
55 baseDir: "/Users/theo/.t3",
56 logPath: "/Users/theo/.t3/userdata/logs/boot-service.log",
57 unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.service.plist",
58};
59const macInstallerPath =
60 "/opt/homebrew/bin:/Users/theo/.npm-global/bin:/Users/theo/.nvm/versions/node/v22.16.0/bin:/usr/bin:/bin";
61const macRenderOptions = { homeDir: "/Users/theo", environmentPath: macInstallerPath };
62​
63it("keeps launchd pinned to the stable launcher rather than a versioned server", () => {
64 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
65​
66 expect(plist).toContain("<string>/opt/homebrew/bin/node</string>");
67 expect(plist).toContain("<string>/Users/theo/.t3/runtime/service-launcher.mjs</string>");
68 expect(plist).not.toContain("versions/1.2.3");
69});
70​
71it("preserves the installer's provider search path in the launch agent", () => {
72 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
73​
74 expect(plist).toContain(` <key>PATH</key>\n <string>${macInstallerPath}</string>`);
75});
76​
77it("restarts the launch agent on the systemd cadence", () => {
78 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
79​
80 expect(plist).toContain("<key>RunAtLoad</key>\n <true/>");
81 expect(plist).toContain("<key>KeepAlive</key>\n <true/>");
82 expect(plist).toContain("<key>ThrottleInterval</key>\n <integer>5</integer>");
83 expect(plist).toContain("<key>ExitTimeOut</key>\n <integer>90</integer>");
84});
85​
86it("appends both stdio streams to the boot service log", () => {
87 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
88​
89 expect(plist).toContain(
90 "<key>StandardOutPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
91 );
92 expect(plist).toContain(
93 "<key>StandardErrorPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
94 );
95});
96​
97it("escapes XML in host paths", () => {
98 const plist = BootService.renderBootServicePlist(
99 { ...macPlan, baseDir: "/Users/theo/T3 & <Co>" },
100 { homeDir: "/Users/theo", environmentPath: "/Users/theo/Tools & <Scripts>:/usr/bin" },
101 );
102​
103 expect(plist).toContain("<string>/Users/theo/T3 &amp; &lt;Co&gt;</string>");
104 expect(plist).toContain("<string>/Users/theo/Tools &amp; &lt;Scripts&gt;:/usr/bin</string>");
105});
106​
107const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
108 platform: NodeJS.Platform = "linux",
109 usePinnedLauncher = false,
110 installerPath = macInstallerPath,
111) {
112 const fs = yield* FileSystem.FileSystem;
113 const path = yield* Path.Path;
114 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
115 const baseDir = path.join(home, ".t3");
116 const sourceLauncher = path.join(home, "service-launcher.mjs");
117 const statePath = path.join(baseDir, "runtime", "service-state.json");
118 yield* fs.writeFileString(sourceLauncher, "export {};\n");
119 const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3");
120 yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
121 yield* fs.writeFileString(runtime.entryPath, "export {};\n");
122 yield* fs.writeFileString(
123 path.join(path.dirname(runtime.entryPath), "service-launcher.mjs"),
124 "export const source = 'pinned runtime';\n",
125 );
126 yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
127​
128 const commands: string[] = [];
129 const timeouts = new Map<string, unknown>();
130 const control: { failCommand: string | undefined } = { failCommand: undefined };
131 const runner = ProcessRunner.ProcessRunner.of({
132 run: (input) =>
133 Effect.sync(() => {
134 const command = `${input.command} ${input.args.join(" ")}`;
135 commands.push(command);
136 timeouts.set(command, input.timeout);
137 return {
138 stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",
139 stderr: "",
140 code: ChildProcessSpawner.ExitCode(command === control.failCommand ? 1 : 0),
141 timedOut: false,
142 stdoutTruncated: false,
143 stderrTruncated: false,
144 stdoutInvalidUtf8: false,
145 stderrInvalidUtf8: false,
146 };
147 }),
148 });
149 const makeService = (environmentPath = installerPath) =>
150 BootService.make({
151 baseDir,
152 logsDir: path.join(baseDir, "userdata", "logs"),
153 cliVersion: "1.2.3",
154 host: {
155 execPath: "/usr/bin/node",
156 ...(usePinnedLauncher ? {} : { launcherSourcePath: sourceLauncher }),
157 },
158 }).pipe(
159 Effect.provideService(ProcessRunner.ProcessRunner, runner),
160 Effect.provide(
161 Layer.mergeAll(
162 Layer.succeed(HostProcessPlatform, platform),
163 Layer.succeed(HostProcessUserId, 501),
164 Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),
165 Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),
166 ConfigProvider.layer(
167 ConfigProvider.fromEnv({
168 env: { HOME: home, ...(environmentPath === "" ? {} : { PATH: environmentPath }) },
169 }),
170 ),
171 ),
172 ),
173 );
174 const service = yield* makeService();
175 return { service, makeService, fs, statePath, commands, timeouts, control };
176});
177​
178it.layer(NodeServices.layer)("boot service install", (it) => {
179 it.effect("installs, reports current state, and uninstalls", () =>
180 Effect.gen(function* () {
181 const { service, fs, statePath, commands, timeouts } = yield* makeHarness();
182 const plan = yield* service.install;
183​
184 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
185 protocol: SERVICE_LAUNCHER_PROTOCOL,
186 activeVersion: "1.2.3",
187 });
188 expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
189 expect((yield* service.status).current).toBe(true);
190 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
191 const pendingState = JSON.stringify({
192 protocol: SERVICE_LAUNCHER_PROTOCOL,
193 activeVersion: "1.2.3",
194 update: {
195 id: "u",
196 fromVersion: "1.2.3",
197 targetVersion: "1.2.4",
198 dbPath: "/tmp/state.sqlite",
199 status: "pending",
200 },
201 });
202 yield* fs.writeFileString(statePath, pendingState);
203 expect((yield* service.status).current).toBe(false);
204 expect(yield* service.uninstall).toBe(true);
205 expect((yield* service.status).installed).toBe(false);
206 expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
207 // The stop can block up to systemd's 90s TimeoutStopSec; the runner's
208 // 60s default would cancel it mid-shutdown.
209 expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
210 Duration.seconds(120),
211 );
212 }),
213 );
214​
215 it.effect("copies the launcher from the prepared pinned runtime", () =>
216 Effect.gen(function* () {
217 const { service, fs } = yield* makeHarness("linux", true);
218 const plan = yield* service.install;
219​
220 expect(yield* fs.readFileString(plan.launcherPath)).toBe(
221 "export const source = 'pinned runtime';\n",
222 );
223 }),
224 );
225​
226 it.effect("restarts an installed service when repair fails", () =>
227 Effect.gen(function* () {
228 const { service, commands, control } = yield* makeHarness();
229 yield* service.install;
230 commands.length = 0;
231 control.failCommand = "systemctl --user daemon-reload";
232​
233 const error = yield* service.install.pipe(Effect.flip);
234 expect(error._tag).toBe("BootServiceCommandError");
235 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
236 "systemctl --user stop t3code.service",
237 "systemctl --user daemon-reload",
238 "systemctl --user restart t3code.service",
239 ]);
240 }),
241 );
242​
243 it.effect("restarts without overwriting a pending remote update", () =>
244 Effect.gen(function* () {
245 const { service, fs, statePath, commands } = yield* makeHarness();
246 yield* service.install;
247 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
248 const pendingState = JSON.stringify({
249 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
250 activeVersion: "1.2.3",
251 update: {
252 id: "remote-update",
253 fromVersion: "1.2.3",
254 targetVersion: "1.2.4",
255 status: "pending",
256 },
257 });
258 yield* fs.writeFileString(statePath, pendingState);
259 commands.length = 0;
260​
261 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
262 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
263 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
264 "systemctl --user stop t3code.service",
265 "systemctl --user restart t3code.service",
266 ]);
267 }),
268 );
269​
270 it.effect("fails closed on Windows", () =>
271 Effect.gen(function* () {
272 const { service } = yield* makeHarness("win32");
273 expect((yield* service.status).supported).toBe(false);
274 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
275 }),
276 );
277​
278 it.effect("installs, reports current state, and uninstalls on macOS", () =>
279 Effect.gen(function* () {
280 const { service, fs, statePath, commands, timeouts } = yield* makeHarness("darwin");
281 const plan = yield* service.install;
282​
283 expect(plan.unitPath.endsWith("Library/LaunchAgents/com.t3tools.t3code.service.plist")).toBe(
284 true,
285 );
286 expect(yield* fs.readFileString(plan.unitPath)).toContain(
287 ` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
288 );
289 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
290 protocol: SERVICE_LAUNCHER_PROTOCOL,
291 activeVersion: "1.2.3",
292 });
293 expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
294 expect((yield* service.status).current).toBe(true);
295 expect(yield* service.uninstall).toBe(true);
296 expect((yield* service.status).installed).toBe(false);
297 expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
298 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
299 // A bootout can block up to the plist's 90s ExitTimeOut; the runner's
300 // 60s default would cancel it and let bootstrap race a loaded job.
301 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
302 Duration.seconds(120),
303 );
304 }),
305 );
306​
307 it.effect("restarts the launch agent when repair fails", () =>
308 Effect.gen(function* () {
309 const { service, commands, control } = yield* makeHarness("darwin");
310 yield* service.install;
311 const plistPath = (yield* service.status).unitPath;
312 commands.length = 0;
313 control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
314​
315 const error = yield* service.install.pipe(Effect.flip);
316 expect(error._tag).toBe("BootServiceCommandError");
317 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
318 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
319 "launchctl enable gui/501/com.t3tools.t3code.service",
320 `launchctl bootstrap gui/501 ${plistPath}`,
321 `launchctl bootstrap gui/501 ${plistPath}`,
322 ]);
323 }),
324 );
325​
326 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
327 Effect.gen(function* () {
328 const { service, fs } = yield* makeHarness("darwin", false, "");
329 const plan = yield* service.install;
330​
331 expect(yield* fs.readFileString(plan.unitPath)).toContain(
332 " <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
333 );
334 expect((yield* service.status).current).toBe(true);
335 }),
336 );
337​
338 it.effect("adds missing provider directories to a minimal installer PATH", () =>
339 Effect.gen(function* () {
340 const { service, fs } = yield* makeHarness("darwin", false, "/usr/bin:/bin");
341 const plan = yield* service.install;
342​
343 expect(yield* fs.readFileString(plan.unitPath)).toContain(
344 " <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",
345 );
346 expect((yield* service.status).current).toBe(true);
347 }),
348 );
349​
350 it.effect("keeps an installed launch agent current when the process PATH changes", () =>
351 Effect.gen(function* () {
352 const { service, makeService } = yield* makeHarness("darwin");
353 yield* service.install;
354​
355 const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");
356 expect((yield* restartedService.status).current).toBe(true);
357 }),
358 );
359​
360 it.effect("drops PATH directories that cannot be represented in a launch agent plist", () =>
361 Effect.gen(function* () {
362 const { service, fs } = yield* makeHarness(
363 "darwin",
364 false,
365 "/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",
366 );
367 const plan = yield* service.install;
368 const plist = yield* fs.readFileString(plan.unitPath);
369​
370 expect(plist).toContain(
371 " <key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
372 );
373 expect(plist).not.toContain("\u0001");
374 expect((yield* service.status).current).toBe(true);
375 }),
376 );
377​
378 it.effect("ignores a bootout for an agent that is not loaded", () =>
379 Effect.gen(function* () {
380 const { service, control } = yield* makeHarness("darwin");
381 yield* service.install;
382 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
383​
384 yield* service.install;
385 expect((yield* service.status).current).toBe(true);
386 }),
387 );
388​
389 it.effect("restarts without overwriting a pending remote update on macOS", () =>
390 Effect.gen(function* () {
391 const { service, fs, statePath, commands } = yield* makeHarness("darwin");
392 yield* service.install;
393 const plistPath = (yield* service.status).unitPath;
394 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
395 const pendingState = JSON.stringify({
396 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
397 activeVersion: "1.2.3",
398 update: {
399 id: "remote-update",
400 fromVersion: "1.2.3",
401 targetVersion: "1.2.4",
402 status: "pending",
403 },
404 });
405 yield* fs.writeFileString(statePath, pendingState);
406 commands.length = 0;
407​
408 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
409 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
410 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
411 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
412 `launchctl bootstrap gui/501 ${plistPath}`,
413 ]);
414 }),
415 );
416});