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