Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serviceLauncherClient.test.ts

461 lines19.3 KB

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 }
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 // regression: #45698 an update from the app left the Windows t3.cmd shim on the old runtime
279 it.effect("moves the Windows t3.cmd shim the installer wrote to the new runtime", () =>
280 Effect.gen(function* () {
281 const fs = yield* FileSystem.FileSystem;
282 const path = yield* Path.Path;
283 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
284 const baseDir = path.join(root, ".t3");
285 const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3.exe");
286 const shim = path.join(root, ".local/bin/t3.cmd");
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 yield* fs.makeDirectory(path.dirname(shim), { recursive: true });
292 yield* fs.writeFileString(shim, `@echo off\r\n"${exe("1.0.0")}" %*`);
293 yield* fs.writeFileString(path.join(baseDir, "runtime/launchers"), `${shim}\n`);
294​
295 yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
296 Effect.provideService(HostProcess.Environment, {
297 USERPROFILE: root,
298 T3CODE_INSTALL_BIN_DIR: path.dirname(shim),
299 PATH: path.dirname(shim),
300 }),
301 );
302​
303 assert.equal(yield* fs.readFileString(shim), `@echo off\r\n"${exe("2.0.0")}" %*`);
304 }).pipe(Effect.provideService(HostProcess.Platform, "win32")),
305 );
306​
307 it.effect("still moves the PATH launcher when the install bin one cannot be rewritten", () =>
308 Effect.gen(function* () {
309 const fs = yield* FileSystem.FileSystem;
310 const path = yield* Path.Path;
311 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
312 const baseDir = path.join(root, ".t3");
313 const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
314 const installed = path.join(root, ".local/bin/t3");
315 const onPath = path.join(root, "bin/t3");
316 for (const file of [exe("1.0.0"), exe("2.0.0")]) {
317 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
318 yield* fs.writeFileString(file, "");
319 }
320 for (const link of [installed, onPath]) {
321 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
322 yield* fs.symlink(exe("1.0.0"), link);
323 }
324 const warnings: unknown[] = [];
325 const logger = Logger.make(({ logLevel, message }) => {
326 if (logLevel === "Warn") warnings.push(message);
327 });
328 const failingFs = FileSystem.FileSystem.of({
329 ...fs,
330 rename: (source, destination) =>
331 destination === installed
332 ? Effect.fail(
333 new PlatformError.PlatformError(
334 new PlatformError.SystemError({
335 _tag: "PermissionDenied",
336 module: "FileSystem",
337 method: "rename",
338 pathOrDescriptor: destination,
339 }),
340 ),
341 )
342 : fs.rename(source, destination),
343 });
344​
345 yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
346 Effect.provideService(HostProcess.Environment, {
347 HOME: root,
348 PATH: path.dirname(onPath),
349 }),
350 Effect.provideService(FileSystem.FileSystem, failingFs),
351 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
352 );
353​
354 assert.lengthOf(warnings, 1);
355 assert.include(JSON.stringify(warnings), installed);
356 assert.equal(yield* fs.readLink(installed), exe("1.0.0"));
357 assert.equal(yield* fs.readFileString(onPath), posixLauncherScript(exe("2.0.0")));
358 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
359 );
360​
361 it.effect("leaves unowned install files and PATH symlinks untouched after self-update", () =>
362 Effect.gen(function* () {
363 const fs = yield* FileSystem.FileSystem;
364 const path = yield* Path.Path;
365 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
366 const baseDir = path.join(root, ".t3");
367 const installed = path.join(root, ".local/bin/t3");
368 const onPath = path.join(root, "bin/t3");
369 const foreign = path.join(root, "other-home/runtime/versions/1.0.0/t3");
370 const target = path.join(baseDir, "runtime/versions/2.0.0/t3");
371 for (const file of [installed, foreign, target]) {
372 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
373 yield* fs.writeFileString(file, "user-owned file");
374 }
375 yield* fs.makeDirectory(path.dirname(onPath), { recursive: true });
376 yield* fs.symlink(foreign, onPath);
377​
378 yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
379 Effect.provideService(HostProcess.Environment, {
380 HOME: root,
381 PATH: path.dirname(onPath),
382 }),
383 );
384​
385 assert.equal(yield* fs.readFileString(installed), "user-owned file");
386 assert.equal(yield* fs.readLink(onPath), foreign);
387 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
388 );
389​
390 it.effect.each([
391 // The working-directory t3 is checked by its execute bits, which Windows hosts do not set.
392 ...(HostProcess.Platform.defaultValue() === "win32"
393 ? []
394 : [
395 { name: "leading", searchPath: (missing: string) => `:${missing}`, moved: true },
396 { name: "trailing", searchPath: (missing: string) => `${missing}:`, moved: true },
397 ]),
398 { name: "whole", searchPath: () => "", moved: false },
399 ])("treats a $name empty PATH entry like the shell does", ({ searchPath, moved }) =>
400 Effect.gen(function* () {
401 const fs = yield* FileSystem.FileSystem;
402 const path = yield* Path.Path;
403 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
404 const baseDir = path.join(root, ".t3");
405 const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
406 const cwd = path.join(root, "work");
407 const inCwd = path.join(cwd, "t3");
408 for (const file of [exe("1.0.0"), exe("2.0.0")]) {
409 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
410 yield* fs.writeFileString(file, "", { mode: 0o755 });
411 }
412 yield* fs.makeDirectory(cwd);
413 yield* fs.symlink(exe("1.0.0"), inCwd);
414​
415 yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
416 Effect.provideService(HostProcess.Environment, {
417 HOME: root,
418 PATH: searchPath(path.join(root, "missing")),
419 }),
420 Effect.provideService(HostProcess.WorkingDirectory, cwd),
421 );
422​
423 // A nonempty PATH searches the working directory there; an empty PATH searches nothing.
424 if (moved) {
425 assert.equal(yield* fs.readFileString(inCwd), posixLauncherScript(exe("2.0.0")));
426 } else {
427 assert.equal(yield* fs.readLink(inCwd), exe("1.0.0"));
428 }
429 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
430 );
431​
432 it.effect("passes over a working-directory t3 the shell cannot run", () =>
433 Effect.gen(function* () {
434 const fs = yield* FileSystem.FileSystem;
435 const path = yield* Path.Path;
436 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
437 const baseDir = path.join(root, ".t3");
438 const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
439 const cwd = path.join(root, "work");
440 const onPath = path.join(root, "bin/t3");
441 for (const file of [exe("1.0.0"), exe("2.0.0")]) {
442 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
443 yield* fs.writeFileString(file, "", { mode: 0o755 });
444 }
445 // A directory named t3 in the working directory, which the shell skips.
446 yield* fs.makeDirectory(path.join(cwd, "t3"), { recursive: true });
447 yield* fs.makeDirectory(path.dirname(onPath), { recursive: true });
448 yield* fs.symlink(exe("1.0.0"), onPath);
449​
450 yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
451 Effect.provideService(HostProcess.Environment, {
452 HOME: root,
453 PATH: `:${path.dirname(onPath)}`,
454 }),
455 Effect.provideService(HostProcess.WorkingDirectory, cwd),
456 );
457​
458 assert.equal(yield* fs.readFileString(onPath), posixLauncherScript(exe("2.0.0")));
459 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
460 );
461});