Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import { ServerSelfUpdateError, ThreadId } from "@t3tools/contracts";
4import { HostProcessExecutablePath } from "@t3tools/shared/hostProcess";
5import * as Cause from "effect/Cause";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Fiber from "effect/Fiber";
10import * as Path from "effect/Path";
11import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
12
13import * as ServerConfig from "../config.ts";
14import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
15import * as ProcessRunner from "../processRunner.ts";
16import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
17import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
18import * as ServerSelfUpdate from "./selfUpdate.ts";
19
20interface HarnessOptions {
21 readonly mode?: "web" | "desktop";
22 readonly managed?: boolean;
23 readonly preflight?: "ready" | "blocked";
24 readonly nativeModuleAvailable?: boolean;
25 readonly requestUpdate?: ServiceLauncherClient.ServiceLauncherClient["Service"]["requestUpdate"];
26 readonly desktopAppUpdate?: DesktopAppUpdate.DesktopAppUpdate["Service"];
27}
28
29const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
30 options: HarnessOptions = {},
31) {
32 const fs = yield* FileSystem.FileSystem;
33 const path = yield* Path.Path;
34 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
35 const order: string[] = [];
36 const runner = ProcessRunner.ProcessRunner.of({
37 run: (input) =>
38 Effect.gen(function* () {
39 if (input.command === "npm") {
40 order.push("install");
41 const prefix = input.args[input.args.indexOf("--prefix") + 1];
42 if (prefix === undefined) return yield* Effect.die("missing npm prefix");
43 const entry = path.join(prefix, "node_modules", "t3", "dist", "bin.mjs");
44 yield* fs.makeDirectory(path.dirname(entry), { recursive: true }).pipe(Effect.orDie);
45 yield* fs.writeFileString(entry, "export {};\n").pipe(Effect.orDie);
46 return {
47 stdout: "",
48 stderr: "",
49 code: ChildProcessSpawner.ExitCode(0),
50 timedOut: false,
51 stdoutTruncated: false,
52 stderrTruncated: false,
53 stdoutInvalidUtf8: false,
54 stderrInvalidUtf8: false,
55 };
56 }
57 if (input.args[0] === "--input-type=commonjs") {
58 order.push("native-module");
59 return {
60 stdout: "",
61 stderr: options.nativeModuleAvailable === false ? "Cannot find module pty.node" : "",
62 code: ChildProcessSpawner.ExitCode(options.nativeModuleAvailable === false ? 1 : 0),
63 timedOut: false,
64 stdoutTruncated: false,
65 stderrTruncated: false,
66 stdoutInvalidUtf8: false,
67 stderrInvalidUtf8: false,
68 };
69 }
70 order.push("preflight");
71 const result =
72 options.preflight === "blocked"
73 ? { status: "blocked", version: "1.1.0", reason: "local update required" }
74 : {
75 status: "ready",
76 version: "1.1.0",
77 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
78 };
79 return {
80 // @effect-diagnostics-next-line preferSchemaOverJson:off - fake child-process stdout.
81 stdout: JSON.stringify(result),
82 stderr: "",
83 code: ChildProcessSpawner.ExitCode(0),
84 timedOut: false,
85 stdoutTruncated: false,
86 stderrTruncated: false,
87 stdoutInvalidUtf8: false,
88 stderrInvalidUtf8: false,
89 };
90 }),
91 });
92 const launcher = ServiceLauncherClient.ServiceLauncherClient.of({
93 managed: options.managed ?? true,
94 requestUpdate:
95 options.requestUpdate ??
96 (() =>
97 Effect.sync(() => {
98 order.push("accept");
99 return "launcher-id";
100 })),
101 prepareTrial: Effect.sync((): undefined => undefined),
102 });
103 const config = yield* ServerConfig.ServerConfig.pipe(
104 Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
105 );
106 const selfUpdate = yield* ServerSelfUpdate.make().pipe(
107 Effect.provideService(ProcessRunner.ProcessRunner, runner),
108 Effect.provideService(ServiceLauncherClient.ServiceLauncherClient, launcher),
109 Effect.provideService(
110 DesktopAppUpdate.DesktopAppUpdate,
111 options.desktopAppUpdate ?? {
112 available: false,
113 run: () => Effect.die("unexpected desktop app update run"),
114 },
115 ),
116 Effect.provideService(HostProcessExecutablePath, "/usr/bin/node"),
117 Effect.provide(ServerConfig.layer({ ...config, mode: options.mode ?? "web" })),
118 );
119 return { selfUpdate, order };
120});
121
122it.layer(NodeServices.layer)("server self update", (it) => {
123 it.effect("marks running threads at the boot-service handoff", () =>
124 Effect.gen(function* () {
125 const events: string[] = [];
126 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
127 mode: "web",
128 selfUpdate: {
129 update: (_input, reportProgress = () => Effect.void) =>
130 reportProgress("downloading").pipe(
131 Effect.andThen(reportProgress("installing")),
132 Effect.as({
133 targetVersion: "1.1.0",
134 method: "boot-service" as const,
135 updateId: "update-id",
136 }),
137 ),
138 commitDesktopUpdate: () => Effect.never,
139 },
140 prepare: Effect.sync(() => {
141 events.push("prepare");
142 return [ThreadId.make("thread-running")];
143 }),
144 clear: () => Effect.sync(() => void events.push("clear")),
145 });
146
147 yield* selfUpdate.update({ targetVersion: "1.1.0", continueRunningThreads: true }, (stage) =>
148 Effect.sync(() => void events.push(stage)),
149 );
150
151 expect(events).toEqual(["downloading", "prepare", "installing"]);
152 }),
153 );
154
155 it.effect("marks desktop threads only when the prepared update commits", () =>
156 Effect.gen(function* () {
157 const threadId = ThreadId.make("thread-running-desktop");
158 const events: string[] = [];
159 const commitError = new ServerSelfUpdateError({ reason: "install failed" });
160 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
161 mode: "desktop",
162 selfUpdate: {
163 update: (_input, reportProgress = () => Effect.void) =>
164 reportProgress("installing").pipe(
165 Effect.as({
166 targetVersion: "1.2.0",
167 method: "desktop-app" as const,
168 desktopUpdateToken: "desktop-token",
169 }),
170 ),
171 commitDesktopUpdate: () =>
172 Effect.sync(() => events.push("commit")).pipe(Effect.andThen(Effect.fail(commitError))),
173 },
174 prepare: Effect.sync(() => {
175 events.push("prepare");
176 return [threadId];
177 }),
178 clear: (threadIds) => Effect.sync(() => void events.push(`clear:${threadIds.join(",")}`)),
179 });
180
181 yield* selfUpdate.update({ targetVersion: "1.2.0", continueRunningThreads: true }, (stage) =>
182 Effect.sync(() => void events.push(stage)),
183 );
184 expect(events).toEqual(["installing"]);
185 expect(yield* selfUpdate.commitDesktopUpdate("desktop-token").pipe(Effect.flip)).toBe(
186 commitError,
187 );
188 expect(events).toEqual(["installing", "prepare", "commit", `clear:${threadId}`]);
189 expect(yield* selfUpdate.commitDesktopUpdate("desktop-token").pipe(Effect.flip)).toBe(
190 commitError,
191 );
192 expect(events).toEqual([
193 "installing",
194 "prepare",
195 "commit",
196 `clear:${threadId}`,
197 "prepare",
198 "commit",
199 `clear:${threadId}`,
200 ]);
201 }),
202 );
203
204 it.effect("reports a failed continuation-marker cleanup", () =>
205 Effect.gen(function* () {
206 const updateError = new ServerSelfUpdateError({ reason: "update failed" });
207 const clearError = new ServerSelfUpdateError({ reason: "marker cleanup failed" });
208 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
209 mode: "web",
210 selfUpdate: {
211 update: (_input, reportProgress = () => Effect.void) =>
212 reportProgress("installing").pipe(Effect.andThen(Effect.fail(updateError))),
213 commitDesktopUpdate: () => Effect.never,
214 },
215 prepare: Effect.succeed([ThreadId.make("thread-cleanup-failure")]),
216 clear: () => Effect.fail(clearError),
217 });
218
219 expect(
220 yield* selfUpdate
221 .update({ targetVersion: "1.1.0", continueRunningThreads: true })
222 .pipe(Effect.flip),
223 ).toBe(clearError);
224 }),
225 );
226
227 it.effect("keeps continuation markers after the boot-service handoff is accepted", () =>
228 Effect.gen(function* () {
229 const events: string[] = [];
230 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
231 mode: "web",
232 selfUpdate: {
233 update: (
234 _input,
235 reportProgress = () => Effect.void,
236 onHandoffAccepted = () => Effect.void,
237 ) =>
238 reportProgress("installing").pipe(
239 Effect.andThen(onHandoffAccepted()),
240 Effect.andThen(Effect.interrupt),
241 ),
242 commitDesktopUpdate: () => Effect.never,
243 },
244 prepare: Effect.sync(() => {
245 events.push("prepare");
246 return [ThreadId.make("thread-accepted-boot-handoff")];
247 }),
248 clear: () => Effect.sync(() => void events.push("clear")),
249 });
250
251 const exit = yield* selfUpdate
252 .update({ targetVersion: "1.1.0", continueRunningThreads: true })
253 .pipe(Effect.exit);
254
255 expect(exit._tag).toBe("Failure");
256 expect(events).toEqual(["prepare"]);
257 }),
258 );
259
260 it.effect("keeps continuation markers after the desktop handoff is accepted", () =>
261 Effect.gen(function* () {
262 const events: string[] = [];
263 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
264 mode: "desktop",
265 selfUpdate: {
266 update: () =>
267 Effect.succeed({
268 targetVersion: "1.2.0",
269 method: "desktop-app" as const,
270 desktopUpdateToken: "accepted-desktop-token",
271 }),
272 commitDesktopUpdate: (_requestId, onHandoffAccepted = () => Effect.void) =>
273 onHandoffAccepted().pipe(Effect.andThen(Effect.interrupt)),
274 },
275 prepare: Effect.sync(() => {
276 events.push("prepare");
277 return [ThreadId.make("thread-accepted-desktop-handoff")];
278 }),
279 clear: () => Effect.sync(() => void events.push("clear")),
280 });
281
282 yield* selfUpdate.update({
283 targetVersion: "1.2.0",
284 continueRunningThreads: true,
285 });
286 const exit = yield* selfUpdate
287 .commitDesktopUpdate("accepted-desktop-token")
288 .pipe(Effect.exit);
289
290 expect(exit._tag).toBe("Failure");
291 expect(events).toEqual(["prepare"]);
292 }),
293 );
294
295 it.effect("clears continuation markers for mixed failure and interrupt causes", () =>
296 Effect.gen(function* () {
297 const events: string[] = [];
298 const commitError = new ServerSelfUpdateError({ reason: "install failed" });
299 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
300 mode: "desktop",
301 selfUpdate: {
302 update: () =>
303 Effect.succeed({
304 targetVersion: "1.2.0",
305 method: "desktop-app" as const,
306 desktopUpdateToken: "failed-desktop-token",
307 }),
308 commitDesktopUpdate: (_requestId, onHandoffAccepted = () => Effect.void) =>
309 onHandoffAccepted().pipe(
310 Effect.andThen(
311 Effect.failCause(
312 Cause.fromReasons([
313 Cause.makeFailReason(commitError),
314 Cause.makeInterruptReason(),
315 ]),
316 ),
317 ),
318 ),
319 },
320 prepare: Effect.sync(() => [ThreadId.make("thread-failed-desktop-install")]),
321 clear: () => Effect.sync(() => void events.push("clear")),
322 });
323
324 yield* selfUpdate.update({
325 targetVersion: "1.2.0",
326 continueRunningThreads: true,
327 });
328 const exit = yield* selfUpdate.commitDesktopUpdate("failed-desktop-token").pipe(Effect.exit);
329 expect(exit._tag).toBe("Failure");
330 if (exit._tag === "Failure") {
331 expect(Cause.hasInterrupts(exit.cause)).toBe(true);
332 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(false);
333 }
334 expect(events).toEqual(["clear"]);
335 }),
336 );
337
338 it.effect("stages and preflights before asking the launcher for an update ID", () =>
339 Effect.gen(function* () {
340 const { selfUpdate, order } = yield* makeHarness();
341 expect(yield* selfUpdate.update({ targetVersion: "1.1.0" })).toEqual({
342 targetVersion: "1.1.0",
343 method: "boot-service",
344 updateId: "launcher-id",
345 });
346 expect(order).toEqual(["install", "native-module", "preflight", "accept"]);
347 }),
348 );
349
350 it.effect("rejects invalid versions and desktop-managed servers before staging", () =>
351 Effect.gen(function* () {
352 const web = yield* makeHarness();
353 expect(
354 (yield* web.selfUpdate.update({ targetVersion: "latest" }).pipe(Effect.flip)).reason,
355 ).toBe("'latest' is not an exact t3 version.");
356 const desktop = yield* makeHarness({ mode: "desktop" });
357 expect(
358 (yield* desktop.selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason,
359 ).toContain("desktop app");
360 expect([...web.order, ...desktop.order]).toEqual([]);
361 }),
362 );
363
364 it.effect("does not hand off an update when npm succeeds without a working native module", () =>
365 Effect.gen(function* () {
366 const { selfUpdate, order } = yield* makeHarness({ nativeModuleAvailable: false });
367 const error = yield* selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip);
368 expect(error.reason).toBe("Could not prepare t3@1.1.0.");
369 expect(order).toEqual(["install", "native-module"]);
370 }),
371 );
372
373 it.effect("delegates desktop-managed updates to the desktop app when available", () =>
374 Effect.gen(function* () {
375 const stages: string[] = [];
376 const { selfUpdate, order } = yield* makeHarness({
377 mode: "desktop",
378 desktopAppUpdate: {
379 available: true,
380 run: (reportProgress) =>
381 reportProgress("downloading").pipe(
382 Effect.andThen(reportProgress("installing")),
383 Effect.as({ targetVersion: "1.2.0", method: "desktop-app" as const }),
384 ),
385 commit: () => Effect.never,
386 },
387 });
388 const result = yield* selfUpdate.update({ targetVersion: "1.1.0" }, (stage) =>
389 Effect.sync(() => void stages.push(stage)),
390 );
391 expect(result).toEqual({ targetVersion: "1.2.0", method: "desktop-app" });
392 expect(stages).toEqual(["downloading", "installing"]);
393 // The launcher staging path must not run on the desktop path.
394 expect(order).toEqual([]);
395 }),
396 );
397
398 it.effect("preserves the preflight refusal reason", () =>
399 Effect.gen(function* () {
400 const { selfUpdate } = yield* makeHarness({ preflight: "blocked" });
401 expect((yield* selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason).toBe(
402 "local update required",
403 );
404 }),
405 );
406
407 it.effect("allows only one update at a time", () =>
408 Effect.gen(function* () {
409 const requested = yield* Deferred.make<void>();
410 const accepted = yield* Deferred.make<string>();
411 const { selfUpdate } = yield* makeHarness({
412 requestUpdate: () =>
413 Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(accepted))),
414 });
415 const first = yield* Effect.forkChild(selfUpdate.update({ targetVersion: "1.1.0" }), {
416 startImmediately: true,
417 });
418 yield* Deferred.await(requested);
419 expect((yield* selfUpdate.update({ targetVersion: "1.1.1" }).pipe(Effect.flip)).reason).toBe(
420 "A server update is already in progress.",
421 );
422 yield* Deferred.succeed(accepted, "launcher-id");
423 expect((yield* Fiber.join(first)).updateId).toBe("launcher-id");
424 }),
425 );
426});