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

selfUpdate.test.ts

388 lines14.8 KB

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 * as Stream from "effect/Stream";
12import { HttpClient, HttpClientResponse } from "effect/http";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14​
15import * as ServerConfig from "../config.ts";
16import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
17import * as ProcessRunner from "../processRunner.ts";
18import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
19import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
20import * as ServerSelfUpdate from "./selfUpdate.ts";
21​
22interface HarnessOptions {
23 readonly mode?: "web" | "desktop";
24 readonly managed?: boolean;
25 readonly preflight?: "ready" | "blocked";
26 readonly beforeDownload?: Effect.Effect<void>;
27 readonly requestUpdate?: ServiceLauncherClient.ServiceLauncherClient["Service"]["requestUpdate"];
28 readonly desktopAppUpdate?: DesktopAppUpdate.DesktopAppUpdate["Service"];
30​
31const archiveBytes = new TextEncoder().encode("not really a tarball");
32const releaseHttpClient = (order: string[], beforeDownload?: Effect.Effect<void>) =>
33 HttpClient.make((request) =>
34 Effect.gen(function* () {
35 if (request.url.endsWith("/SHA256SUMS")) {
36 const digest = yield* Effect.promise(() => crypto.subtle.digest("SHA-256", archiveBytes));
37 const hex = Array.from(new Uint8Array(digest), (byte) =>
38 byte.toString(16).padStart(2, "0"),
39 ).join("");
40 return HttpClientResponse.fromWeb(
41 request,
42 new Response(`${hex} t3-1.1.0-linux-x64.tar.gz\n`),
43 );
44 }
45 if (beforeDownload) yield* beforeDownload;
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 stdout: JSON.stringify(result),
88 stderr: "",
89 code: ChildProcessSpawner.ExitCode(0),
90 timedOut: false,
91 stdoutTruncated: false,
92 stderrTruncated: false,
93 stdoutInvalidUtf8: false,
94 stderrInvalidUtf8: false,
95 };
96 }),
97 });
98 const launcher = ServiceLauncherClient.ServiceLauncherClient.of({
99 managed: options.managed ?? true,
100 requestUpdate:
101 options.requestUpdate ??
102 (() =>
103 Effect.sync(() => {
104 order.push("accept");
105 return "launcher-id";
106 })),
107 prepareTrial: Effect.undefined,
108 });
109 const config = yield* ServerConfig.ServerConfig.pipe(
110 Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
111 );
112 const selfUpdate = yield* ServerSelfUpdate.make().pipe(
113 Effect.provideService(ProcessRunner.ProcessRunner, runner),
114 Effect.provideService(ServiceLauncherClient.ServiceLauncherClient, launcher),
115 Effect.provideService(
116 DesktopAppUpdate.DesktopAppUpdate,
117 options.desktopAppUpdate ?? {
118 available: false,
119 run: () => Effect.die("unexpected desktop app update run"),
120 },
121 ),
122 Effect.provideService(HttpClient.HttpClient, releaseHttpClient(order, options.beforeDownload)),
123 Effect.provideService(HostProcess.Platform, "linux"),
124 Effect.provideService(HostProcess.Architecture, "x64"),
125 Effect.provide(ServerConfig.layer({ ...config, mode: options.mode ?? "web" })),
126 );
127 return { selfUpdate, order };
128});
129​
130it.layer(NodeServices.layer)("server self update", (it) => {
131 it.effect("marks running threads at the boot-service handoff", () =>
132 Effect.gen(function* () {
133 const events: string[] = [];
134 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
135 mode: "web",
136 selfUpdate: {
137 update: (_input, reportProgress = () => Effect.void) =>
138 reportProgress("downloading").pipe(
139 Effect.andThen(reportProgress("installing")),
140 Effect.as({
141 targetVersion: "1.1.0",
142 method: "boot-service" as const,
143 updateId: "update-id",
144 }),
145 ),
146 commitDesktopUpdate: () => Effect.never,
147 },
148 prepare: Effect.sync(() => {
149 events.push("prepare");
150 return [ThreadId.make("thread-running")];
151 }),
152 clear: () => Effect.sync(() => void events.push("clear")),
153 });
154​
155 yield* selfUpdate.update({ targetVersion: "1.1.0", continueRunningThreads: true }, (stage) =>
156 Effect.sync(() => void events.push(stage)),
157 );
158​
159 expect(events).toEqual(["downloading", "prepare", "installing"]);
160 }),
161 );
162​
163 it.effect("marks desktop threads only when the prepared update commits", () =>
164 Effect.gen(function* () {
165 const threadId = ThreadId.make("thread-running-desktop");
166 const events: string[] = [];
167 const commitError = new ServerSelfUpdateError({ reason: "install failed" });
168 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
169 mode: "desktop",
170 selfUpdate: {
171 update: (_input, reportProgress = () => Effect.void) =>
172 reportProgress("installing").pipe(
173 Effect.as({
174 targetVersion: "1.2.0",
175 method: "desktop-app" as const,
176 desktopUpdateToken: "desktop-token",
177 }),
178 ),
179 commitDesktopUpdate: () =>
180 Effect.sync(() => events.push("commit")).pipe(Effect.andThen(Effect.fail(commitError))),
181 },
182 prepare: Effect.sync(() => {
183 events.push("prepare");
184 return [threadId];
185 }),
186 clear: (threadIds) => Effect.sync(() => void events.push(`clear:${threadIds.join(",")}`)),
187 });
188​
189 yield* selfUpdate.update({ targetVersion: "1.2.0", continueRunningThreads: true }, (stage) =>
190 Effect.sync(() => void events.push(stage)),
191 );
192 expect(events).toEqual(["installing"]);
193 expect(yield* selfUpdate.commitDesktopUpdate("desktop-token").pipe(Effect.flip)).toBe(
194 commitError,
195 );
196 expect(events).toEqual(["installing", "prepare", "commit", `clear:${threadId}`]);
197 expect(yield* selfUpdate.commitDesktopUpdate("desktop-token").pipe(Effect.flip)).toBe(
198 commitError,
199 );
200 expect(events).toEqual([
201 "installing",
202 "prepare",
203 "commit",
204 `clear:${threadId}`,
205 "prepare",
206 "commit",
207 `clear:${threadId}`,
208 ]);
209 }),
210 );
211​
212 it.effect("keeps continuation markers after the boot-service handoff is accepted", () =>
213 Effect.gen(function* () {
214 const events: string[] = [];
215 const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
216 mode: "web",
217 selfUpdate: {
218 update: (
219 _input,
220 reportProgress = () => Effect.void,
221 onHandoffAccepted = () => Effect.void,
222 ) =>
223 reportProgress("installing").pipe(
224 Effect.andThen(onHandoffAccepted()),
225 Effect.andThen(Effect.interrupt),
226 ),
227 commitDesktopUpdate: () => Effect.never,
228 },
229 prepare: Effect.sync(() => {
230 events.push("prepare");
231 return [ThreadId.make("thread-accepted-boot-handoff")];
232 }),
233 clear: () => Effect.sync(() => void events.push("clear")),
234 });
235​
236 const exit = yield* selfUpdate
237 .update({ targetVersion: "1.1.0", continueRunningThreads: true })
238 .pipe(Effect.exit);
239​
240 expect(exit._tag).toBe("Failure");
241 expect(events).toEqual(["prepare"]);
242 }),
243 );
244​
245 it.effect("clears continuation markers for mixed failure and interrupt causes", () =>
246 Effect.gen(function* () {
247 const events: string[] = [];
248 const commitError = new ServerSelfUpdateError({ reason: "install failed" });
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: "failed-desktop-token",
257 }),
258 commitDesktopUpdate: (_requestId, onHandoffAccepted = () => Effect.void) =>
259 onHandoffAccepted().pipe(
260 Effect.andThen(
261 Effect.failCause(
262 Cause.fromReasons([
263 Cause.makeFailReason(commitError),
264 Cause.makeInterruptReason(),
265 ]),
266 ),
267 ),
268 ),
269 },
270 prepare: Effect.sync(() => [ThreadId.make("thread-failed-desktop-install")]),
271 clear: () => Effect.sync(() => void events.push("clear")),
272 });
273​
274 yield* selfUpdate.update({
275 targetVersion: "1.2.0",
276 continueRunningThreads: true,
277 });
278 const exit = yield* selfUpdate.commitDesktopUpdate("failed-desktop-token").pipe(Effect.exit);
279 expect(exit._tag).toBe("Failure");
280 if (exit._tag === "Failure") {
281 expect(Cause.hasInterrupts(exit.cause)).toBe(true);
282 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(false);
283 }
284 expect(events).toEqual(["clear"]);
285 }),
286 );
287​
288 // regression: #5181 make remote updates rollback-safe
289 it.effect("rejects invalid versions and desktop-managed servers before staging", () =>
290 Effect.gen(function* () {
291 const web = yield* makeHarness();
292 expect(
293 (yield* web.selfUpdate.update({ targetVersion: "latest" }).pipe(Effect.flip)).reason,
294 ).toBe("'latest' is not an exact t3 version.");
295 const desktop = yield* makeHarness({ mode: "desktop" });
296 expect(
297 (yield* desktop.selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason,
298 ).toContain("desktop app");
299 expect([...web.order, ...desktop.order]).toEqual([]);
300 }),
301 );
302​
303 it.effect("delegates desktop-managed updates to the desktop app when available", () =>
304 Effect.gen(function* () {
305 const stages: string[] = [];
306 const { selfUpdate, order } = yield* makeHarness({
307 mode: "desktop",
308 desktopAppUpdate: {
309 available: true,
310 run: (reportProgress) =>
311 reportProgress("downloading").pipe(
312 Effect.andThen(reportProgress("installing")),
313 Effect.as({ targetVersion: "1.2.0", method: "desktop-app" as const }),
314 ),
315 commit: () => Effect.never,
316 },
317 });
318 const result = yield* selfUpdate.update({ targetVersion: "1.1.0" }, (stage) =>
319 Effect.sync(() => void stages.push(stage)),
320 );
321 expect(result).toEqual({ targetVersion: "1.2.0", method: "desktop-app" });
322 expect(stages).toEqual(["downloading", "installing"]);
323 expect(order).toEqual([]);
324 }),
325 );
326​
327 it.effect("allows only one update at a time", () =>
328 Effect.gen(function* () {
329 const requested = yield* Deferred.make<void>();
330 const accepted = yield* Deferred.make<string>();
331 const { selfUpdate } = yield* makeHarness({
332 requestUpdate: () =>
333 Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(accepted))),
334 });
335 const first = yield* Effect.forkChild(selfUpdate.update({ targetVersion: "1.1.0" }), {
336 startImmediately: true,
337 });
338 yield* Deferred.await(requested);
339 expect((yield* selfUpdate.update({ targetVersion: "1.1.1" }).pipe(Effect.flip)).reason).toBe(
340 "A server update is already in progress.",
341 );
342 yield* Deferred.succeed(accepted, "launcher-id");
343 expect((yield* Fiber.join(first)).updateId).toBe("launcher-id");
344 }),
345 );
346​
347 it.effect("keeps preparing after the progress stream closes", () =>
348 Effect.gen(function* () {
349 const releaseDownload = yield* Deferred.make<void>();
350 const sawDownloading = yield* Deferred.make<void>();
351 const accepted = yield* Deferred.make<void>();
352 const { selfUpdate, order } = yield* makeHarness({
353 beforeDownload: Deferred.await(releaseDownload),
354 requestUpdate: () =>
355 Effect.sync(() => {
356 order.push("accept");
357 }).pipe(Effect.andThen(Deferred.succeed(accepted, undefined)), Effect.as("launcher-id")),
358 });
359​
360 const consumed = yield* ServerSelfUpdate.updateProgressStream(selfUpdate, {
361 targetVersion: "1.1.0",
362 }).pipe(
363 Stream.tap((event) =>
364 event.type === "progress" && event.stage === "downloading"
365 ? Deferred.succeed(sawDownloading, undefined)
366 : Effect.void,
367 ),
368 Stream.runDrain,
369 Effect.forkChild,
370 );
371​
372 yield* Deferred.await(sawDownloading);
373 // The socket drop ends the stream. The download is still held.
374 yield* Fiber.interrupt(consumed);
375 expect((yield* selfUpdate.update({ targetVersion: "1.2.0" }).pipe(Effect.flip)).reason).toBe(
376 "A server update is already in progress.",
377 );
378​
379 yield* Deferred.succeed(releaseDownload, undefined);
380 // `installing` is offered only after the stream queue has shut down.
381 yield* Deferred.await(accepted);
382 expect(order).toEqual(["download", "extract", "preflight", "accept"]);
383 expect((yield* selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason).toBe(
384 "A server update is already in progress.",
385 );
386 }),
387 );
388});