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} 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=control-group");
35 expect(unit).not.toContain("versions/1.2.3");
36});
37
38const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
39 platform: NodeJS.Platform = "linux",
40 usePinnedLauncher = false,
41) {
42 const fs = yield* FileSystem.FileSystem;
43 const path = yield* Path.Path;
44 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
45 const baseDir = path.join(home, ".t3");
46 const sourceLauncher = path.join(home, "service-launcher.mjs");
47 const statePath = path.join(baseDir, "runtime", "service-state.json");
48 yield* fs.writeFileString(sourceLauncher, "export {};\n");
49 const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3");
50 yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
51 yield* fs.writeFileString(runtime.entryPath, "export {};\n");
52 yield* fs.writeFileString(
53 path.join(path.dirname(runtime.entryPath), "service-launcher.mjs"),
54 "export const source = 'pinned runtime';\n",
55 );
56 yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
57
58 const commands: string[] = [];
59 const control: { failCommand: string | undefined } = { failCommand: undefined };
60 const runner = ProcessRunner.ProcessRunner.of({
61 run: (input) =>
62 Effect.sync(() => {
63 const command = `${input.command} ${input.args.join(" ")}`;
64 commands.push(command);
65 return {
66 stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",
67 stderr: "",
68 code: ChildProcessSpawner.ExitCode(command === control.failCommand ? 1 : 0),
69 timedOut: false,
70 stdoutTruncated: false,
71 stderrTruncated: false,
72 };
73 }),
74 });
75 const service = yield* BootService.make({
76 baseDir,
77 logsDir: path.join(baseDir, "userdata", "logs"),
78 cliVersion: "1.2.3",
79 host: {
80 execPath: "/usr/bin/node",
81 ...(usePinnedLauncher ? {} : { launcherSourcePath: sourceLauncher }),
82 },
83 }).pipe(
84 Effect.provideService(ProcessRunner.ProcessRunner, runner),
85 Effect.provide(
86 Layer.mergeAll(
87 Layer.succeed(HostProcessPlatform, platform),
88 Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),
89 Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),
90 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
91 ),
92 ),
93 );
94 return { service, fs, statePath, commands, control };
95});
96
97it.layer(NodeServices.layer)("boot service install", (it) => {
98 it.effect("installs, reports current state, and uninstalls", () =>
99 Effect.gen(function* () {
100 const { service, fs, statePath, commands } = yield* makeHarness();
101 const plan = yield* service.install;
102
103 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
104 protocol: SERVICE_LAUNCHER_PROTOCOL,
105 activeVersion: "1.2.3",
106 });
107 expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
108 expect((yield* service.status).current).toBe(true);
109 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
110 const pendingState = JSON.stringify({
111 protocol: SERVICE_LAUNCHER_PROTOCOL,
112 activeVersion: "1.2.3",
113 update: {
114 id: "u",
115 fromVersion: "1.2.3",
116 targetVersion: "1.2.4",
117 dbPath: "/tmp/state.sqlite",
118 status: "pending",
119 },
120 });
121 yield* fs.writeFileString(statePath, pendingState);
122 expect((yield* service.status).current).toBe(false);
123 expect(yield* service.uninstall).toBe(true);
124 expect((yield* service.status).installed).toBe(false);
125 expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
126 }),
127 );
128
129 it.effect("copies the launcher from the prepared pinned runtime", () =>
130 Effect.gen(function* () {
131 const { service, fs } = yield* makeHarness("linux", true);
132 const plan = yield* service.install;
133
134 expect(yield* fs.readFileString(plan.launcherPath)).toBe(
135 "export const source = 'pinned runtime';\n",
136 );
137 }),
138 );
139
140 it.effect("restarts an installed service when repair fails", () =>
141 Effect.gen(function* () {
142 const { service, commands, control } = yield* makeHarness();
143 yield* service.install;
144 commands.length = 0;
145 control.failCommand = "systemctl --user daemon-reload";
146
147 const error = yield* service.install.pipe(Effect.flip);
148 expect(error._tag).toBe("BootServiceCommandError");
149 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
150 "systemctl --user stop t3code.service",
151 "systemctl --user daemon-reload",
152 "systemctl --user restart t3code.service",
153 ]);
154 }),
155 );
156
157 it.effect("restarts without overwriting a pending remote update", () =>
158 Effect.gen(function* () {
159 const { service, fs, statePath, commands } = yield* makeHarness();
160 yield* service.install;
161 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
162 const pendingState = JSON.stringify({
163 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
164 activeVersion: "1.2.3",
165 update: {
166 id: "remote-update",
167 fromVersion: "1.2.3",
168 targetVersion: "1.2.4",
169 status: "pending",
170 },
171 });
172 yield* fs.writeFileString(statePath, pendingState);
173 commands.length = 0;
174
175 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
176 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
177 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
178 "systemctl --user stop t3code.service",
179 "systemctl --user restart t3code.service",
180 ]);
181 }),
182 );
183
184 it.effect("fails closed off Linux", () =>
185 Effect.gen(function* () {
186 const { service } = yield* makeHarness("darwin");
187 expect((yield* service.status).supported).toBe(false);
188 expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
189 }),
190 );
191});