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

selfUpdate.test.ts

403 lines15.2 KB

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