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(["install", "update"] as const)(
63 "%s refuses a downgrade before changing the service",
64 (command) =>
65 Effect.gen(function* () {
66 const fs = yield* FileSystem.FileSystem;
67 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
68 const { service, installOptions } = makeTestService(newerServiceStatus);
69 vi.spyOn(BootService, "layer").mockReturnValue(
70 Layer.succeed(BootService.BootService, service),
71 );
72
73 const error = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
74 command,
75 "--base-dir",
76 baseDir,
77 ]).pipe(
78 Effect.provideService(HostProcess.Environment, {}),
79 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
80 Effect.flip,
81 );
82
83 expect(error).toMatchObject({
84 _tag: "BootServiceDowngradeRefusedError",
85 installedVersion: "999.0.0",
86 targetVersion: packageJson.version,
87 });
88 expect(installOptions).toEqual([]);
89 }),
90 );
91
92 it.effect.each([
93 { label: "a new service", installed: false, env: "", expected: "T3CODE_LAN=false\n" },
94 // Services installed before T3CODE_LAN existed keep listening on the local network.
95 { label: "an older service", installed: true, env: "", expected: "" },
96 {
97 label: "a set host",
98 installed: false,
99 env: "T3CODE_HOST=::\n",
100 expected: "T3CODE_HOST=::\n",
101 },
102 ])("install keeps $label off the local network only when it is new", (input) =>
103 Effect.gen(function* () {
104 const fs = yield* FileSystem.FileSystem;
105 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
106 yield* fs.writeFileString(`${baseDir}/service.env`, input.env);
107 const { service } = makeTestService({
108 ...status,
109 installed: input.installed,
110 current: false,
111 });
112 vi.spyOn(BootService, "layer").mockReturnValue(
113 Layer.succeed(BootService.BootService, service),
114 );
115
116 yield* Command.runWith(serviceCommand, { version: packageJson.version })([
117 "install",
118 "--base-dir",
119 baseDir,
120 ]).pipe(
121 Effect.provideService(HostProcess.Environment, {}),
122 Effect.provide(
123 Layer.mergeAll(
124 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
125 Layer.fresh(TestConsole.layer),
126 ),
127 ),
128 );
129 expect(yield* fs.readFileString(`${baseDir}/service.env`)).toBe(input.expected);
130 }),
131 );
132
133 it.effect("protect refuses root before creating any T3 directories", () =>
134 Effect.gen(function* () {
135 const fs = yield* FileSystem.FileSystem;
136 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
137 const baseDir = `${parent}/t3`;
138 vi.spyOn(BootService, "layer").mockReturnValue(
139 Layer.succeed(BootService.BootService, makeTestService(status).service),
140 );
141
142 const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
143 "protect",
144 "--base-dir",
145 baseDir,
146 ]).pipe(
147 Effect.andThen(TestConsole.logLines),
148 Effect.map((lines) => lines.join("\n")),
149 Effect.provideService(HostProcess.Environment, {}),
150 Effect.provideService(HostProcess.Platform, "linux"),
151 Effect.provideService(HostProcess.UserId, 0),
152 Effect.provide(
153 Layer.mergeAll(
154 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
155 Layer.fresh(TestConsole.layer),
156 ),
157 ),
158 );
159 expect(output).toContain("without sudo");
160 expect(yield* fs.exists(baseDir)).toBe(false);
161 }),
162 );
163
164 // regression: #13239 a stale nvm-installed CLI reported "already using" its own version
165 it.effect.each(["install", "update"] as const)(
166 "%s names the CLI that found nothing to change",
167 (command) =>
168 Effect.gen(function* () {
169 const fs = yield* FileSystem.FileSystem;
170 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
171 const { service, installOptions } = makeTestService(status);
172 vi.spyOn(BootService, "layer").mockReturnValue(
173 Layer.succeed(BootService.BootService, service),
174 );
175 const node = "/home/me/.nvm/versions/node/v26.8.2/bin/node";
176 const script = "/home/me/.nvm/versions/node/v26.8.2/lib/node_modules/t3/dist/bin.mjs";
177
178 const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
179 command,
180 "--base-dir",
181 baseDir,
182 ]).pipe(
183 Effect.andThen(TestConsole.logLines),
184 Effect.map((lines) => lines.join("\n")),
185 Effect.provideService(HostProcess.Environment, {}),
186 Effect.provideService(HostProcess.IsExecutable, false),
187 Effect.provideService(HostProcess.ExecutablePath, node),
188 Effect.provideService(HostProcess.Arguments, [node, script, "service", command]),
189 Effect.provide(
190 Layer.mergeAll(
191 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
192 Layer.fresh(TestConsole.layer),
193 ),
194 ),
195 );
196 expect(output).toContain(`t3@${packageJson.version}`);
197 expect(output).toContain(script);
198 expect(installOptions).toEqual([]);
199 }),
200 );
201
202 it.effect.each([
203 { label: "this home's service", otherHome: false, unreadable: false, removed: [true] },
204 { label: "another home's service", otherHome: true, unreadable: false, removed: [] },
205 { label: "an unreadable service", otherHome: false, unreadable: true, removed: [true] },
206 ])("uninstall removes only $label", (input) =>
207 Effect.gen(function* () {
208 const fs = yield* FileSystem.FileSystem;
209 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
210 const { service, uninstalls } = makeTestService({
211 ...status,
212 installedBaseDir: input.otherHome ? "/home/me/.t3" : baseDir,
213 });
214 vi.spyOn(BootService, "layer").mockReturnValue(
215 Layer.succeed(
216 BootService.BootService,
217 input.unreadable
218 ? {
219 ...service,
220 status: Effect.fail(new BootService.BootServiceInstallError({ cause: "EACCES" })),
221 }
222 : service,
223 ),
224 );
225
226 const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
227 "uninstall",
228 "--base-dir",
229 baseDir,
230 ]).pipe(
231 Effect.andThen(TestConsole.logLines),
232 Effect.map((lines) => lines.join("\n")),
233 Effect.provideService(HostProcess.Environment, {}),
234 Effect.provide(
235 Layer.mergeAll(
236 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
237 Layer.fresh(TestConsole.layer),
238 ),
239 ),
240 );
241 expect(uninstalls).toEqual(input.removed);
242 expect(output).toContain(input.otherHome ? "another T3 home" : "Removed");
243 }),
244 );
245});