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

bootService.test.ts

203 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 };
85 }),
86 });
87 const service = yield* BootService.make({
88 baseDir,
89 logsDir: path.join(baseDir, "userdata", "logs"),
90 cliVersion: "1.2.3",
91 host: {
92 execPath: "/usr/bin/node",
93 ...(usePinnedLauncher ? {} : { launcherSourcePath: sourceLauncher }),
94 },
95 }).pipe(
96 Effect.provideService(ProcessRunner.ProcessRunner, runner),
97 Effect.provide(
98 Layer.mergeAll(
99 Layer.succeed(HostProcessPlatform, platform),
100 Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),
101 Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),
102 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
103 ),
104 ),
105 );
106 return { service, fs, statePath, commands, control };
107});
108​
109it.layer(NodeServices.layer)("boot service install", (it) => {
110 it.effect("installs, reports current state, and uninstalls", () =>
111 Effect.gen(function* () {
112 const { service, fs, statePath, commands } = yield* makeHarness();
113 const plan = yield* service.install;
114​
115 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
116 protocol: SERVICE_LAUNCHER_PROTOCOL,
117 activeVersion: "1.2.3",
118 });
119 expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
120 expect((yield* service.status).current).toBe(true);
121 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
122 const pendingState = JSON.stringify({
123 protocol: SERVICE_LAUNCHER_PROTOCOL,
124 activeVersion: "1.2.3",
125 update: {
126 id: "u",
127 fromVersion: "1.2.3",
128 targetVersion: "1.2.4",
129 dbPath: "/tmp/state.sqlite",
130 status: "pending",
131 },
132 });
133 yield* fs.writeFileString(statePath, pendingState);
134 expect((yield* service.status).current).toBe(false);
135 expect(yield* service.uninstall).toBe(true);
136 expect((yield* service.status).installed).toBe(false);
137 expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
138 }),
139 );
140​
141 it.effect("copies the launcher from the prepared pinned runtime", () =>
142 Effect.gen(function* () {
143 const { service, fs } = yield* makeHarness("linux", true);
144 const plan = yield* service.install;
145​
146 expect(yield* fs.readFileString(plan.launcherPath)).toBe(
147 "export const source = 'pinned runtime';\n",
148 );
149 }),
150 );
151​
152 it.effect("restarts an installed service when repair fails", () =>
153 Effect.gen(function* () {
154 const { service, commands, control } = yield* makeHarness();
155 yield* service.install;
156 commands.length = 0;
157 control.failCommand = "systemctl --user daemon-reload";
158​
159 const error = yield* service.install.pipe(Effect.flip);
160 expect(error._tag).toBe("BootServiceCommandError");
161 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
162 "systemctl --user stop t3code.service",
163 "systemctl --user daemon-reload",
164 "systemctl --user restart t3code.service",
165 ]);
166 }),
167 );
168​
169 it.effect("restarts without overwriting a pending remote update", () =>
170 Effect.gen(function* () {
171 const { service, fs, statePath, commands } = yield* makeHarness();
172 yield* service.install;
173 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
174 const pendingState = JSON.stringify({
175 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
176 activeVersion: "1.2.3",
177 update: {
178 id: "remote-update",
179 fromVersion: "1.2.3",
180 targetVersion: "1.2.4",
181 status: "pending",
182 },
183 });
184 yield* fs.writeFileString(statePath, pendingState);
185 commands.length = 0;
186​
187 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
188 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
189 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
190 "systemctl --user stop t3code.service",
191 "systemctl --user restart t3code.service",
192 ]);
193 }),
194 );
195​
196 it.effect("fails closed off Linux", () =>
197 Effect.gen(function* () {
198 const { service } = yield* makeHarness("darwin");
199 expect((yield* service.status).supported).toBe(false);
200 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
201 }),
202 );
203});