Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import { ServerAutomaticUpdateDeferredError, ServerSelfUpdateError } from "@t3tools/contracts";
4import { HostProcessExecutablePath } from "@t3tools/shared/hostProcess";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Fiber from "effect/Fiber";
9import * as Path from "effect/Path";
10import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
11
12import * as ServerConfig from "../config.ts";
13import * as ProcessRunner from "../processRunner.ts";
14import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
15import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
16import * as ServerSelfUpdate from "./selfUpdate.ts";
17
18interface HarnessOptions {
19 readonly mode?: "web" | "desktop";
20 readonly managed?: boolean;
21 readonly preflight?: "ready" | "blocked";
22 readonly automaticUpdateIdle?: (
23 order: string[],
24 targetVersion: string,
25 ) => Effect.Effect<void, ServerSelfUpdateError | ServerAutomaticUpdateDeferredError>;
26 readonly install?: (order: string[]) => Effect.Effect<void>;
27 readonly requestUpdate?: ServiceLauncherClient.ServiceLauncherClient["Service"]["requestUpdate"];
28}
29
30const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
31 options: HarnessOptions = {},
32) {
33 const fs = yield* FileSystem.FileSystem;
34 const path = yield* Path.Path;
35 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
36 const order: string[] = [];
37 const runner = ProcessRunner.ProcessRunner.of({
38 run: (input) =>
39 Effect.gen(function* () {
40 if (input.command === "npm") {
41 order.push("install");
42 yield* options.install?.(order) ?? Effect.void;
43 const prefix = input.args[input.args.indexOf("--prefix") + 1];
44 if (prefix === undefined) return yield* Effect.die("missing npm prefix");
45 const entry = path.join(prefix, "node_modules", "t3", "dist", "bin.mjs");
46 yield* fs.makeDirectory(path.dirname(entry), { recursive: true }).pipe(Effect.orDie);
47 yield* fs.writeFileString(entry, "export {};\n").pipe(Effect.orDie);
48 return {
49 stdout: "",
50 stderr: "",
51 code: ChildProcessSpawner.ExitCode(0),
52 timedOut: false,
53 stdoutTruncated: false,
54 stderrTruncated: false,
55 stdoutInvalidUtf8: false,
56 stderrInvalidUtf8: false,
57 };
58 }
59 order.push("preflight");
60 const result =
61 options.preflight === "blocked"
62 ? { status: "blocked", version: "1.1.0", reason: "local update required" }
63 : {
64 status: "ready",
65 version: "1.1.0",
66 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
67 };
68 return {
69 // @effect-diagnostics-next-line preferSchemaOverJson:off - fake child-process stdout.
70 stdout: JSON.stringify(result),
71 stderr: "",
72 code: ChildProcessSpawner.ExitCode(0),
73 timedOut: false,
74 stdoutTruncated: false,
75 stderrTruncated: false,
76 stdoutInvalidUtf8: false,
77 stderrInvalidUtf8: false,
78 };
79 }),
80 });
81 const launcher = ServiceLauncherClient.ServiceLauncherClient.of({
82 managed: options.managed ?? true,
83 requestUpdate:
84 options.requestUpdate ??
85 (() =>
86 Effect.sync(() => {
87 order.push("accept");
88 return "launcher-id";
89 })),
90 prepareTrial: Effect.sync((): undefined => undefined),
91 });
92 const config = yield* ServerConfig.ServerConfig.pipe(
93 Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
94 );
95 const selfUpdate = yield* ServerSelfUpdate.make().pipe(
96 Effect.provideService(ProcessRunner.ProcessRunner, runner),
97 Effect.provideService(ServiceLauncherClient.ServiceLauncherClient, launcher),
98 Effect.provideService(HostProcessExecutablePath, "/usr/bin/node"),
99 Effect.provideService(
100 ServerSelfUpdate.ServerSelfUpdateIdleCheck,
101 ServerSelfUpdate.ServerSelfUpdateIdleCheck.of({
102 assertIdle: (targetVersion) =>
103 options.automaticUpdateIdle?.(order, targetVersion) ?? Effect.void,
104 }),
105 ),
106 Effect.provide(ServerConfig.layer({ ...config, mode: options.mode ?? "web" })),
107 );
108 return { selfUpdate, order };
109});
110
111it.layer(NodeServices.layer)("server self update", (it) => {
112 it.effect("stages and preflights before asking the launcher for an update ID", () =>
113 Effect.gen(function* () {
114 const { selfUpdate, order } = yield* makeHarness();
115 expect(yield* selfUpdate.update({ targetVersion: "1.1.0" })).toEqual({
116 targetVersion: "1.1.0",
117 method: "boot-service",
118 updateId: "launcher-id",
119 });
120 expect(order).toEqual(["install", "preflight", "accept"]);
121 }),
122 );
123
124 it.effect("rejects invalid versions and desktop-managed servers before staging", () =>
125 Effect.gen(function* () {
126 const web = yield* makeHarness();
127 expect(
128 (yield* web.selfUpdate.update({ targetVersion: "latest" }).pipe(Effect.flip)).reason,
129 ).toBe("'latest' is not an exact t3 version.");
130 const desktop = yield* makeHarness({ mode: "desktop" });
131 expect(
132 (yield* desktop.selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason,
133 ).toContain("desktop app");
134 expect([...web.order, ...desktop.order]).toEqual([]);
135 }),
136 );
137
138 it.effect("preserves the preflight refusal reason", () =>
139 Effect.gen(function* () {
140 const { selfUpdate } = yield* makeHarness({ preflight: "blocked" });
141 expect((yield* selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason).toBe(
142 "local update required",
143 );
144 }),
145 );
146
147 it.effect("rejects automatic downgrades before staging", () =>
148 Effect.gen(function* () {
149 const { selfUpdate, order } = yield* makeHarness();
150 const error = yield* selfUpdate
151 .update({ targetVersion: "0.0.1", automatic: true })
152 .pipe(Effect.flip);
153
154 expect(error.reason).toContain("newer version");
155 expect(order).toEqual([]);
156 }),
157 );
158
159 it.effect("suppresses repeated automatic attempts after failure until a manual retry", () =>
160 Effect.gen(function* () {
161 let requests = 0;
162 const { selfUpdate } = yield* makeHarness({
163 requestUpdate: () =>
164 Effect.sync(() => {
165 requests += 1;
166 }).pipe(
167 Effect.andThen(
168 Effect.fail(
169 new ServiceLauncherClient.ServiceLauncherClientError({ operation: "send" }),
170 ),
171 ),
172 ),
173 });
174
175 yield* selfUpdate.update({ targetVersion: "1.1.0", automatic: true }).pipe(Effect.flip);
176 yield* selfUpdate.update({ targetVersion: "1.1.0", automatic: true }).pipe(Effect.flip);
177 expect(requests).toBe(1);
178
179 yield* selfUpdate.update({ targetVersion: "1.2.0" }).pipe(Effect.flip);
180 expect(requests).toBe(1);
181 yield* selfUpdate.update({ targetVersion: "1.1.0", automatic: true }).pipe(Effect.flip);
182 expect(requests).toBe(1);
183
184 yield* selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip);
185 expect(requests).toBe(2);
186 }),
187 );
188
189 it.effect("does not wedge updates when a manual retry is interrupted", () =>
190 Effect.gen(function* () {
191 const retryStarted = yield* Deferred.make<void>();
192 const releaseRetry = yield* Deferred.make<void>();
193 let requests = 0;
194 const { selfUpdate } = yield* makeHarness({
195 requestUpdate: () =>
196 Effect.sync(() => {
197 requests += 1;
198 }).pipe(
199 Effect.andThen(
200 Effect.fail(
201 new ServiceLauncherClient.ServiceLauncherClientError({ operation: "send" }),
202 ),
203 ),
204 ),
205 });
206
207 yield* selfUpdate.update({ targetVersion: "1.1.0", automatic: true }).pipe(Effect.flip);
208 const retryFiber = yield* selfUpdate
209 .update({ targetVersion: "1.1.0" }, () =>
210 Deferred.succeed(retryStarted, undefined).pipe(
211 Effect.andThen(Deferred.await(releaseRetry)),
212 ),
213 )
214 .pipe(Effect.forkChild);
215 yield* Deferred.await(retryStarted);
216 const interruptFiber = yield* Fiber.interrupt(retryFiber).pipe(Effect.forkChild);
217 yield* Deferred.succeed(releaseRetry, undefined);
218 yield* Fiber.join(interruptFiber);
219
220 yield* selfUpdate.update({ targetVersion: "1.1.0", automatic: true }).pipe(Effect.flip);
221 expect(requests).toBe(1);
222 yield* selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip);
223 expect(requests).toBe(2);
224 }),
225 );
226
227 it.effect("rechecks automatic updates after staging and before activation", () =>
228 Effect.gen(function* () {
229 const { selfUpdate, order } = yield* makeHarness({
230 automaticUpdateIdle: (order, targetVersion) =>
231 Effect.sync(() => order.push("idle-check")).pipe(
232 Effect.andThen(
233 new ServerAutomaticUpdateDeferredError({
234 reason: "new work started while downloading",
235 targetVersion,
236 }),
237 ),
238 ),
239 });
240 const error = yield* selfUpdate
241 .update({ targetVersion: "1.1.0", automatic: true })
242 .pipe(Effect.flip);
243
244 expect(error.reason).toContain("new work started");
245 expect(order).toEqual(["install", "preflight", "idle-check"]);
246 }),
247 );
248
249 it.effect("keeps admission closed if an automatic update caller disconnects during handoff", () =>
250 Effect.gen(function* () {
251 const requestStarted = yield* Deferred.make<void>();
252 const releaseRequest = yield* Deferred.make<void>();
253 const { selfUpdate, order } = yield* makeHarness({
254 requestUpdate: () =>
255 Deferred.succeed(requestStarted, undefined).pipe(
256 Effect.andThen(Deferred.await(releaseRequest)),
257 Effect.as("launcher-id"),
258 ),
259 });
260 const updateFiber = yield* selfUpdate
261 .update({ targetVersion: "1.1.0", automatic: true })
262 .pipe(Effect.forkChild);
263 yield* Deferred.await(requestStarted);
264 const interruptFiber = yield* Fiber.interrupt(updateFiber).pipe(Effect.forkChild);
265 yield* Effect.yieldNow;
266
267 const duringHandoff = yield* selfUpdate
268 .withCommandAdmission(Effect.succeed("started"))
269 .pipe(Effect.flip);
270 expect(duringHandoff.reason).toContain("cannot start new work");
271
272 yield* Deferred.succeed(releaseRequest, undefined);
273 yield* Fiber.join(interruptFiber);
274 const afterAcceptance = yield* selfUpdate
275 .withCommandAdmission(Effect.succeed("started"))
276 .pipe(Effect.flip);
277 expect(afterAcceptance.reason).toContain("cannot start new work");
278 expect(order).toEqual(["install", "preflight"]);
279 }),
280 );
281
282 it.effect("allows automatic update staging to be interrupted before handoff", () =>
283 Effect.gen(function* () {
284 const installStarted = yield* Deferred.make<void>();
285 const releaseInstall = yield* Deferred.make<void>();
286 let installs = 0;
287 const { selfUpdate, order } = yield* makeHarness({
288 install: () => {
289 installs += 1;
290 return installs === 1
291 ? Deferred.succeed(installStarted, undefined).pipe(
292 Effect.andThen(Deferred.await(releaseInstall)),
293 )
294 : Effect.void;
295 },
296 });
297 const updateFiber = yield* selfUpdate
298 .update({ targetVersion: "1.1.0", automatic: true })
299 .pipe(Effect.forkChild);
300 yield* Deferred.await(installStarted);
301 const interruptFiber = yield* Fiber.interrupt(updateFiber).pipe(Effect.forkChild);
302 yield* Deferred.succeed(releaseInstall, undefined);
303 yield* Fiber.join(interruptFiber);
304
305 expect(order).toEqual(["install"]);
306 expect(yield* selfUpdate.update({ targetVersion: "1.1.0", automatic: true })).toEqual({
307 targetVersion: "1.1.0",
308 method: "boot-service",
309 updateId: "launcher-id",
310 });
311 }),
312 );
313
314 it.effect("blocks new commands after an automatic handoff is accepted", () =>
315 Effect.gen(function* () {
316 const { selfUpdate } = yield* makeHarness();
317 yield* selfUpdate.update({ targetVersion: "1.1.0", automatic: true });
318
319 const error = yield* selfUpdate
320 .withCommandAdmission(Effect.succeed("started"))
321 .pipe(Effect.flip);
322 expect(error.reason).toContain("cannot start new work");
323 }),
324 );
325
326 it.effect("keeps command admission open for manual updates", () =>
327 Effect.gen(function* () {
328 const { selfUpdate } = yield* makeHarness();
329 yield* selfUpdate.update({ targetVersion: "1.1.0" });
330 expect(yield* selfUpdate.withCommandAdmission(Effect.succeed("started"))).toBe("started");
331 }),
332 );
333
334 it.effect("allows only one update at a time", () =>
335 Effect.gen(function* () {
336 const requested = yield* Deferred.make<void>();
337 const accepted = yield* Deferred.make<string>();
338 const { selfUpdate } = yield* makeHarness({
339 requestUpdate: () =>
340 Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(accepted))),
341 });
342 const first = yield* Effect.forkChild(selfUpdate.update({ targetVersion: "1.1.0" }), {
343 startImmediately: true,
344 });
345 yield* Deferred.await(requested);
346 expect((yield* selfUpdate.update({ targetVersion: "1.1.1" }).pipe(Effect.flip)).reason).toBe(
347 "A server update is already in progress.",
348 );
349 yield* Deferred.succeed(accepted, "launcher-id");
350 expect((yield* Fiber.join(first)).updateId).toBe("launcher-id");
351 }),
352 );
353});