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 { serviceCommand } from "./service.ts";
16
17afterEach(() => vi.restoreAllMocks());
18
19const status = {
20 supported: true,
21 installed: true,
22 current: true,
23 unitPath: "/home/me/.config/systemd/user/t3code.service",
24 logPath: "/home/me/.t3/userdata/logs/boot-service.log",
25} as const;
26
27const newerServiceStatus = { ...status, current: false, installedVersion: "999.0.0" };
28
29function makeTestService(
30 serviceStatus: BootService.BootServiceStatus,
31 restartOutcome: "restarted" | "queued" = "restarted",
32) {
33 const installOptions: Array<Parameters<BootService.BootService["Service"]["install"]>[0]> = [];
34 const restarts: Array<true> = [];
35 const uninstalls: Array<true> = [];
36 const service = BootService.BootService.of({
37 status: Effect.succeed(serviceStatus),
38 withStopped: (operation) => operation,
39 restart: Effect.sync(() => {
40 restarts.push(true);
41 return serviceStatus.installed ? restartOutcome : "skipped";
42 }),
43 install: (options) =>
44 Effect.sync(() => {
45 installOptions.push(options);
46 return {
47 program: ["/test/t3/runtime/versions/1.0.0/t3", "__service-launcher"],
48 baseDir: "/test/t3",
49 unitPath: serviceStatus.unitPath,
50 logPath: serviceStatus.logPath,
51 };
52 }),
53 uninstall: Effect.sync(() => {
54 uninstalls.push(true);
55 return serviceStatus.installed;
56 }),
57 });
58 return { service, installOptions, restarts, uninstalls };
59}
60
61it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands", (it) => {
62 it.effect.each(
63 (["install", "update"] as const).flatMap((command) => [
64 {
65 command,
66 label: "a downgrade",
67 status: newerServiceStatus,
68 error: {
69 _tag: "BootServiceDowngradeRefusedError",
70 installedVersion: "999.0.0",
71 targetVersion: packageJson.version,
72 },
73 },
74 // This home's newer state must not ask for --allow-downgrade first.
75 {
76 command,
77 label: "another home's service",
78 status: { ...newerServiceStatus, otherBaseDir: "/srv/t3" },
79 error: { _tag: "BootServiceOtherBaseDirError", installedBaseDir: "/srv/t3" },
80 },
81 ]),
82 )(
83 "$command refuses $label before changing the service",
84 ({ command, status: serviceStatus, error: expected }) =>
85 Effect.gen(function* () {
86 const fs = yield* FileSystem.FileSystem;
87 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
88 const { service, installOptions } = makeTestService(serviceStatus);
89 vi.spyOn(BootService, "layer").mockReturnValue(
90 Layer.succeed(BootService.BootService, service),
91 );
92
93 const error = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
94 command,
95 "--base-dir",
96 baseDir,
97 ]).pipe(
98 Effect.provideService(HostProcess.Environment, {}),
99 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
100 Effect.flip,
101 );
102
103 expect(error).toMatchObject(expected);
104 expect(installOptions).toEqual([]);
105 }),
106 );
107
108 it.effect.each([
109 { label: "a new service", installed: false, env: "", expected: "T3CODE_LAN=false\n" },
110 // Services installed before T3CODE_LAN existed keep listening on the local network.
111 { label: "an older service", installed: true, env: "", expected: "" },
112 {
113 label: "a set host",
114 installed: false,
115 env: "T3CODE_HOST=::\n",
116 expected: "T3CODE_HOST=::\n",
117 },
118 ])("install keeps $label off the local network only when it is new", (input) =>
119 Effect.gen(function* () {
120 const fs = yield* FileSystem.FileSystem;
121 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
122 yield* fs.writeFileString(`${baseDir}/service.env`, input.env);
123 const { service } = makeTestService({
124 ...status,
125 installed: input.installed,
126 current: false,
127 });
128 vi.spyOn(BootService, "layer").mockReturnValue(
129 Layer.succeed(BootService.BootService, service),
130 );
131
132 yield* Command.runWith(serviceCommand, { version: packageJson.version })([
133 "install",
134 "--base-dir",
135 baseDir,
136 ]).pipe(
137 Effect.provideService(HostProcess.Environment, {}),
138 Effect.provide(
139 Layer.mergeAll(
140 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
141 Layer.fresh(TestConsole.layer),
142 ),
143 ),
144 );
145 expect(yield* fs.readFileString(`${baseDir}/service.env`)).toBe(input.expected);
146 }),
147 );
148
149 it.effect("protect refuses root before creating any T3 directories", () =>
150 Effect.gen(function* () {
151 const fs = yield* FileSystem.FileSystem;
152 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
153 const baseDir = `${parent}/t3`;
154 vi.spyOn(BootService, "layer").mockReturnValue(
155 Layer.succeed(BootService.BootService, makeTestService(status).service),
156 );
157
158 const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
159 "protect",
160 "--base-dir",
161 baseDir,
162 ]).pipe(
163 Effect.andThen(TestConsole.logLines),
164 Effect.map((lines) => lines.join("\n")),
165 Effect.provideService(HostProcess.Environment, {}),
166 Effect.provideService(HostProcess.Platform, "linux"),
167 Effect.provideService(HostProcess.UserId, 0),
168 Effect.provide(
169 Layer.mergeAll(
170 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
171 Layer.fresh(TestConsole.layer),
172 ),
173 ),
174 );
175 expect(output).toContain("without sudo");
176 expect(yield* fs.exists(baseDir)).toBe(false);
177 }),
178 );
179
180 // regression: #13239 a stale nvm-installed CLI reported "already using" its own version
181 it.effect.each(["install", "update"] as const)(
182 "%s names the CLI that found nothing to change",
183 (command) =>
184 Effect.gen(function* () {
185 const fs = yield* FileSystem.FileSystem;
186 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
187 const { service, installOptions } = makeTestService(status);
188 vi.spyOn(BootService, "layer").mockReturnValue(
189 Layer.succeed(BootService.BootService, service),
190 );
191 const node = "/home/me/.nvm/versions/node/v26.8.2/bin/node";
192 const script = "/home/me/.nvm/versions/node/v26.8.2/lib/node_modules/t3/dist/bin.mjs";
193
194 const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
195 command,
196 "--base-dir",
197 baseDir,
198 ]).pipe(
199 Effect.andThen(TestConsole.logLines),
200 Effect.map((lines) => lines.join("\n")),
201 Effect.provideService(HostProcess.Environment, {}),
202 Effect.provideService(HostProcess.IsExecutable, false),
203 Effect.provideService(HostProcess.ExecutablePath, node),
204 Effect.provideService(HostProcess.Arguments, [node, script, "service", command]),
205 Effect.provide(
206 Layer.mergeAll(
207 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
208 Layer.fresh(TestConsole.layer),
209 ),
210 ),
211 );
212 expect(output).toContain(`t3@${packageJson.version}`);
213 expect(output).toContain(script);
214 expect(installOptions).toEqual([]);
215 }),
216 );
217
218 it.effect.each([
219 { label: "this home's service", otherHome: false, unreadable: false, removed: [true] },
220 { label: "another home's service", otherHome: true, unreadable: false, removed: [] },
221 { label: "an unreadable service", otherHome: false, unreadable: true, removed: [true] },
222 ])("uninstall removes only $label", (input) =>
223 Effect.gen(function* () {
224 const fs = yield* FileSystem.FileSystem;
225 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
226 const { service, uninstalls } = makeTestService({
227 ...status,
228 installedBaseDir: input.otherHome ? "/home/me/.t3" : baseDir,
229 });
230 vi.spyOn(BootService, "layer").mockReturnValue(
231 Layer.succeed(
232 BootService.BootService,
233 input.unreadable
234 ? {
235 ...service,
236 status: Effect.fail(new BootService.BootServiceInstallError({ cause: "EACCES" })),
237 }
238 : service,
239 ),
240 );
241
242 const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
243 "uninstall",
244 "--base-dir",
245 baseDir,
246 ]).pipe(
247 Effect.andThen(TestConsole.logLines),
248 Effect.map((lines) => lines.join("\n")),
249 Effect.provideService(HostProcess.Environment, {}),
250 Effect.provide(
251 Layer.mergeAll(
252 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
253 Layer.fresh(TestConsole.layer),
254 ),
255 ),
256 );
257 expect(uninstalls).toEqual(input.removed);
258 expect(output).toContain(input.otherHome ? "--base-dir '/home/me/.t3'" : "Removed");
259 }),
260 );
261});