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

bootService.test.ts

205 lines7.8 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import {
4 HostProcessArguments,
5 HostProcessExecutablePath,
6 HostProcessPlatform,
7} from "@t3tools/shared/hostProcess";
8import * as ConfigProvider from "effect/ConfigProvider";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
14​
15import * as ProcessRunner from "../processRunner.ts";
16import * as BootService from "./bootService.ts";
17import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
18import {
19 parseServiceState,
20 SERVICE_LAUNCHER_PROTOCOL,
21 serviceStateHasPendingUpdate,
22} from "./serviceProtocol.ts";
23​
24it("keeps systemd pinned to the stable launcher rather than a versioned server", () => {
25 const unit = BootService.renderBootServiceUnit({
26 nodePath: "/usr/bin/node",
27 launcherPath: "/home/theo/.t3/runtime/service-launcher.mjs",
28 baseDir: "/home/theo/.t3",
29 logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
30 unitPath: "/home/theo/.config/systemd/user/t3code.service",
31 });
32​
33 expect(unit).toContain("ExecStart=/usr/bin/node /home/theo/.t3/runtime/service-launcher.mjs");
34 expect(unit).toContain("KillMode=mixed");
35 expect(unit).not.toContain("versions/1.2.3");
36});
37​
38it("survives the kernel OOM-killing a greedy agent child", () => {
39 const unit = BootService.renderBootServiceUnit({
40 nodePath: "/usr/bin/node",
41 launcherPath: "/home/theo/.t3/runtime/service-launcher.mjs",
42 baseDir: "/home/theo/.t3",
43 logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
44 unitPath: "/home/theo/.config/systemd/user/t3code.service",
45 });
46​
47 expect(unit).toContain("OOMPolicy=continue");
48});
49​
50const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
51 platform: NodeJS.Platform = "linux",
52 usePinnedLauncher = false,
53) {
54 const fs = yield* FileSystem.FileSystem;
55 const path = yield* Path.Path;
56 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
57 const baseDir = path.join(home, ".t3");
58 const sourceLauncher = path.join(home, "service-launcher.mjs");
59 const statePath = path.join(baseDir, "runtime", "service-state.json");
60 yield* fs.writeFileString(sourceLauncher, "export {};\n");
61 const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3");
62 yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
63 yield* fs.writeFileString(runtime.entryPath, "export {};\n");
64 yield* fs.writeFileString(
65 path.join(path.dirname(runtime.entryPath), "service-launcher.mjs"),
66 "export const source = 'pinned runtime';\n",
67 );
68 yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
69​
70 const commands: string[] = [];
71 const control: { failCommand: string | undefined } = { failCommand: undefined };
72 const runner = ProcessRunner.ProcessRunner.of({
73 run: (input) =>
74 Effect.sync(() => {
75 const command = `${input.command} ${input.args.join(" ")}`;
76 commands.push(command);
77 return {
78 stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",
79 stderr: "",
80 code: ChildProcessSpawner.ExitCode(command === control.failCommand ? 1 : 0),
81 timedOut: false,
82 stdoutTruncated: false,
83 stderrTruncated: false,
84 stdoutInvalidUtf8: false,
85 stderrInvalidUtf8: false,
86 };
87 }),
88 });
89 const service = yield* BootService.make({
90 baseDir,
91 logsDir: path.join(baseDir, "userdata", "logs"),
92 cliVersion: "1.2.3",
93 host: {
94 execPath: "/usr/bin/node",
95 ...(usePinnedLauncher ? {} : { launcherSourcePath: sourceLauncher }),
96 },
97 }).pipe(
98 Effect.provideService(ProcessRunner.ProcessRunner, runner),
99 Effect.provide(
100 Layer.mergeAll(
101 Layer.succeed(HostProcessPlatform, platform),
102 Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),
103 Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),
104 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
105 ),
106 ),
107 );
108 return { service, fs, statePath, commands, control };
109});
110​
111it.layer(NodeServices.layer)("boot service install", (it) => {
112 it.effect("installs, reports current state, and uninstalls", () =>
113 Effect.gen(function* () {
114 const { service, fs, statePath, commands } = yield* makeHarness();
115 const plan = yield* service.install;
116​
117 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
118 protocol: SERVICE_LAUNCHER_PROTOCOL,
119 activeVersion: "1.2.3",
120 });
121 expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
122 expect((yield* service.status).current).toBe(true);
123 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
124 const pendingState = JSON.stringify({
125 protocol: SERVICE_LAUNCHER_PROTOCOL,
126 activeVersion: "1.2.3",
127 update: {
128 id: "u",
129 fromVersion: "1.2.3",
130 targetVersion: "1.2.4",
131 dbPath: "/tmp/state.sqlite",
132 status: "pending",
133 },
134 });
135 yield* fs.writeFileString(statePath, pendingState);
136 expect((yield* service.status).current).toBe(false);
137 expect(yield* service.uninstall).toBe(true);
138 expect((yield* service.status).installed).toBe(false);
139 expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
140 }),
141 );
142​
143 it.effect("copies the launcher from the prepared pinned runtime", () =>
144 Effect.gen(function* () {
145 const { service, fs } = yield* makeHarness("linux", true);
146 const plan = yield* service.install;
147​
148 expect(yield* fs.readFileString(plan.launcherPath)).toBe(
149 "export const source = 'pinned runtime';\n",
150 );
151 }),
152 );
153​
154 it.effect("restarts an installed service when repair fails", () =>
155 Effect.gen(function* () {
156 const { service, commands, control } = yield* makeHarness();
157 yield* service.install;
158 commands.length = 0;
159 control.failCommand = "systemctl --user daemon-reload";
160​
161 const error = yield* service.install.pipe(Effect.flip);
162 expect(error._tag).toBe("BootServiceCommandError");
163 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
164 "systemctl --user stop t3code.service",
165 "systemctl --user daemon-reload",
166 "systemctl --user restart t3code.service",
167 ]);
168 }),
169 );
170​
171 it.effect("restarts without overwriting a pending remote update", () =>
172 Effect.gen(function* () {
173 const { service, fs, statePath, commands } = yield* makeHarness();
174 yield* service.install;
175 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
176 const pendingState = JSON.stringify({
177 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
178 activeVersion: "1.2.3",
179 update: {
180 id: "remote-update",
181 fromVersion: "1.2.3",
182 targetVersion: "1.2.4",
183 status: "pending",
184 },
185 });
186 yield* fs.writeFileString(statePath, pendingState);
187 commands.length = 0;
188​
189 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
190 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
191 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
192 "systemctl --user stop t3code.service",
193 "systemctl --user restart t3code.service",
194 ]);
195 }),
196 );
197​
198 it.effect("fails closed off Linux", () =>
199 Effect.gen(function* () {
200 const { service } = yield* makeHarness("darwin");
201 expect((yield* service.status).supported).toBe(false);
202 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
203 }),
204 );
205});