Open History to see the last commit
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};
59
60it("keeps launchd pinned to the stable launcher rather than a versioned server", () => {
61 const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
62
63 expect(plist).toContain("<string>/opt/homebrew/bin/node</string>");
64 expect(plist).toContain("<string>/Users/theo/.t3/runtime/service-launcher.mjs</string>");
65 expect(plist).not.toContain("versions/1.2.3");
66});
67
68it("restarts the launch agent on the systemd cadence", () => {
69 const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
70
71 expect(plist).toContain("<key>RunAtLoad</key>\n <true/>");
72 expect(plist).toContain("<key>KeepAlive</key>\n <true/>");
73 expect(plist).toContain("<key>ThrottleInterval</key>\n <integer>5</integer>");
74 expect(plist).toContain("<key>ExitTimeOut</key>\n <integer>90</integer>");
75});
76
77it("appends both stdio streams to the boot service log", () => {
78 const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
79
80 expect(plist).toContain(
81 "<key>StandardOutPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
82 );
83 expect(plist).toContain(
84 "<key>StandardErrorPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
85 );
86});
87
88it("escapes XML in host paths", () => {
89 const plist = BootService.renderBootServicePlist(
90 { ...macPlan, baseDir: "/Users/theo/T3 & <Co>" },
91 { homeDir: "/Users/theo" },
92 );
93
94 expect(plist).toContain("<string>/Users/theo/T3 & <Co></string>");
95});
96
97const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
98 platform: NodeJS.Platform = "linux",
99 usePinnedLauncher = false,
100) {
101 const fs = yield* FileSystem.FileSystem;
102 const path = yield* Path.Path;
103 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
104 const baseDir = path.join(home, ".t3");
105 const sourceLauncher = path.join(home, "service-launcher.mjs");
106 const statePath = path.join(baseDir, "runtime", "service-state.json");
107 yield* fs.writeFileString(sourceLauncher, "export {};\n");
108 const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3");
109 yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
110 yield* fs.writeFileString(runtime.entryPath, "export {};\n");
111 yield* fs.writeFileString(
112 path.join(path.dirname(runtime.entryPath), "service-launcher.mjs"),
113 "export const source = 'pinned runtime';\n",
114 );
115 yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
116
117 const commands: string[] = [];
118 const timeouts = new Map<string, unknown>();
119 const control: { failCommand: string | undefined } = { failCommand: undefined };
120 const runner = ProcessRunner.ProcessRunner.of({
121 run: (input) =>
122 Effect.sync(() => {
123 const command = `${input.command} ${input.args.join(" ")}`;
124 commands.push(command);
125 timeouts.set(command, input.timeout);
126 return {
127 stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",
128 stderr: "",
129 code: ChildProcessSpawner.ExitCode(command === control.failCommand ? 1 : 0),
130 timedOut: false,
131 stdoutTruncated: false,
132 stderrTruncated: false,
133 stdoutInvalidUtf8: false,
134 stderrInvalidUtf8: false,
135 };
136 }),
137 });
138 const service = yield* BootService.make({
139 baseDir,
140 logsDir: path.join(baseDir, "userdata", "logs"),
141 cliVersion: "1.2.3",
142 host: {
143 execPath: "/usr/bin/node",
144 ...(usePinnedLauncher ? {} : { launcherSourcePath: sourceLauncher }),
145 },
146 }).pipe(
147 Effect.provideService(ProcessRunner.ProcessRunner, runner),
148 Effect.provide(
149 Layer.mergeAll(
150 Layer.succeed(HostProcessPlatform, platform),
151 Layer.succeed(HostProcessUserId, 501),
152 Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),
153 Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),
154 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
155 ),
156 ),
157 );
158 return { service, fs, statePath, commands, timeouts, control };
159});
160
161it.layer(NodeServices.layer)("boot service install", (it) => {
162 it.effect("installs, reports current state, and uninstalls", () =>
163 Effect.gen(function* () {
164 const { service, fs, statePath, commands, timeouts } = yield* makeHarness();
165 const plan = yield* service.install;
166
167 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
168 protocol: SERVICE_LAUNCHER_PROTOCOL,
169 activeVersion: "1.2.3",
170 });
171 expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
172 expect((yield* service.status).current).toBe(true);
173 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
174 const pendingState = JSON.stringify({
175 protocol: SERVICE_LAUNCHER_PROTOCOL,
176 activeVersion: "1.2.3",
177 update: {
178 id: "u",
179 fromVersion: "1.2.3",
180 targetVersion: "1.2.4",
181 dbPath: "/tmp/state.sqlite",
182 status: "pending",
183 },
184 });
185 yield* fs.writeFileString(statePath, pendingState);
186 expect((yield* service.status).current).toBe(false);
187 expect(yield* service.uninstall).toBe(true);
188 expect((yield* service.status).installed).toBe(false);
189 expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
190 // The stop can block up to systemd's 90s TimeoutStopSec; the runner's
191 // 60s default would cancel it mid-shutdown.
192 expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
193 Duration.seconds(120),
194 );
195 }),
196 );
197
198 it.effect("copies the launcher from the prepared pinned runtime", () =>
199 Effect.gen(function* () {
200 const { service, fs } = yield* makeHarness("linux", true);
201 const plan = yield* service.install;
202
203 expect(yield* fs.readFileString(plan.launcherPath)).toBe(
204 "export const source = 'pinned runtime';\n",
205 );
206 }),
207 );
208
209 it.effect("restarts an installed service when repair fails", () =>
210 Effect.gen(function* () {
211 const { service, commands, control } = yield* makeHarness();
212 yield* service.install;
213 commands.length = 0;
214 control.failCommand = "systemctl --user daemon-reload";
215
216 const error = yield* service.install.pipe(Effect.flip);
217 expect(error._tag).toBe("BootServiceCommandError");
218 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
219 "systemctl --user stop t3code.service",
220 "systemctl --user daemon-reload",
221 "systemctl --user restart t3code.service",
222 ]);
223 }),
224 );
225
226 it.effect("restarts without overwriting a pending remote update", () =>
227 Effect.gen(function* () {
228 const { service, fs, statePath, commands } = yield* makeHarness();
229 yield* service.install;
230 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
231 const pendingState = JSON.stringify({
232 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
233 activeVersion: "1.2.3",
234 update: {
235 id: "remote-update",
236 fromVersion: "1.2.3",
237 targetVersion: "1.2.4",
238 status: "pending",
239 },
240 });
241 yield* fs.writeFileString(statePath, pendingState);
242 commands.length = 0;
243
244 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
245 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
246 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
247 "systemctl --user stop t3code.service",
248 "systemctl --user restart t3code.service",
249 ]);
250 }),
251 );
252
253 it.effect("fails closed on Windows", () =>
254 Effect.gen(function* () {
255 const { service } = yield* makeHarness("win32");
256 expect((yield* service.status).supported).toBe(false);
257 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
258 }),
259 );
260
261 it.effect("installs, reports current state, and uninstalls on macOS", () =>
262 Effect.gen(function* () {
263 const { service, fs, statePath, commands, timeouts } = yield* makeHarness("darwin");
264 const plan = yield* service.install;
265
266 expect(plan.unitPath.endsWith("Library/LaunchAgents/com.t3tools.t3code.service.plist")).toBe(
267 true,
268 );
269 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
270 protocol: SERVICE_LAUNCHER_PROTOCOL,
271 activeVersion: "1.2.3",
272 });
273 expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
274 expect((yield* service.status).current).toBe(true);
275 expect(yield* service.uninstall).toBe(true);
276 expect((yield* service.status).installed).toBe(false);
277 expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
278 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
279 // A bootout can block up to the plist's 90s ExitTimeOut; the runner's
280 // 60s default would cancel it and let bootstrap race a loaded job.
281 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
282 Duration.seconds(120),
283 );
284 }),
285 );
286
287 it.effect("restarts the launch agent when repair fails", () =>
288 Effect.gen(function* () {
289 const { service, commands, control } = yield* makeHarness("darwin");
290 yield* service.install;
291 const plistPath = (yield* service.status).unitPath;
292 commands.length = 0;
293 control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
294
295 const error = yield* service.install.pipe(Effect.flip);
296 expect(error._tag).toBe("BootServiceCommandError");
297 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
298 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
299 "launchctl enable gui/501/com.t3tools.t3code.service",
300 `launchctl bootstrap gui/501 ${plistPath}`,
301 `launchctl bootstrap gui/501 ${plistPath}`,
302 ]);
303 }),
304 );
305
306 it.effect("ignores a bootout for an agent that is not loaded", () =>
307 Effect.gen(function* () {
308 const { service, control } = yield* makeHarness("darwin");
309 yield* service.install;
310 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
311
312 yield* service.install;
313 expect((yield* service.status).current).toBe(true);
314 }),
315 );
316
317 it.effect("restarts without overwriting a pending remote update on macOS", () =>
318 Effect.gen(function* () {
319 const { service, fs, statePath, commands } = yield* makeHarness("darwin");
320 yield* service.install;
321 const plistPath = (yield* service.status).unitPath;
322 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
323 const pendingState = JSON.stringify({
324 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
325 activeVersion: "1.2.3",
326 update: {
327 id: "remote-update",
328 fromVersion: "1.2.3",
329 targetVersion: "1.2.4",
330 status: "pending",
331 },
332 });
333 yield* fs.writeFileString(statePath, pendingState);
334 commands.length = 0;
335
336 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
337 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
338 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
339 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
340 `launchctl bootstrap gui/501 ${plistPath}`,
341 ]);
342 }),
343 );
344});