Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as NetService from "@t3tools/shared/Net";
5import * as ConfigProvider from "effect/ConfigProvider";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as TestConsole from "effect/testing/TestConsole";
10import { Command } from "effect/cli";
11import { afterEach, vi } from "vite-plus/test";
12
13import packageJson from "../../package.json" with { type: "json" };
14import * as BootService from "../cloud/bootService.ts";
15import { resolveHostCliCommand } from "./invocation.ts";
16import { serviceCommand } from "./service.ts";
17
18afterEach(() => vi.restoreAllMocks());
19
20const status = {
21 supported: true,
22 installed: true,
23 current: true,
24 unitPath: "/home/me/.config/systemd/user/t3code.service",
25 logPath: "/home/me/.t3/userdata/logs/boot-service.log",
26} as const;
27
28const newerServiceStatus = { ...status, current: false, installedVersion: "999.0.0" };
29
30function makeTestService(
31 serviceStatus: BootService.BootServiceStatus,
32 restartOutcome: "restarted" | "queued" | "skipped" = "restarted",
33) {
34 const installOptions: Array<Parameters<BootService.BootService["Service"]["install"]>[0]> = [];
35 const restarts: Array<true> = [];
36 const uninstalls: Array<true> = [];
37 const service = BootService.BootService.of({
38 status: Effect.succeed(serviceStatus),
39 withStopped: (operation) => operation,
40 restart: Effect.sync(() => {
41 restarts.push(true);
42 return serviceStatus.installed ? restartOutcome : "skipped";
43 }),
44 install: (options) =>
45 Effect.sync(() => {
46 installOptions.push(options);
47 return {
48 program: ["/test/t3/runtime/versions/1.0.0/t3", "__service-launcher"],
49 baseDir: "/test/t3",
50 unitPath: serviceStatus.unitPath,
51 logPath: serviceStatus.logPath,
52 };
53 }),
54 uninstall: Effect.sync(() => {
55 uninstalls.push(true);
56 return serviceStatus.installed;
57 }),
58 });
59 return { service, installOptions, restarts, uninstalls };
60}
61
62it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands", (it) => {
63 it.effect.each(
64 (["install", "update"] as const).flatMap((command) => [
65 {
66 command,
67 label: "a downgrade",
68 status: newerServiceStatus,
69 error: {
70 _tag: "BootServiceDowngradeRefusedError",
71 installedVersion: "999.0.0",
72 targetVersion: packageJson.version,
73 },
74 },
75 // This home's newer state must not ask for --allow-downgrade first.
76 {
77 command,
78 label: "another home's service",
79 status: { ...newerServiceStatus, otherBaseDir: "/srv/t3" },
80 error: { _tag: "BootServiceOtherBaseDirError", installedBaseDir: "/srv/t3" },
81 },
82 ]),
83 )(
84 "$command refuses $label before changing the service",
85 ({ command, status: serviceStatus, error: expected }) =>
86 Effect.gen(function* () {
87 const fs = yield* FileSystem.FileSystem;
88 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
89 const { service, installOptions } = makeTestService(serviceStatus);
90 vi.spyOn(BootService, "layer").mockReturnValue(
91 Layer.succeed(BootService.BootService, service),
92 );
93
94 const error = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
95 command,
96 "--base-dir",
97 baseDir,
98 ]).pipe(
99 Effect.provideService(HostProcess.Environment, {}),
100 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
101 Effect.flip,
102 );
103
104 expect(error).toMatchObject(expected);
105 expect(installOptions).toEqual([]);
106 }),
107 );
108
109 it.effect.each([
110 { label: "a new service", installed: false, env: "", expected: "T3CODE_LAN=false\n" },
111 // Services installed before T3CODE_LAN existed keep listening on the local network.
112 { label: "an older service", installed: true, env: "", expected: "" },
113 {
114 label: "a set host",
115 installed: false,
116 env: "T3CODE_HOST=::\n",
117 expected: "T3CODE_HOST=::\n",
118 },
119 {
120 label: "a quoted multiline value",
121 installed: false,
122 env: 'CUSTOM="first\nT3CODE_LAN=example\nlast"\n',
123 expected: 'CUSTOM="first\nT3CODE_LAN=example\nlast"\nT3CODE_LAN=false\n',
124 },
125 ])("install keeps $label off the local network only when it is new", (input) =>
126 Effect.gen(function* () {
127 const fs = yield* FileSystem.FileSystem;
128 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
129 yield* fs.writeFileString(`${baseDir}/service.env`, input.env);
130 const { service } = makeTestService({
131 ...status,
132 installed: input.installed,
133 current: false,
134 });
135 vi.spyOn(BootService, "layer").mockReturnValue(
136 Layer.succeed(BootService.BootService, service),
137 );
138
139 const [lines, up] = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
140 "install",
141 "--base-dir",
142 baseDir,
143 ]).pipe(
144 Effect.andThen(
145 Effect.all([TestConsole.logLines, resolveHostCliCommand("up", ["--base-dir", baseDir])]),
146 ),
147 Effect.provideService(HostProcess.Environment, {}),
148 Effect.provide(
149 Layer.mergeAll(
150 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
151 Layer.fresh(TestConsole.layer),
152 ),
153 ),
154 );
155 expect(yield* fs.readFileString(`${baseDir}/service.env`)).toBe(input.expected);
156 expect(lines.map(String).filter((line) => line.includes("other devices"))).toEqual(
157 input.installed ? [] : [`Run \`${up.command}\` to choose how your other devices reach it.`],
158 );
159 }),
160 );
161
162 it.effect("restart says a service whose home it cannot determine was not restarted", () =>
163 Effect.gen(function* () {
164 const fs = yield* FileSystem.FileSystem;
165 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
166 vi.spyOn(BootService, "layer").mockReturnValue(
167 Layer.succeed(
168 BootService.BootService,
169 makeTestService({ ...status, current: false }, "skipped").service,
170 ),
171 );
172
173 const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
174 "restart",
175 "--base-dir",
176 baseDir,
177 ]).pipe(
178 Effect.andThen(TestConsole.logLines),
179 Effect.map((lines) => lines.join("\n")),
180 Effect.provideService(HostProcess.Environment, {}),
181 Effect.provide(
182 Layer.mergeAll(
183 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
184 Layer.fresh(TestConsole.layer),
185 ),
186 ),
187 );
188 expect(output).toContain("T3 home could not be determined, so it was not restarted");
189 expect(output).toContain(status.unitPath);
190 }),
191 );
192
193 it.effect("protect refuses root before creating any T3 directories", () =>
194 Effect.gen(function* () {
195 const fs = yield* FileSystem.FileSystem;
196 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
197 const baseDir = `${parent}/t3`;
198 vi.spyOn(BootService, "layer").mockReturnValue(
199 Layer.succeed(BootService.BootService, makeTestService(status).service),
200 );
201
202 const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
203 "protect",
204 "--base-dir",
205 baseDir,
206 ]).pipe(
207 Effect.andThen(TestConsole.logLines),
208 Effect.map((lines) => lines.join("\n")),
209 Effect.provideService(HostProcess.Environment, {}),
210 Effect.provideService(HostProcess.Platform, "linux"),
211 Effect.provideService(HostProcess.UserId, 0),
212 Effect.provide(
213 Layer.mergeAll(
214 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
215 Layer.fresh(TestConsole.layer),
216 ),
217 ),
218 );
219 expect(output).toContain("without sudo");
220 expect(yield* fs.exists(baseDir)).toBe(false);
221 }),
222 );
223
224 // regression: #13239 a stale nvm-installed CLI reported "already using" its own version
225 it.effect.each(["install", "update"] as const)(
226 "%s names the CLI that found nothing to change",
227 (command) =>
228 Effect.gen(function* () {
229 const fs = yield* FileSystem.FileSystem;
230 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
231 const { service, installOptions } = makeTestService(status);
232 vi.spyOn(BootService, "layer").mockReturnValue(
233 Layer.succeed(BootService.BootService, service),
234 );
235 const node = "/home/me/.nvm/versions/node/v26.8.2/bin/node";
236 const script = "/home/me/.nvm/versions/node/v26.8.2/lib/node_modules/t3/dist/bin.mjs";
237
238 const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
239 command,
240 "--base-dir",
241 baseDir,
242 ]).pipe(
243 Effect.andThen(TestConsole.logLines),
244 Effect.map((lines) => lines.join("\n")),
245 Effect.provideService(HostProcess.Environment, {}),
246 Effect.provideService(HostProcess.IsExecutable, false),
247 Effect.provideService(HostProcess.ExecutablePath, node),
248 Effect.provideService(HostProcess.Arguments, [node, script, "service", command]),
249 Effect.provide(
250 Layer.mergeAll(
251 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
252 Layer.fresh(TestConsole.layer),
253 ),
254 ),
255 );
256 expect(output).toContain(`t3@${packageJson.version}`);
257 expect(output).toContain(script);
258 expect(installOptions).toEqual([]);
259 }),
260 );
261
262 it.effect.each([
263 {
264 label: "a missing service",
265 status: { ...status, installed: false },
266 hint: "service install",
267 args: [],
268 },
269 { label: "a newer service", status: newerServiceStatus, hint: "update", args: ["999.0.0"] },
270 {
271 label: "a stopped service",
272 status: { ...status, problems: ["service-stopped"] as const },
273 hint: "service install",
274 args: [],
275 },
276 {
277 label: "a restart-pending service",
278 status: { ...status, problems: ["restart-pending"] as const },
279 hint: "service restart",
280 args: [],
281 },
282 ])("status of $label names its next step with --base-dir", (input) =>
283 Effect.gen(function* () {
284 const fs = yield* FileSystem.FileSystem;
285 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
286 vi.spyOn(BootService, "layer").mockReturnValue(
287 Layer.succeed(BootService.BootService, makeTestService(input.status).service),
288 );
289
290 const [lines, next] = yield* Command.runWith(serviceCommand, {
291 version: packageJson.version,
292 })(["status", "--base-dir", baseDir]).pipe(
293 Effect.andThen(
294 Effect.all([
295 TestConsole.logLines,
296 resolveHostCliCommand(input.hint, ["--base-dir", baseDir, ...input.args]),
297 ]),
298 ),
299 Effect.provideService(HostProcess.Environment, {}),
300 Effect.provide(
301 Layer.mergeAll(
302 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
303 Layer.fresh(TestConsole.layer),
304 ),
305 ),
306 );
307 expect(lines.join("\n")).toContain(`\`${next.command}\``);
308 }),
309 );
310
311 it.effect.each([
312 { label: "this home's service", otherHome: false, unreadable: false, removed: [true] },
313 { label: "another home's service", otherHome: true, unreadable: false, removed: [] },
314 { label: "an unreadable service", otherHome: false, unreadable: true, removed: [true] },
315 ])("uninstall removes only $label", (input) =>
316 Effect.gen(function* () {
317 const fs = yield* FileSystem.FileSystem;
318 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
319 const { service, uninstalls } = makeTestService({
320 ...status,
321 installedBaseDir: input.otherHome ? "/home/me/.t3" : baseDir,
322 ...(input.otherHome ? { otherBaseDir: "/home/me/.t3" } : {}),
323 });
324 vi.spyOn(BootService, "layer").mockReturnValue(
325 Layer.succeed(
326 BootService.BootService,
327 input.unreadable
328 ? {
329 ...service,
330 status: Effect.fail(new BootService.BootServiceInstallError({ cause: "EACCES" })),
331 }
332 : service,
333 ),
334 );
335
336 const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
337 "uninstall",
338 "--base-dir",
339 baseDir,
340 ]).pipe(
341 Effect.andThen(TestConsole.logLines),
342 Effect.map((lines) => lines.join("\n")),
343 Effect.provideService(HostProcess.Environment, {}),
344 Effect.provide(
345 Layer.mergeAll(
346 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
347 Layer.fresh(TestConsole.layer),
348 ),
349 ),
350 );
351 expect(uninstalls).toEqual(input.removed);
352 expect(output).toContain(input.otherHome ? "--base-dir '/home/me/.t3'" : "Removed");
353 }),
354 );
355});