Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import * as FileSystem from "effect/FileSystem";
3import * as Path from "effect/Path";
4import * as Logger from "effect/Logger";
5import * as PlatformError from "effect/PlatformError";
6import { assert, expect, it } from "@effect/vitest";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as Effect from "effect/Effect";
9import * as Deferred from "effect/Deferred";
10import * as Fiber from "effect/Fiber";
11
12import {
13 SERVICE_LAUNCHER_CONTEXT_ENV,
14 SERVICE_LAUNCHER_PROTOCOL,
15 type ServiceLauncherChildMessage,
16 type ServiceLauncherParentMessage,
17} from "./serviceProtocol.ts";
18import { posixLauncherScript } from "./pinnedRuntime.ts";
19import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
20
21class FakeLauncherProcess {
22 readonly connected: boolean;
23 readonly env: Record<string, string | undefined>;
24 readonly sent: ServiceLauncherChildMessage[] = [];
25 readonly #listeners = new Map<string, Set<(...args: ReadonlyArray<unknown>) => void>>();
26
27 constructor(context: unknown, connected = true) {
28 this.connected = connected;
29 this.env = { [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) };
30 }
31
32 send = (message: ServiceLauncherChildMessage, callback?: (error: Error | null) => void) => {
33 this.sent.push(message);
34 callback?.(null);
35 return true;
36 };
37
38 on = (event: "message" | "disconnect", listener: (...args: ReadonlyArray<unknown>) => void) => {
39 const listeners = this.#listeners.get(event) ?? new Set();
40 listeners.add(listener);
41 this.#listeners.set(event, listeners);
42 };
43
44 off = (event: "message" | "disconnect", listener: (...args: ReadonlyArray<unknown>) => void) => {
45 this.#listeners.get(event)?.delete(listener);
46 };
47
48 emit(message: ServiceLauncherParentMessage) {
49 for (const listener of this.#listeners.get("message") ?? []) listener(message);
50 }
51}
52
53const makeClient = (host: FakeLauncherProcess, currentVersion: string) =>
54 ServiceLauncherClient.make({ currentVersion }).pipe(
55 Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, host),
56 Effect.provideService(HostProcess.Environment, host.env),
57 Effect.provide(NodeServices.layer),
58 );
59
60// regression: #34502 a remote update never replaces the launcher, so an installed one stays protocol 3
61it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])(
62 "waits for a protocol-%i launcher to durably commit the trial update ID, then moves owned launchers",
63 (protocol) =>
64 Effect.gen(function* () {
65 const fs = yield* FileSystem.FileSystem;
66 const path = yield* Path.Path;
67 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-trial-" });
68 const baseDir = path.join(root, ".t3");
69 const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
70 const installed = path.join(root, ".local/bin/t3");
71 for (const file of [exe("1.0.0"), exe("1.1.0")]) {
72 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
73 yield* fs.writeFileString(file, "");
74 }
75 yield* fs.makeDirectory(path.dirname(installed), { recursive: true });
76 yield* fs.symlink(exe("1.0.0"), installed);
77
78 const pending = {
79 id: "update-1",
80 fromVersion: "1.0.0",
81 targetVersion: "1.1.0",
82 dbPath: "/tmp/state.sqlite",
83 status: "pending" as const,
84 };
85 const host = new FakeLauncherProcess({ protocol, childVersion: "1.1.0", update: pending });
86 host.env["HOME"] = root;
87 // The launcher reloads the user manager after commit, so oomd's watch must already be mirrored.
88 const bin = path.join(root, "bin");
89 const calls = path.join(root, "systemctl-calls");
90 yield* fs.makeDirectory(bin);
91 yield* fs.writeFileString(
92 path.join(bin, "systemctl"),
93 [
94 "#!/bin/sh",
95 `echo "$*" >>'${calls}'`,
96 'case "$*" in',
97 " *ControlGroup*) echo /user.slice/user-1000.slice/user@1000.service ;;",
98 " *ManagedOOMMemoryPressureLimit*) echo 0 ;;",
99 " *ManagedOOMMemoryPressure\\ *) echo kill ;;",
100 "esac",
101 "",
102 ].join("\n"),
103 );
104 yield* fs.chmod(path.join(bin, "systemctl"), 0o755);
105 host.env["PATH"] = `${bin}:/usr/bin:/bin`;
106 const sentPrepared = yield* Deferred.make<void>();
107 const send = host.send;
108 host.send = (message, callback) => {
109 Deferred.doneUnsafe(sentPrepared, Effect.void);
110 return send(message, callback);
111 };
112 const client = yield* makeClient(host, "1.1.0").pipe(
113 Effect.provideService(HostProcess.Platform, "linux"),
114 );
115 const prepared = yield* Effect.forkChild(client.prepareTrial({ baseDir }), {
116 startImmediately: true,
117 });
118 yield* Deferred.await(sentPrepared);
119 // Nothing runs systemctl after "prepared", so the log is what ran before it.
120 expect(yield* fs.readFileString(calls)).toContain(
121 "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill",
122 );
123 expect(host.sent).toEqual([{ type: "prepared", updateId: "update-1" }]);
124 assert.equal(yield* fs.readLink(installed), exe("1.0.0"));
125
126 const committed = {
127 id: pending.id,
128 fromVersion: pending.fromVersion,
129 targetVersion: pending.targetVersion,
130 status: "committed" as const,
131 };
132 host.emit({ type: "committed", updateId: committed.id });
133 expect(yield* Fiber.join(prepared)).toEqual(committed);
134 assert.equal(yield* fs.readFileString(installed), posixLauncherScript(exe("1.1.0")));
135
136 // A later start replays the stored outcome; user pins made since then stay put.
137 yield* fs.remove(installed);
138 yield* fs.symlink(exe("1.0.0"), installed);
139 const restarted = new FakeLauncherProcess({
140 protocol,
141 childVersion: "1.1.0",
142 update: committed,
143 });
144 restarted.env["HOME"] = root;
145 const restartedClient = yield* makeClient(restarted, "1.1.0");
146 expect(yield* restartedClient.prepareTrial({ baseDir })).toEqual(committed);
147 assert.equal(yield* fs.readLink(installed), exe("1.0.0"));
148 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
149);
150
151it.effect("returns the launcher-generated ID only after update acceptance", () =>
152 Effect.gen(function* () {
153 const host = new FakeLauncherProcess({
154 protocol: SERVICE_LAUNCHER_PROTOCOL,
155 childVersion: "1.0.0",
156 });
157 const client = yield* makeClient(host, "1.0.0");
158 const requested = yield* Effect.forkChild(
159 client.requestUpdate({ targetVersion: "1.1.0", dbPath: "/tmp/state.sqlite" }),
160 { startImmediately: true },
161 );
162 yield* Effect.yieldNow;
163 host.emit({
164 type: "update-accepted",
165 updateId: "launcher-id",
166 });
167 expect(yield* Fiber.join(requested)).toBe("launcher-id");
168 }),
169);
170
171it.effect("preserves a launcher rejection as a distinct error", () =>
172 Effect.gen(function* () {
173 const host = new FakeLauncherProcess({
174 protocol: SERVICE_LAUNCHER_PROTOCOL,
175 childVersion: "1.0.0",
176 });
177 const client = yield* makeClient(host, "1.0.0");
178 const requested = yield* Effect.forkChild(
179 client.requestUpdate({ targetVersion: "1.1.0", dbPath: "/tmp/state.sqlite" }),
180 { startImmediately: true },
181 );
182 yield* Effect.yieldNow;
183 host.emit({ type: "update-rejected", reason: "requires local update" });
184 expect(yield* Fiber.join(requested).pipe(Effect.flip)).toMatchObject({
185 _tag: "ServiceLauncherRejectedError",
186 targetVersion: "1.1.0",
187 reason: "requires local update",
188 });
189 }),
190);
191
192it.effect("stops the server when the launcher asks over IPC", () =>
193 Effect.gen(function* () {
194 const host = new FakeLauncherProcess({
195 protocol: SERVICE_LAUNCHER_PROTOCOL,
196 childVersion: "1.0.0",
197 });
198 const stopped = yield* Effect.forkChild(
199 ServiceLauncherClient.awaitServiceLauncherStop({ currentVersion: "1.0.0" }).pipe(
200 Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, host),
201 Effect.provideService(HostProcess.Environment, host.env),
202 ),
203 { startImmediately: true },
204 );
205 host.emit({ type: "stop" });
206 yield* Fiber.join(stopped);
207 }),
208);
209
210it.effect("rejects contradictory trial context instead of leaving activation closed", () =>
211 Effect.gen(function* () {
212 const host = new FakeLauncherProcess({
213 protocol: SERVICE_LAUNCHER_PROTOCOL,
214 childVersion: "1.1.0",
215 update: {
216 id: "update-1",
217 fromVersion: "1.0.0",
218 targetVersion: "1.2.0",
219 dbPath: "/tmp/state.sqlite",
220 status: "pending",
221 },
222 });
223 const error = yield* makeClient(host, "1.1.0").pipe(Effect.flip);
224 expect(error.message).toBe("The service launcher supplied invalid startup context.");
225 }),
226);
227
228it.effect("ignores launcher context inherited without an IPC channel", () =>
229 Effect.gen(function* () {
230 const host = new FakeLauncherProcess(
231 { protocol: SERVICE_LAUNCHER_PROTOCOL, childVersion: "1.0.0" },
232 false,
233 );
234 const client = yield* makeClient(host, "1.1.0");
235 const error = yield* client
236 .requestUpdate({ targetVersion: "1.2.0", dbPath: "/tmp/state.sqlite" })
237 .pipe(Effect.flip);
238 expect(error).toMatchObject({ _tag: "ServiceLauncherClientError", operation: "unmanaged" });
239 expect(host.sent).toEqual([]);
240 }),
241);
242
243it.layer(NodeServices.layer)("self-update launchers", (it) => {
244 it.effect(
245 "updates custom install and PATH launchers, including versions older than fromVersion",
246 () =>
247 Effect.gen(function* () {
248 const fs = yield* FileSystem.FileSystem;
249 const path = yield* Path.Path;
250 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
251 const baseDir = path.join(root, ".t3");
252 const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
253 const installed = path.join(root, "custom/bin/t3");
254 const onPath = path.join(root, "bin/t3");
255 for (const file of [exe("1.0.0"), exe("1.5.0"), exe("2.0.0")]) {
256 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
257 yield* fs.writeFileString(file, "");
258 }
259 yield* fs.makeDirectory(path.dirname(installed), { recursive: true });
260 yield* fs.writeFileString(installed, posixLauncherScript(exe("1.5.0")), { mode: 0o755 });
261 yield* fs.makeDirectory(path.dirname(onPath), { recursive: true });
262 yield* fs.symlink(exe("1.0.0"), onPath);
263
264 yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
265 Effect.provideService(HostProcess.Environment, {
266 HOME: root,
267 T3CODE_INSTALL_BIN_DIR: path.dirname(installed),
268 PATH: path.dirname(onPath),
269 }),
270 );
271
272 // The script is rewritten and the legacy symlink becomes one.
273 assert.equal(yield* fs.readFileString(installed), posixLauncherScript(exe("2.0.0")));
274 assert.equal(yield* fs.readFileString(onPath), posixLauncherScript(exe("2.0.0")));
275 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
276 );
277
278 it.effect("still moves the PATH launcher when the install bin one cannot be rewritten", () =>
279 Effect.gen(function* () {
280 const fs = yield* FileSystem.FileSystem;
281 const path = yield* Path.Path;
282 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
283 const baseDir = path.join(root, ".t3");
284 const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
285 const installed = path.join(root, ".local/bin/t3");
286 const onPath = path.join(root, "bin/t3");
287 for (const file of [exe("1.0.0"), exe("2.0.0")]) {
288 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
289 yield* fs.writeFileString(file, "");
290 }
291 for (const link of [installed, onPath]) {
292 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
293 yield* fs.symlink(exe("1.0.0"), link);
294 }
295 const warnings: unknown[] = [];
296 const logger = Logger.make(({ logLevel, message }) => {
297 if (logLevel === "Warn") warnings.push(message);
298 });
299 const failingFs = FileSystem.FileSystem.of({
300 ...fs,
301 rename: (source, destination) =>
302 destination === installed
303 ? Effect.fail(
304 new PlatformError.PlatformError(
305 new PlatformError.SystemError({
306 _tag: "PermissionDenied",
307 module: "FileSystem",
308 method: "rename",
309 pathOrDescriptor: destination,
310 }),
311 ),
312 )
313 : fs.rename(source, destination),
314 });
315
316 yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
317 Effect.provideService(HostProcess.Environment, {
318 HOME: root,
319 PATH: path.dirname(onPath),
320 }),
321 Effect.provideService(FileSystem.FileSystem, failingFs),
322 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
323 );
324
325 assert.lengthOf(warnings, 1);
326 assert.include(JSON.stringify(warnings), installed);
327 assert.equal(yield* fs.readLink(installed), exe("1.0.0"));
328 assert.equal(yield* fs.readFileString(onPath), posixLauncherScript(exe("2.0.0")));
329 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
330 );
331
332 it.effect("leaves unowned install files and PATH symlinks untouched after self-update", () =>
333 Effect.gen(function* () {
334 const fs = yield* FileSystem.FileSystem;
335 const path = yield* Path.Path;
336 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
337 const baseDir = path.join(root, ".t3");
338 const installed = path.join(root, ".local/bin/t3");
339 const onPath = path.join(root, "bin/t3");
340 const foreign = path.join(root, "other-home/runtime/versions/1.0.0/t3");
341 const target = path.join(baseDir, "runtime/versions/2.0.0/t3");
342 for (const file of [installed, foreign, target]) {
343 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
344 yield* fs.writeFileString(file, "user-owned file");
345 }
346 yield* fs.makeDirectory(path.dirname(onPath), { recursive: true });
347 yield* fs.symlink(foreign, onPath);
348
349 yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
350 Effect.provideService(HostProcess.Environment, {
351 HOME: root,
352 PATH: path.dirname(onPath),
353 }),
354 );
355
356 assert.equal(yield* fs.readFileString(installed), "user-owned file");
357 assert.equal(yield* fs.readLink(onPath), foreign);
358 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
359 );
360
361 it.effect.each([
362 // The working-directory t3 is checked by its execute bits, which Windows hosts do not set.
363 ...(HostProcess.Platform.defaultValue() === "win32"
364 ? []
365 : [
366 { name: "leading", searchPath: (missing: string) => `:${missing}`, moved: true },
367 { name: "trailing", searchPath: (missing: string) => `${missing}:`, moved: true },
368 ]),
369 { name: "whole", searchPath: () => "", moved: false },
370 ])("treats a $name empty PATH entry like the shell does", ({ searchPath, moved }) =>
371 Effect.gen(function* () {
372 const fs = yield* FileSystem.FileSystem;
373 const path = yield* Path.Path;
374 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
375 const baseDir = path.join(root, ".t3");
376 const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
377 const cwd = path.join(root, "work");
378 const inCwd = path.join(cwd, "t3");
379 for (const file of [exe("1.0.0"), exe("2.0.0")]) {
380 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
381 yield* fs.writeFileString(file, "", { mode: 0o755 });
382 }
383 yield* fs.makeDirectory(cwd);
384 yield* fs.symlink(exe("1.0.0"), inCwd);
385
386 yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
387 Effect.provideService(HostProcess.Environment, {
388 HOME: root,
389 PATH: searchPath(path.join(root, "missing")),
390 }),
391 Effect.provideService(HostProcess.WorkingDirectory, cwd),
392 );
393
394 // A nonempty PATH searches the working directory there; an empty PATH searches nothing.
395 if (moved) {
396 assert.equal(yield* fs.readFileString(inCwd), posixLauncherScript(exe("2.0.0")));
397 } else {
398 assert.equal(yield* fs.readLink(inCwd), exe("1.0.0"));
399 }
400 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
401 );
402
403 it.effect("passes over a working-directory t3 the shell cannot run", () =>
404 Effect.gen(function* () {
405 const fs = yield* FileSystem.FileSystem;
406 const path = yield* Path.Path;
407 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
408 const baseDir = path.join(root, ".t3");
409 const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
410 const cwd = path.join(root, "work");
411 const onPath = path.join(root, "bin/t3");
412 for (const file of [exe("1.0.0"), exe("2.0.0")]) {
413 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
414 yield* fs.writeFileString(file, "", { mode: 0o755 });
415 }
416 // A directory named t3 in the working directory, which the shell skips.
417 yield* fs.makeDirectory(path.join(cwd, "t3"), { recursive: true });
418 yield* fs.makeDirectory(path.dirname(onPath), { recursive: true });
419 yield* fs.symlink(exe("1.0.0"), onPath);
420
421 yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
422 Effect.provideService(HostProcess.Environment, {
423 HOME: root,
424 PATH: `:${path.dirname(onPath)}`,
425 }),
426 Effect.provideService(HostProcess.WorkingDirectory, cwd),
427 );
428
429 assert.equal(yield* fs.readFileString(onPath), posixLauncherScript(exe("2.0.0")));
430 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
431 );
432});