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 { HostProcessArchitecture, HostProcessPlatform } 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 { HttpClient, HttpClientResponse } from "effect/unstable/http";
12import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
13
14import * as ServerConfig from "../config.ts";
15import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
16import * as ProcessRunner from "../processRunner.ts";
17import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
18import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
19import * as ServerSelfUpdate from "./selfUpdate.ts";
20
21interface HarnessOptions {
22 readonly mode?: "web" | "desktop";
23 readonly managed?: boolean;
24 readonly preflight?: "ready" | "blocked";
25 readonly requestUpdate?: ServiceLauncherClient.ServiceLauncherClient["Service"]["requestUpdate"];
26 readonly desktopAppUpdate?: DesktopAppUpdate.DesktopAppUpdate["Service"];
27}
28
29// The staged runtime is a release archive: the fake client serves SHA256SUMS
30// and the tarball, and the fake runner stands in for tar before it answers
31// the staged preflight.
32const archiveBytes = new TextEncoder().encode("not really a tarball");
33const releaseHttpClient = (order: string[]) =>
34 HttpClient.make((request) =>
35 Effect.gen(function* () {
36 if (request.url.endsWith("/SHA256SUMS")) {
37 const digest = yield* Effect.promise(() => crypto.subtle.digest("SHA-256", archiveBytes));
38 const hex = Array.from(new Uint8Array(digest), (byte) =>
39 byte.toString(16).padStart(2, "0"),
40 ).join("");
41 return HttpClientResponse.fromWeb(
42 request,
43 new Response(`${hex} t3-1.1.0-linux-x64.tar.gz\n`),
44 );
45 }
46 order.push("download");
47 return HttpClientResponse.fromWeb(request, new Response(archiveBytes));
48 }),
49 );
50
51const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
52 options: HarnessOptions = {},
53) {
54 const fs = yield* FileSystem.FileSystem;
55 const path = yield* Path.Path;
56 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
57 const order: string[] = [];
58 const runner = ProcessRunner.ProcessRunner.of({
59 run: (input) =>
60 Effect.gen(function* () {
61 if (input.command === "tar") {
62 order.push("extract");
63 const stagingDir = input.args[input.args.indexOf("-C") + 1];
64 if (stagingDir === undefined) return yield* Effect.die("missing tar target");
65 yield* fs.writeFileString(path.join(stagingDir, "t3"), "#!/bin/sh\n").pipe(Effect.orDie);
66 return {
67 stdout: "",
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 order.push("preflight");
78 const result =
79 options.preflight === "blocked"
80 ? { status: "blocked", version: "1.1.0", reason: "local update required" }
81 : {
82 status: "ready",
83 version: "1.1.0",
84 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
85 };
86 return {
87 // @effect-diagnostics-next-line preferSchemaOverJson:off - fake child-process stdout.
88 stdout: JSON.stringify(result),
89 stderr: "",
90 code: ChildProcessSpawner.ExitCode(0),
91 timedOut: false,
92 stdoutTruncated: false,
93 stderrTruncated: false,
94 stdoutInvalidUtf8: false,
95 stderrInvalidUtf8: false,
96 };
97 }),
98 });
99 const launcher = ServiceLauncherClient.ServiceLauncherClient.of({
100 managed: options.managed ?? true,
101 requestUpdate:
102 options.requestUpdate ??
103 (() =>
104 Effect.sync(() => {
105 order.push("accept");
106 return "launcher-id";
107 })),
108 prepareTrial: Effect.undefined,
109 });
110 const config = yield* ServerConfig.ServerConfig.pipe(
111 Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
112 );
113 const selfUpdate = yield* ServerSelfUpdate.make().pipe(
114 Effect.provideService(ProcessRunner.ProcessRunner, runner),
115 Effect.provideService(ServiceLauncherClient.ServiceLauncherClient, launcher),
116 Effect.provideService(
117 DesktopAppUpdate.DesktopAppUpdate,
118 options.desktopAppUpdate ?? {
119 available: false,
120 run: () => Effect.die("unexpected desktop app update run"),
121 },
122 ),
123 Effect.provideService(HttpClient.HttpClient, releaseHttpClient(order)),
124 Effect.provideService(HostProcessPlatform, "linux"),
125 Effect.provideService(HostProcessArchitecture, "x64"),
126 Effect.provide(ServerConfig.layer({ ...config, mode: options.mode ?? "web" })),
127 );
128 return { selfUpdate, order };
129});
130
131it.layer(NodeServices.layer)("server self update", (it) => {
132 it.effect("marks running threads at the boot-service handoff", () =>
133 Effect.gen(function* () {
134 const events: string[] = [];
135 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
136 mode: "web",
137 selfUpdate: {
138 update: (_input, reportProgress = () => Effect.void) =>
139 reportProgress("downloading").pipe(
140 Effect.andThen(reportProgress("installing")),
141 Effect.as({
142 targetVersion: "1.1.0",
143 method: "boot-service" as const,
144 updateId: "update-id",
145 }),
146 ),
147 commitDesktopUpdate: () => Effect.never,
148 },
149 prepare: Effect.sync(() => {
150 events.push("prepare");
151 return [ThreadId.make("thread-running")];
152 }),
153 clear: () => Effect.sync(() => void events.push("clear")),
154 });
155
156 yield* selfUpdate.update({ targetVersion: "1.1.0", continueRunningThreads: true }, (stage) =>
157 Effect.sync(() => void events.push(stage)),
158 );
159
160 expect(events).toEqual(["downloading", "prepare", "installing"]);
161 }),
162 );
163
164 it.effect("marks desktop threads only when the prepared update commits", () =>
165 Effect.gen(function* () {
166 const threadId = ThreadId.make("thread-running-desktop");
167 const events: string[] = [];
168 const commitError = new ServerSelfUpdateError({ reason: "install failed" });
169 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
170 mode: "desktop",
171 selfUpdate: {
172 update: (_input, reportProgress = () => Effect.void) =>
173 reportProgress("installing").pipe(
174 Effect.as({
175 targetVersion: "1.2.0",
176 method: "desktop-app" as const,
177 desktopUpdateToken: "desktop-token",
178 }),
179 ),
180 commitDesktopUpdate: () =>
181 Effect.sync(() => events.push("commit")).pipe(Effect.andThen(Effect.fail(commitError))),
182 },
183 prepare: Effect.sync(() => {
184 events.push("prepare");
185 return [threadId];
186 }),
187 clear: (threadIds) => Effect.sync(() => void events.push(`clear:${threadIds.join(",")}`)),
188 });
189
190 yield* selfUpdate.update({ targetVersion: "1.2.0", continueRunningThreads: true }, (stage) =>
191 Effect.sync(() => void events.push(stage)),
192 );
193 expect(events).toEqual(["installing"]);
194 expect(yield* selfUpdate.commitDesktopUpdate("desktop-token").pipe(Effect.flip)).toBe(
195 commitError,
196 );
197 expect(events).toEqual(["installing", "prepare", "commit", `clear:${threadId}`]);
198 expect(yield* selfUpdate.commitDesktopUpdate("desktop-token").pipe(Effect.flip)).toBe(
199 commitError,
200 );
201 expect(events).toEqual([
202 "installing",
203 "prepare",
204 "commit",
205 `clear:${threadId}`,
206 "prepare",
207 "commit",
208 `clear:${threadId}`,
209 ]);
210 }),
211 );
212
213 it.effect("reports a failed continuation-marker cleanup", () =>
214 Effect.gen(function* () {
215 const updateError = new ServerSelfUpdateError({ reason: "update failed" });
216 const clearError = new ServerSelfUpdateError({ reason: "marker cleanup failed" });
217 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
218 mode: "web",
219 selfUpdate: {
220 update: (_input, reportProgress = () => Effect.void) =>
221 reportProgress("installing").pipe(Effect.andThen(Effect.fail(updateError))),
222 commitDesktopUpdate: () => Effect.never,
223 },
224 prepare: Effect.succeed([ThreadId.make("thread-cleanup-failure")]),
225 clear: () => Effect.fail(clearError),
226 });
227
228 expect(
229 yield* selfUpdate
230 .update({ targetVersion: "1.1.0", continueRunningThreads: true })
231 .pipe(Effect.flip),
232 ).toBe(clearError);
233 }),
234 );
235
236 it.effect("keeps continuation markers after the boot-service handoff is accepted", () =>
237 Effect.gen(function* () {
238 const events: string[] = [];
239 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
240 mode: "web",
241 selfUpdate: {
242 update: (
243 _input,
244 reportProgress = () => Effect.void,
245 onHandoffAccepted = () => Effect.void,
246 ) =>
247 reportProgress("installing").pipe(
248 Effect.andThen(onHandoffAccepted()),
249 Effect.andThen(Effect.interrupt),
250 ),
251 commitDesktopUpdate: () => Effect.never,
252 },
253 prepare: Effect.sync(() => {
254 events.push("prepare");
255 return [ThreadId.make("thread-accepted-boot-handoff")];
256 }),
257 clear: () => Effect.sync(() => void events.push("clear")),
258 });
259
260 const exit = yield* selfUpdate
261 .update({ targetVersion: "1.1.0", continueRunningThreads: true })
262 .pipe(Effect.exit);
263
264 expect(exit._tag).toBe("Failure");
265 expect(events).toEqual(["prepare"]);
266 }),
267 );
268
269 it.effect("keeps continuation markers after the desktop handoff is accepted", () =>
270 Effect.gen(function* () {
271 const events: string[] = [];
272 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
273 mode: "desktop",
274 selfUpdate: {
275 update: () =>
276 Effect.succeed({
277 targetVersion: "1.2.0",
278 method: "desktop-app" as const,
279 desktopUpdateToken: "accepted-desktop-token",
280 }),
281 commitDesktopUpdate: (_requestId, onHandoffAccepted = () => Effect.void) =>
282 onHandoffAccepted().pipe(Effect.andThen(Effect.interrupt)),
283 },
284 prepare: Effect.sync(() => {
285 events.push("prepare");
286 return [ThreadId.make("thread-accepted-desktop-handoff")];
287 }),
288 clear: () => Effect.sync(() => void events.push("clear")),
289 });
290
291 yield* selfUpdate.update({
292 targetVersion: "1.2.0",
293 continueRunningThreads: true,
294 });
295 const exit = yield* selfUpdate
296 .commitDesktopUpdate("accepted-desktop-token")
297 .pipe(Effect.exit);
298
299 expect(exit._tag).toBe("Failure");
300 expect(events).toEqual(["prepare"]);
301 }),
302 );
303
304 it.effect("clears continuation markers for mixed failure and interrupt causes", () =>
305 Effect.gen(function* () {
306 const events: string[] = [];
307 const commitError = new ServerSelfUpdateError({ reason: "install failed" });
308 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
309 mode: "desktop",
310 selfUpdate: {
311 update: () =>
312 Effect.succeed({
313 targetVersion: "1.2.0",
314 method: "desktop-app" as const,
315 desktopUpdateToken: "failed-desktop-token",
316 }),
317 commitDesktopUpdate: (_requestId, onHandoffAccepted = () => Effect.void) =>
318 onHandoffAccepted().pipe(
319 Effect.andThen(
320 Effect.failCause(
321 Cause.fromReasons([
322 Cause.makeFailReason(commitError),
323 Cause.makeInterruptReason(),
324 ]),
325 ),
326 ),
327 ),
328 },
329 prepare: Effect.sync(() => [ThreadId.make("thread-failed-desktop-install")]),
330 clear: () => Effect.sync(() => void events.push("clear")),
331 });
332
333 yield* selfUpdate.update({
334 targetVersion: "1.2.0",
335 continueRunningThreads: true,
336 });
337 const exit = yield* selfUpdate.commitDesktopUpdate("failed-desktop-token").pipe(Effect.exit);
338 expect(exit._tag).toBe("Failure");
339 if (exit._tag === "Failure") {
340 expect(Cause.hasInterrupts(exit.cause)).toBe(true);
341 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(false);
342 }
343 expect(events).toEqual(["clear"]);
344 }),
345 );
346
347 it.effect("stages and preflights before asking the launcher for an update ID", () =>
348 Effect.gen(function* () {
349 const { selfUpdate, order } = yield* makeHarness();
350 expect(yield* selfUpdate.update({ targetVersion: "1.1.0" })).toEqual({
351 targetVersion: "1.1.0",
352 method: "boot-service",
353 updateId: "launcher-id",
354 });
355 expect(order).toEqual(["download", "extract", "preflight", "accept"]);
356 }),
357 );
358
359 it.effect("rejects invalid versions and desktop-managed servers before staging", () =>
360 Effect.gen(function* () {
361 const web = yield* makeHarness();
362 expect(
363 (yield* web.selfUpdate.update({ targetVersion: "latest" }).pipe(Effect.flip)).reason,
364 ).toBe("'latest' is not an exact t3 version.");
365 const desktop = yield* makeHarness({ mode: "desktop" });
366 expect(
367 (yield* desktop.selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason,
368 ).toContain("desktop app");
369 expect([...web.order, ...desktop.order]).toEqual([]);
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});