Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as TestClock from "effect/testing/TestClock";
9import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
10
11import {
12 HostProcessArguments,
13 HostProcessEnvironment,
14 HostProcessExecutablePath,
15 HostProcessPlatform,
16} from "@t3tools/shared/hostProcess";
17
18import * as ServerConfig from "../config.ts";
19import * as ProcessRunner from "../processRunner.ts";
20import {
21 BOOT_SERVICE_UNIT_ENV,
22 BOOT_SERVICE_UNIT_FILE,
23 renderBootServiceUnit,
24} from "./bootService.ts";
25import * as SelfUpdate from "./selfUpdate.ts";
26
27const NODE_PATH = "/usr/local/bin/node";
28
29interface RecordedCommand {
30 readonly command: string;
31 readonly args: ReadonlyArray<string>;
32}
33
34const makeRecordingRunnerLayer = (
35 commands: Array<RecordedCommand>,
36 options?: {
37 readonly failWhen?: ((command: string, args: ReadonlyArray<string>) => boolean) | undefined;
38 readonly stdoutFor?:
39 | ((command: string, args: ReadonlyArray<string>) => string | undefined)
40 | undefined;
41 },
42) =>
43 Layer.succeed(
44 ProcessRunner.ProcessRunner,
45 ProcessRunner.ProcessRunner.of({
46 run: (input) =>
47 Effect.sync(() => {
48 commands.push({ command: input.command, args: input.args });
49 const failed = options?.failWhen?.(input.command, input.args) === true;
50 const versionFromPath =
51 input.command === NODE_PATH && input.args[1] === "--version"
52 ? /[/\\]runtime[/\\]versions[/\\]([^/\\]+)/.exec(input.args[0] ?? "")?.[1]
53 : undefined;
54 return {
55 stdout:
56 options?.stdoutFor?.(input.command, input.args) ??
57 (versionFromPath === undefined ? "" : `${versionFromPath}\n`),
58 stderr: failed ? `${input.command} exploded` : "",
59 code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
60 timedOut: false,
61 stdoutTruncated: false,
62 stderrTruncated: false,
63 };
64 }),
65 }),
66 );
67
68const provideHostRefs = (input: {
69 readonly platform: NodeJS.Platform;
70 readonly env: NodeJS.ProcessEnv;
71 readonly entryPath: string;
72}) =>
73 Effect.provide(
74 Layer.mergeAll(
75 Layer.succeed(HostProcessPlatform, input.platform),
76 Layer.succeed(HostProcessEnvironment, input.env),
77 Layer.succeed(HostProcessExecutablePath, NODE_PATH),
78 Layer.succeed(HostProcessArguments, [NODE_PATH, input.entryPath, "serve"]),
79 ),
80 );
81
82it("recognizes published npm artifacts as swappable entry points", () => {
83 assert.isTrue(SelfUpdate.isPublishedCliEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
84 assert.isTrue(
85 SelfUpdate.isPublishedCliEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
86 );
87 assert.isTrue(
88 SelfUpdate.isPublishedCliEntry(
89 "C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
90 ),
91 );
92 // Dev checkouts and the desktop bundle run apps/server/dist directly.
93 assert.isFalse(SelfUpdate.isPublishedCliEntry("/home/theo/dev/t3/apps/server/dist/bin.mjs"));
94 assert.isFalse(SelfUpdate.isPublishedCliEntry(""));
95});
96
97it.layer(NodeServices.layer)("resolveServerSelfUpdateCapability", (it) => {
98 const makeHome = Effect.fn("test.makeHome")(function* () {
99 const fs = yield* FileSystem.FileSystem;
100 const path = yield* Path.Path;
101 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
102 return { fs, path, home };
103 });
104
105 const writeUnitReferencing = Effect.fn("test.writeUnitReferencing")(function* (
106 home: string,
107 entryPath: string,
108 ) {
109 const fs = yield* FileSystem.FileSystem;
110 const path = yield* Path.Path;
111 const unitDir = path.join(home, ".config", "systemd", "user");
112 yield* fs.makeDirectory(unitDir, { recursive: true });
113 yield* fs.writeFileString(
114 path.join(unitDir, "t3code.service"),
115 renderBootServiceUnit({
116 nodePath: NODE_PATH,
117 t3EntryPath: entryPath,
118 baseDir: path.join(home, ".t3"),
119 logPath: path.join(home, ".t3", "userdata", "logs", "boot-service.log"),
120 unitPath: path.join(unitDir, "t3code.service"),
121 }),
122 );
123 });
124
125 it.effect("reports boot-service for the systemd-spawned unit process", () =>
126 Effect.gen(function* () {
127 const { home, path } = yield* makeHome();
128 const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
129 yield* writeUnitReferencing(home, entryPath);
130 const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
131 desktopManaged: false,
132 }).pipe(
133 provideHostRefs({
134 platform: "linux",
135 env: {
136 HOME: home,
137 INVOCATION_ID: "abc123",
138 [BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
139 },
140 entryPath,
141 }),
142 );
143 assert.equal(method, "boot-service");
144 }),
145 );
146
147 it.effect("does not claim a systemd process owned by another unit", () =>
148 Effect.gen(function* () {
149 const { home, path } = yield* makeHome();
150 const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
151 yield* writeUnitReferencing(home, entryPath);
152 const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
153 desktopManaged: false,
154 }).pipe(
155 provideHostRefs({
156 platform: "linux",
157 env: { HOME: home, INVOCATION_ID: "abc123" },
158 entryPath,
159 }),
160 );
161 assert.isNull(method);
162 }),
163 );
164
165 it.effect("reports respawn for a manual run of the pinned artifact", () =>
166 Effect.gen(function* () {
167 const { home, path } = yield* makeHome();
168 const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
169 yield* writeUnitReferencing(home, entryPath);
170 // Same unit on disk, but no INVOCATION_ID: restarting the unit would
171 // not replace this process, so it must respawn itself instead.
172 const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
173 desktopManaged: false,
174 }).pipe(provideHostRefs({ platform: "linux", env: { HOME: home }, entryPath }));
175 assert.equal(method, "respawn");
176 }),
177 );
178
179 it.effect("reports respawn for a foreground npx artifact on darwin", () =>
180 Effect.gen(function* () {
181 const { home } = yield* makeHome();
182 const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
183 desktopManaged: false,
184 }).pipe(
185 provideHostRefs({
186 platform: "darwin",
187 env: { HOME: home },
188 entryPath: `${home}/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs`,
189 }),
190 );
191 assert.equal(method, "respawn");
192 }),
193 );
194
195 it.effect("reports desktop-managed for desktop-supervised backends", () =>
196 Effect.gen(function* () {
197 const { home, path } = yield* makeHome();
198 // Desktop ownership wins over every process-shape heuristic: even a
199 // systemd-looking pinned artifact belongs to the app that spawned it.
200 const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
201 yield* writeUnitReferencing(home, entryPath);
202 const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
203 desktopManaged: true,
204 }).pipe(
205 provideHostRefs({
206 platform: "linux",
207 env: {
208 HOME: home,
209 INVOCATION_ID: "abc123",
210 [BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
211 },
212 entryPath,
213 }),
214 );
215 assert.equal(method, "desktop-managed");
216 }),
217 );
218
219 it.effect("reports no method for dev checkouts and Windows", () =>
220 Effect.gen(function* () {
221 const { home } = yield* makeHome();
222 const devMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
223 desktopManaged: false,
224 }).pipe(
225 provideHostRefs({
226 platform: "darwin",
227 env: { HOME: home },
228 entryPath: `${home}/dev/t3/apps/server/dist/bin.mjs`,
229 }),
230 );
231 assert.isNull(devMethod);
232 const windowsMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
233 desktopManaged: false,
234 }).pipe(
235 provideHostRefs({
236 platform: "win32",
237 env: { HOME: home },
238 entryPath: "C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
239 }),
240 );
241 assert.isNull(windowsMethod);
242 }),
243 );
244});
245
246it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
247 interface RecordedSpawn {
248 readonly command: string;
249 readonly args: ReadonlyArray<string>;
250 }
251
252 const makeContext = Effect.fn("test.makeContext")(function* (options?: {
253 readonly platform?: NodeJS.Platform;
254 readonly bootService?: boolean;
255 readonly desktopManaged?: boolean;
256 readonly entryPath?: string;
257 readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
258 readonly stdoutFor?: (command: string, args: ReadonlyArray<string>) => string | undefined;
259 readonly failSpawn?: boolean;
260 }) {
261 const fs = yield* FileSystem.FileSystem;
262 const path = yield* Path.Path;
263 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
264 const baseDir = path.join(home, ".t3");
265 const entryPath =
266 options?.entryPath ??
267 path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
268 const env: NodeJS.ProcessEnv =
269 options?.bootService === true
270 ? {
271 HOME: home,
272 INVOCATION_ID: "abc123",
273 [BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
274 }
275 : { HOME: home };
276 if (options?.bootService === true) {
277 const unitDir = path.join(home, ".config", "systemd", "user");
278 yield* fs.makeDirectory(unitDir, { recursive: true });
279 yield* fs.writeFileString(
280 path.join(unitDir, "t3code.service"),
281 renderBootServiceUnit({
282 nodePath: NODE_PATH,
283 t3EntryPath: entryPath,
284 baseDir,
285 logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
286 unitPath: path.join(unitDir, "t3code.service"),
287 }),
288 );
289 }
290
291 const commands: Array<RecordedCommand> = [];
292 const spawns: Array<RecordedSpawn> = [];
293 let exited = 0;
294 // layerTest always reports mode "web"; desktop-managed contexts overlay
295 // the mode the desktop app's bootstrap envelope would set.
296 const configLayer =
297 options?.desktopManaged === true
298 ? Layer.effect(
299 ServerConfig.ServerConfig,
300 Effect.gen(function* () {
301 const config = yield* ServerConfig.ServerConfig;
302 return { ...config, mode: "desktop" as const };
303 }),
304 ).pipe(Layer.provide(ServerConfig.layerTest(home, baseDir)))
305 : ServerConfig.layerTest(home, baseDir);
306 const service = yield* SelfUpdate.make({
307 host: {
308 spawnDetached: (command, args) =>
309 Effect.sync(() => spawns.push({ command, args })).pipe(
310 Effect.andThen(
311 options?.failSpawn === true
312 ? Effect.fail(
313 new ProcessRunner.ProcessSpawnError({
314 command,
315 argumentCount: args.length,
316 cause: new Error("detached spawn failed"),
317 }),
318 )
319 : Effect.void,
320 ),
321 ),
322 exitProcess: () => {
323 exited += 1;
324 },
325 },
326 }).pipe(
327 Effect.provide(
328 Layer.mergeAll(
329 makeRecordingRunnerLayer(commands, {
330 failWhen: options?.failWhen,
331 stdoutFor: options?.stdoutFor,
332 }),
333 configLayer,
334 ),
335 ),
336 provideHostRefs({ platform: options?.platform ?? "linux", env, entryPath }),
337 );
338 return {
339 fs,
340 path,
341 home,
342 baseDir,
343 entryPath,
344 commands,
345 spawns,
346 exitCount: () => exited,
347 service,
348 };
349 });
350
351 it.effect("rejects dist-tags and other non-exact versions", () =>
352 Effect.gen(function* () {
353 const context = yield* makeContext();
354 const error = yield* context.service.update({ targetVersion: "latest" }).pipe(Effect.flip);
355 assert.include(error.reason, "not an exact t3 version");
356 assert.lengthOf(context.commands, 0);
357 }),
358 );
359
360 it.effect("refuses to update a desktop-managed backend and points at the app", () =>
361 Effect.gen(function* () {
362 const context = yield* makeContext({ desktopManaged: true, bootService: true });
363 const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
364 assert.include(error.reason, "desktop app");
365 assert.lengthOf(context.commands, 0);
366 assert.lengthOf(context.spawns, 0);
367 }),
368 );
369
370 it.effect("fails without touching anything when no update method applies", () =>
371 Effect.gen(function* () {
372 const context = yield* makeContext({
373 entryPath: "/home/theo/dev/t3/apps/server/dist/bin.mjs",
374 });
375 const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
376 assert.include(error.reason, "cannot update itself");
377 assert.lengthOf(context.commands, 0);
378 }),
379 );
380
381 it.effect("surfaces a failed npm install and never schedules a restart", () =>
382 Effect.gen(function* () {
383 const context = yield* makeContext({ failWhen: (command) => command === "npm" });
384 const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
385 assert.equal(error.reason, "Could not install the requested t3 version.");
386 yield* TestClock.adjust(Duration.seconds(10));
387 assert.lengthOf(context.spawns, 0);
388 assert.equal(context.exitCount(), 0);
389 }).pipe(Effect.provide(TestClock.layer())),
390 );
391
392 it.effect("reinstalls the same version after a failed preflight", () =>
393 Effect.gen(function* () {
394 let preflightAttempts = 0;
395 const context = yield* makeContext({
396 failWhen: (command) => {
397 if (command !== NODE_PATH) return false;
398 preflightAttempts += 1;
399 return preflightAttempts === 1;
400 },
401 });
402 const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
403 const entryPath = context.path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
404 yield* context.fs.makeDirectory(context.path.dirname(entryPath), { recursive: true });
405 yield* context.fs.writeFileString(entryPath, "export {};\n");
406 yield* context.fs.writeFileString(
407 context.path.join(versionDir, ".install-complete"),
408 "0.0.29\n",
409 );
410
411 const firstError = yield* context.service
412 .update({ targetVersion: "0.0.29" })
413 .pipe(Effect.flip);
414 assert.include(firstError.reason, "failed its version check");
415 assert.isFalse(yield* context.fs.exists(versionDir));
416
417 const result = yield* context.service.update({ targetVersion: "0.0.29" });
418 assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
419 assert.deepEqual(
420 context.commands.map((entry) => entry.command),
421 [NODE_PATH, "npm", NODE_PATH],
422 );
423 }).pipe(Effect.provide(TestClock.layer())),
424 );
425
426 it.effect("rejects and removes an installed runtime that reports the wrong version", () =>
427 Effect.gen(function* () {
428 const context = yield* makeContext({
429 stdoutFor: (command, args) =>
430 command === NODE_PATH && args[1] === "--version" ? "0.0.28\n" : undefined,
431 });
432 const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
433
434 const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
435
436 assert.include(error.reason, "did not report the requested");
437 assert.isFalse(yield* context.fs.exists(versionDir));
438 assert.lengthOf(context.spawns, 0);
439 }),
440 );
441
442 it.effect("reports a detached replacement spawn failure and leaves updates retryable", () =>
443 Effect.gen(function* () {
444 const context = yield* makeContext({ failSpawn: true });
445
446 const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
447 assert.include(first.reason, "Could not start the replacement");
448
449 const second = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
450 assert.include(second.reason, "Could not start the replacement");
451 assert.notInclude(second.reason, "already in progress");
452 assert.lengthOf(context.spawns, 2);
453 assert.equal(context.exitCount(), 0);
454 }),
455 );
456
457 it.effect("installs, preflights, and respawns a foreground server", () =>
458 Effect.gen(function* () {
459 const context = yield* makeContext();
460 const result = yield* context.service.update({ targetVersion: "0.0.29" });
461 assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
462 assert.lengthOf(context.spawns, 1);
463
464 const concurrentError = yield* context.service
465 .update({ targetVersion: "0.0.30" })
466 .pipe(Effect.flip);
467 assert.include(concurrentError.reason, "already in progress");
468
469 const pinnedEntry = context.path.join(
470 context.baseDir,
471 "runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
472 );
473 assert.deepEqual(
474 context.commands.map((entry) => [entry.command, ...entry.args].join(" ")),
475 [
476 `npm install --prefix ${context.path.join(context.baseDir, "runtime/versions/0.0.29")} --no-fund --no-audit t3@0.0.29`,
477 `${NODE_PATH} ${pinnedEntry} --version`,
478 ],
479 );
480
481 // The restart is deferred so the RPC acknowledgement flushes first.
482 yield* TestClock.adjust(Duration.seconds(10));
483 assert.lengthOf(context.spawns, 1);
484 const spawn = context.spawns[0];
485 assert.equal(spawn?.command, "/bin/sh");
486 assert.include(spawn?.args ?? [], pinnedEntry);
487 // The replacement replays the original CLI arguments.
488 assert.include(spawn?.args ?? [], "serve");
489 assert.equal(context.exitCount(), 1);
490 }).pipe(Effect.provide(TestClock.layer())),
491 );
492
493 it.effect("rewrites the systemd unit and restarts the boot service", () =>
494 Effect.gen(function* () {
495 const context = yield* makeContext({ bootService: true });
496 const result = yield* context.service.update({ targetVersion: "0.0.29" });
497 assert.deepEqual(result, { targetVersion: "0.0.29", method: "boot-service" });
498
499 const pinnedEntry = context.path.join(
500 context.baseDir,
501 "runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
502 );
503 const unit = yield* context.fs.readFileString(
504 context.path.join(context.home, ".config", "systemd", "user", "t3code.service"),
505 );
506 assert.include(unit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
507 assert.deepEqual(
508 context.commands.map((entry) => entry.command),
509 ["npm", NODE_PATH, "systemctl", "systemctl"],
510 );
511 assert.deepEqual(context.commands[2]?.args, ["--user", "daemon-reload"]);
512
513 assert.deepEqual(context.commands[3], {
514 command: "systemctl",
515 args: ["--user", "restart", "t3code.service"],
516 });
517 assert.lengthOf(context.spawns, 0);
518 // systemd replaces the process; the server must not exit itself.
519 assert.equal(context.exitCount(), 0);
520 }).pipe(Effect.provide(TestClock.layer())),
521 );
522
523 it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
524 Effect.gen(function* () {
525 let failRestart = true;
526 const context = yield* makeContext({
527 bootService: true,
528 failWhen: (command, args) => {
529 if (command !== "systemctl" || args[1] !== "restart" || !failRestart) {
530 return false;
531 }
532 failRestart = false;
533 return true;
534 },
535 });
536 const unitPath = context.path.join(
537 context.home,
538 ".config",
539 "systemd",
540 "user",
541 BOOT_SERVICE_UNIT_FILE,
542 );
543 const previousUnit = yield* context.fs.readFileString(unitPath);
544
545 const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
546 assert.include(first.reason, "Restarting the systemd boot service failed");
547 assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
548 assert.deepEqual(
549 context.commands.slice(-2).map((entry) => entry.args),
550 [
551 ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
552 ["--user", "daemon-reload"],
553 ],
554 );
555
556 const retry = yield* context.service.update({ targetVersion: "0.0.30" });
557 assert.deepEqual(retry, { targetVersion: "0.0.30", method: "boot-service" });
558 }).pipe(Effect.provide(TestClock.layer())),
559 );
560
561 it.effect("restores the previous systemd unit when daemon-reload fails", () =>
562 Effect.gen(function* () {
563 const context = yield* makeContext({
564 bootService: true,
565 failWhen: (command) => command === "systemctl",
566 });
567 const unitPath = context.path.join(
568 context.home,
569 ".config",
570 "systemd",
571 "user",
572 BOOT_SERVICE_UNIT_FILE,
573 );
574 const previousUnit = yield* context.fs.readFileString(unitPath);
575
576 const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
577 assert.include(error.reason, "Reloading systemd units failed");
578 assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
579 assert.deepEqual(
580 context.commands.map((entry) => entry.command),
581 ["npm", NODE_PATH, "systemctl", "systemctl"],
582 );
583
584 yield* TestClock.adjust(Duration.seconds(10));
585 assert.lengthOf(context.spawns, 0);
586 assert.equal(context.exitCount(), 0);
587 }).pipe(Effect.provide(TestClock.layer())),
588 );
589});