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

DesktopBackendManager.test.ts

1,047 lines41.7 KB

1import {
2 SERVER_EXIT_CODE_MANAGED_POLICY,
3 SERVER_EXIT_CODE_STATE_DIR_OWNED,
4 DesktopBackendBootstrap,
5 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
6 DesktopTelemetryControlMessage,
7} from "@t3tools/contracts";
8import {
9 DATABASE_MIGRATION_PROGRESS_MESSAGE,
10 DATABASE_MIGRATIONS_FINISHED_MESSAGE,
11 DATABASE_MIGRATIONS_STARTED_MESSAGE,
12} from "@t3tools/shared/databaseMigrationLog";
13import { assert, describe, it } from "@effect/vitest";
14import * as Clock from "effect/Clock";
15import * as Deferred from "effect/Deferred";
16import * as Duration from "effect/Duration";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Fiber from "effect/Fiber";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as PlatformError from "effect/PlatformError";
23import * as Queue from "effect/Queue";
24import * as Ref from "effect/Ref";
25import * as Schema from "effect/Schema";
26import * as Sink from "effect/Sink";
27import * as Scope from "effect/Scope";
28import * as Stream from "effect/Stream";
29import * as TestClock from "effect/testing/TestClock";
30import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
31import { ChildProcess, ChildProcessSpawner } from "effect/process";
32​
33import * as DesktopBackendManager from "./DesktopBackendManager.ts";
34import * as DesktopObservability from "../app/DesktopObservability.ts";
35import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
36import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
37import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
38​
39const decodeDesktopBackendBootstrap = Schema.decodeEffect(
40 Schema.fromJsonString(DesktopBackendBootstrap),
41);
42const encodeDesktopTelemetryControl = Schema.encodeSync(
43 Schema.fromJsonString(DesktopTelemetryControlMessage),
44);
45​
46const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
47 executablePath: "/electron",
48 args: ["/server/bin.mjs", "--bootstrap-fd", "3"],
49 entryPath: "/server/bin.mjs",
50 cwd: "/server",
51 env: { ELECTRON_RUN_AS_NODE: "1" },
52 bootstrap: {
53 mode: "desktop",
54 noBrowser: true,
55 port: 3773,
56 t3Home: "/tmp/t3",
57 host: "127.0.0.1",
58 desktopBootstrapToken: "token",
59 tailscaleServeEnabled: false,
60 tailscaleServePort: 443,
61 desktopTelemetryFd: 4,
62 desktopTelemetryControlFd: 5,
63 },
64 bootstrapDelivery: "fd3",
65 extendEnv: true,
66 httpBaseUrl: new URL("http://127.0.0.1:3773"),
67 captureOutput: true,
68 preflightFailure: Option.none(),
69};
70​
71const configWithObservability: DesktopBackendBootstrapValue = {
72 ...baseConfig.bootstrap,
73 tailscaleServeEnabled: true,
74 desktopTelemetryFd: 4,
75 otlpTracesUrl: "http://127.0.0.1:4318/v1/traces",
76};
77​
78const readyLine = encodeDesktopTelemetryControl({ version: 1, type: "serverReady" });
79const readyControlChannel: ChildProcessSpawner.ChildProcessHandle["getOutputFd"] = (fd) =>
80 fd === 5 ? Stream.encodeText(Stream.make(`${readyLine}\n`)) : Stream.empty;
81​
82// WSL backends get their bootstrap on stdin and have no control channel, so readiness is polled.
83const { desktopTelemetryControlFd: _controlFd, ...pollingBootstrap } = baseConfig.bootstrap;
84const pollingConfig: DesktopBackendManager.DesktopBackendStartConfig = {
85 ...baseConfig,
86 bootstrap: pollingBootstrap,
87 bootstrapDelivery: "stdin",
88};
89​
90function makeProcess(options?: {
91 readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
92 readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
93 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
94 readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
95 readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
96}): ChildProcessSpawner.ChildProcessHandle {
97 return ChildProcessSpawner.makeHandle({
98 pid: ChildProcessSpawner.ProcessId(123),
99 stdout: options?.stdout ?? Stream.empty,
100 stderr: options?.stderr ?? Stream.empty,
101 all: Stream.merge(options?.stdout ?? Stream.empty, options?.stderr ?? Stream.empty),
102 exitCode: options?.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(0)),
103 isRunning: Effect.succeed(false),
104 kill: options?.kill ?? (() => Effect.void),
105 stdin: Sink.drain,
106 getInputFd: () => Sink.drain,
107 getOutputFd: options?.getOutputFd ?? readyControlChannel,
108 unref: Effect.succeed(Effect.void),
109 });
111​
112function responseForRequest(
113 request: HttpClientRequest.HttpClientRequest,
114 status: number,
115): HttpClientResponse.HttpClientResponse {
116 return HttpClientResponse.fromWeb(request, new Response(null, { status }));
118​
119function layerHttpClient(
120 handler: (
121 request: HttpClientRequest.HttpClientRequest,
122 ) => Effect.Effect<HttpClientResponse.HttpClientResponse>,
123) {
124 return Layer.succeed(
125 HttpClient.HttpClient,
126 HttpClient.make((request) => handler(request)),
127 );
129​
130const layerHealthyHttpClient = layerHttpClient((request) =>
131 Effect.succeed(responseForRequest(request, 200)),
132);
133​
134function decodeBootstrap(raw: string) {
135 return decodeDesktopBackendBootstrap(raw);
137​
138interface MakeInstanceInput {
139 readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
140 readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
141 readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
142 readonly onReady?: Effect.Effect<void>;
143 readonly onShutdown?: Effect.Effect<void>;
144 readonly onStateDirOwned?: Effect.Effect<void>;
145 readonly onMigrationProgress?: (
146 progress: { current: number; total: number } | null,
147 ) => Effect.Effect<void>;
148 readonly onStartupFailure?: (
149 failure: DesktopBackendManager.BackendStartupFailure,
150 ) => Effect.Effect<void>;
151 readonly onPreflightFailed?: (
152 failure: DesktopBackendManager.PreflightFailure,
153 ) => Effect.Effect<boolean>;
154 readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
155 readonly configResolve?: Effect.Effect<
156 DesktopBackendManager.DesktopBackendStartConfig,
157 PlatformError.PlatformError
158 >;
159 readonly desktopTelemetryStream?: Stream.Stream<Uint8Array>;
160 readonly desktopTelemetryPublisher?: Partial<
161 DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
162 >;
163 readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
165​
166function makeTestInstance(input: MakeInstanceInput) {
167 const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
168 beginSession: () => Effect.void,
169 writeOutputChunk: () => Effect.void,
170 persistFailureSnapshot: () => Effect.void,
171 persistFailure: () => Effect.void,
172 discardSession: Effect.void,
173 ...input.backendOutputLog,
174 };
175 const layerServices = Layer.mergeAll(
176 FileSystem.layerNoop({
177 exists: () => Effect.succeed(true),
178 }),
179 input.spawnerLayer,
180 input.httpClientLayer ?? layerHealthyHttpClient,
181 Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
182 forInstance: () => Effect.succeed(stubLog),
183 } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
184 Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
185 latest: Effect.succeedNone,
186 changes: Stream.empty,
187 encoded: input.desktopTelemetryStream ?? Stream.empty,
188 handleControlForSource: () => Effect.void,
189 removeControlSource: () => Effect.void,
190 publishUpdateReport: () => Effect.void,
191 updateRequests: Stream.empty,
192 updateCommits: Stream.empty,
193 updateCancellations: Stream.empty,
194 ...input.desktopTelemetryPublisher,
195 }),
196 DesktopBrowserHost.layer,
197 DesktopWslEnvironment.layerTest(
198 input.pruneRuntimes === undefined ? {} : { pruneRuntimes: input.pruneRuntimes },
199 ),
200 );
201​
202 const instance = DesktopBackendManager.makeBackendInstance({
203 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
204 label: Effect.succeed("Windows"),
205 configResolve: input.configResolve ?? Effect.succeed(input.config ?? baseConfig),
206 ...(input.onReady ? { onReady: () => input.onReady! } : {}),
207 ...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}),
208 ...(input.onStateDirOwned ? { onStateDirOwned: () => input.onStateDirOwned! } : {}),
209 ...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}),
210 ...(input.onStartupFailure ? { onStartupFailure: input.onStartupFailure } : {}),
211 ...(input.onMigrationProgress ? { onMigrationProgress: input.onMigrationProgress } : {}),
212 });
213​
214 return instance.pipe(Effect.provide(layerServices));
216​
217describe("DesktopBackendManager", () => {
218 it.effect("notifies readiness waiters on HTTP readiness and stop without clock advancement", () =>
219 Effect.gen(function* () {
220 const probe = yield* Deferred.make<void>();
221 const ready = yield* Deferred.make<void>();
222 const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
223 const instance = yield* makeTestInstance({
224 config: pollingConfig,
225 spawnerLayer: Layer.succeed(
226 ChildProcessSpawner.ChildProcessSpawner,
227 ChildProcessSpawner.make(() =>
228 Effect.acquireRelease(
229 Effect.succeed(
230 makeProcess({
231 exitCode: Deferred.await(exit),
232 kill: () =>
233 Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid),
234 }),
235 ),
236 () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
237 ),
238 ),
239 ),
240 httpClientLayer: Layer.succeed(
241 HttpClient.HttpClient,
242 HttpClient.make((request) =>
243 Deferred.succeed(probe, undefined).pipe(
244 Effect.andThen(Deferred.await(ready)),
245 Effect.as(HttpClientResponse.fromWeb(request, new Response("{}"))),
246 ),
247 ),
248 ),
249 });
250 yield* instance.start;
251 yield* Deferred.await(probe);
252 const waiter = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild);
253 yield* Deferred.succeed(ready, undefined);
254 assert.isTrue(yield* Fiber.join(waiter));
255 yield* instance.stop();
256 assert.isFalse(yield* instance.waitForReady(Duration.seconds(15)));
257 }),
258 );
259​
260 it.effect("a polled backend is ready only once its listener answers as this launch", () =>
261 Effect.gen(function* () {
262 const answersAsLaunch = yield* Ref.make(false);
263 const probedUrls = yield* Ref.make<ReadonlyArray<string>>([]);
264 const ready = yield* Deferred.make<void>();
265 const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
266 const instance = yield* makeTestInstance({
267 config: {
268 ...pollingConfig,
269 readinessProbe: Effect.succeed({
270 path: "/launch-proof?challenge=abc",
271 accept: (body: string) => Effect.succeed(body === "proof-for-abc"),
272 }),
273 },
274 onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
275 spawnerLayer: Layer.succeed(
276 ChildProcessSpawner.ChildProcessSpawner,
277 ChildProcessSpawner.make(() =>
278 Effect.acquireRelease(
279 Effect.succeed(makeProcess({ exitCode: Deferred.await(exit) })),
280 () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
281 ),
282 ),
283 ),
284 httpClientLayer: layerHttpClient((request) =>
285 Ref.update(probedUrls, (urls) => [...urls, request.url]).pipe(
286 Effect.andThen(Ref.get(answersAsLaunch)),
287 Effect.map((asLaunch) =>
288 HttpClientResponse.fromWeb(
289 request,
290 new Response(asLaunch ? "proof-for-abc" : "{}", { status: 200 }),
291 ),
292 ),
293 ),
294 ),
295 });
296 yield* instance.start;
297 yield* TestClock.adjust(Duration.seconds(5));
298​
299 assert.isFalse(yield* Deferred.isDone(ready));
300 assert.isFalse((yield* instance.snapshot).ready);
301 assert.deepStrictEqual(
302 [...new Set(yield* Ref.get(probedUrls))],
303 ["http://127.0.0.1:3773/launch-proof?challenge=abc"],
304 );
305​
306 yield* Ref.set(answersAsLaunch, true);
307 yield* TestClock.adjust(Duration.seconds(1));
308​
309 assert.isTrue(yield* Deferred.isDone(ready));
310 yield* instance.stop();
311 }),
312 );
313​
314 it.effect("notices a WSL backend soon after it listens despite slow refused connects", () =>
315 Effect.gen(function* () {
316 const ready = yield* Deferred.make<void>();
317 const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
318 const instance = yield* makeTestInstance({
319 config: { ...pollingConfig, httpBaseUrl: new URL("http://172.20.84.98:3773") },
320 onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
321 spawnerLayer: Layer.succeed(
322 ChildProcessSpawner.ChildProcessSpawner,
323 ChildProcessSpawner.make(() =>
324 Effect.acquireRelease(
325 Effect.succeed(makeProcess({ exitCode: Deferred.await(exit) })),
326 () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
327 ),
328 ),
329 ),
330 // Before the server listens at 300 ms, each refused connect takes a second to fail.
331 httpClientLayer: layerHttpClient((request) =>
332 Clock.currentTimeMillis.pipe(
333 Effect.flatMap((now) =>
334 now < 300
335 ? Effect.sleep(Duration.seconds(1)).pipe(
336 Effect.as(responseForRequest(request, 503)),
337 )
338 : Effect.succeed(responseForRequest(request, 200)),
339 ),
340 ),
341 ),
342 });
343 yield* instance.start;
344 yield* TestClock.adjust(Duration.millis(600));
345​
346 assert.isTrue(yield* Deferred.isDone(ready));
347 yield* instance.stop();
348 }),
349 );
350​
351 it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
352 Effect.gen(function* () {
353 let spawnedCommand: ChildProcess.Command | undefined;
354 let bootstrapJson = "";
355 let telemetryJson = "";
356 let readyCount = 0;
357 const ready = yield* Deferred.make<void>();
358 const exited = yield* Queue.unbounded<void>();
359​
360 const layerSpawner = Layer.succeed(
361 ChildProcessSpawner.ChildProcessSpawner,
362 ChildProcessSpawner.make((command) =>
363 Effect.gen(function* () {
364 spawnedCommand = command;
365 if (command._tag === "StandardCommand") {
366 const fd3 = command.options.additionalFds?.fd3;
367 if (fd3?.type === "input" && fd3.stream) {
368 bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
369 }
370 const fd4 = command.options.additionalFds?.fd4;
371 if (fd4?.type === "input" && fd4.stream) {
372 telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString);
373 }
374 }
375​
376 return makeProcess({
377 exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
378 });
379 }),
380 ),
381 );
382​
383 const instance = yield* makeTestInstance({
384 config: {
385 ...baseConfig,
386 bootstrap: configWithObservability,
387 },
388 spawnerLayer: layerSpawner,
389 desktopTelemetryStream: Stream.encodeText(
390 Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'),
391 ),
392 onReady: Effect.sync(() => {
393 readyCount += 1;
394 }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
395 backendOutputLog: {
396 persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
397 },
398 });
399​
400 yield* instance.start;
401 yield* Queue.take(exited);
402​
403 assert.equal(readyCount, 1);
404 assert.isDefined(spawnedCommand);
405 if (spawnedCommand._tag !== "StandardCommand") {
406 throw new Error("Expected backend to spawn a standard command.");
407 }
408​
409 assert.equal(spawnedCommand.command, "/electron");
410 assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]);
411 assert.equal(spawnedCommand.options.cwd, "/server");
412 assert.equal(spawnedCommand.options.extendEnv, true);
413 assert.equal(spawnedCommand.options.stdout, "pipe");
414 assert.equal(spawnedCommand.options.stderr, "pipe");
415 assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
416 assert.isDefined(spawnedCommand.options.forceKillAfter);
417 assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
418 assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
419 assert.equal(
420 Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
421 5_000,
422 );
423​
424 assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
425 assert.equal(
426 telemetryJson,
427 '{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n',
428 );
429 }),
430 );
431​
432 it.effect("delivers fd3 bootstrap while ownership recording is pending", () =>
433 Effect.gen(function* () {
434 const recording = yield* Deferred.make<void>();
435 const finishRecording = yield* Deferred.make<void>();
436 const receivedBootstrap = yield* Deferred.make<Option.Option<string>>();
437 const exitObserved = yield* Deferred.make<void>();
438 const childExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
439 const forgotten = yield* Ref.make(false);
440 const layerSpawner = Layer.succeed(
441 ChildProcessSpawner.ChildProcessSpawner,
442 ChildProcessSpawner.make(
443 Effect.fnUntraced(function* (command) {
444 if (!ChildProcess.isStandardCommand(command)) {
445 return yield* Effect.die("Expected a standard local backend command");
446 }
447 const fd = command.options.additionalFds?.fd3;
448 if (fd?.type !== "input" || fd.stream === undefined) {
449 return yield* Effect.die("Expected a bootstrap stream on fd 3");
450 }
451 yield* fd.stream.pipe(
452 Stream.decodeText(),
453 Stream.mkString,
454 Effect.timeoutOption(Duration.seconds(1)),
455 Effect.flatMap((payload) => Deferred.succeed(receivedBootstrap, payload)),
456 Effect.forkScoped,
457 );
458 return makeProcess({ exitCode: Deferred.await(childExit) });
459 }),
460 ),
461 );
462 const run = yield* DesktopBackendManager.runBackendProcess({
463 ...baseConfig,
464 desktopTelemetryStream: Stream.empty,
465 onExitObserved: () => Deferred.succeed(exitObserved, undefined).pipe(Effect.asVoid),
466 trackProcess: () =>
467 Deferred.succeed(recording, undefined).pipe(
468 Effect.andThen(Deferred.await(finishRecording)),
469 Effect.as(Ref.set(forgotten, true)),
470 ),
471 }).pipe(Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)), Effect.forkChild);
472​
473 yield* Deferred.await(recording);
474 yield* TestClock.adjust(Duration.seconds(2));
475 const payload = yield* Deferred.await(receivedBootstrap);
476 assert.isTrue(Option.isSome(payload), "desktop bootstrap missed the reader deadline");
477 assert.deepEqual(yield* decodeBootstrap(Option.getOrThrow(payload)), baseConfig.bootstrap);
478 yield* Deferred.succeed(childExit, ChildProcessSpawner.ExitCode(0));
479 yield* Deferred.await(exitObserved);
480 assert.isFalse(yield* Ref.get(forgotten));
481 yield* Deferred.succeed(finishRecording, undefined);
482 yield* Fiber.join(run);
483 assert.isTrue(yield* Ref.get(forgotten));
484 }),
485 );
486​
487 it.effect("reports a SIGKILL exit without an exit code", () =>
488 Effect.gen(function* () {
489 const exitCause = PlatformError.systemError({
490 _tag: "Unknown",
491 module: "ChildProcess",
492 method: "exitCode",
493 cause: new Error("Process interrupted due to receipt of signal: 'SIGKILL'"),
494 });
495 const layerSpawner = Layer.succeed(
496 ChildProcessSpawner.ChildProcessSpawner,
497 ChildProcessSpawner.make(() =>
498 Effect.succeed(makeProcess({ exitCode: Effect.fail(exitCause) })),
499 ),
500 );
501​
502 const exit = yield* DesktopBackendManager.runBackendProcess({
503 ...baseConfig,
504 desktopTelemetryStream: Stream.empty,
505 }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)));
506​
507 assert.deepEqual(exit, { code: Option.none(), reason: "killed by SIGKILL" });
508 }),
509 );
510​
511 it.effect("reports child exit before waiting for trailing output to drain", () =>
512 Effect.gen(function* () {
513 const exitObserved = yield* Deferred.make<void>();
514 const finishOutputDrain = yield* Deferred.make<void>();
515 const layerSpawner = Layer.succeed(
516 ChildProcessSpawner.ChildProcessSpawner,
517 ChildProcessSpawner.make(() =>
518 Effect.succeed(
519 makeProcess({
520 stdout: Stream.fromEffect(
521 Deferred.await(finishOutputDrain).pipe(
522 Effect.as(new TextEncoder().encode("trailing output\n")),
523 ),
524 ),
525 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
526 }),
527 ),
528 ),
529 );
530​
531 const runFiber = yield* DesktopBackendManager.runBackendProcess({
532 ...baseConfig,
533 desktopTelemetryStream: Stream.empty,
534 onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid),
535 }).pipe(Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)), Effect.forkChild);
536​
537 yield* Deferred.await(exitObserved);
538 assert.isUndefined(runFiber.pollUnsafe());
539​
540 yield* Deferred.succeed(finishOutputDrain, void 0);
541 assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1);
542 }),
543 );
544​
545 it.effect("a backend with a control channel is ready only once it says so there", () =>
546 Effect.gen(function* () {
547 const announce = yield* Deferred.make<void>();
548 const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
549 const instance = yield* makeTestInstance({
550 spawnerLayer: Layer.succeed(
551 ChildProcessSpawner.ChildProcessSpawner,
552 ChildProcessSpawner.make(() =>
553 Effect.succeed(
554 makeProcess({
555 getOutputFd: (fd) =>
556 fd === 5
557 ? Stream.fromEffect(Deferred.await(announce)).pipe(
558 Stream.flatMap(() => readyControlChannel(fd)),
559 )
560 : Stream.empty,
561 exitCode: Deferred.await(exit),
562 kill: () =>
563 Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid),
564 }),
565 ),
566 ),
567 ),
568 // An HTTP answer on the port is not the backend's own ready signal.
569 httpClientLayer: layerHealthyHttpClient,
570 });
571​
572 yield* instance.start;
573 const early = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild);
574 yield* TestClock.adjust(Duration.seconds(15));
575 assert.isFalse(yield* Fiber.join(early));
576​
577 yield* Deferred.succeed(announce, undefined);
578 assert.isTrue(yield* instance.waitForReady(Duration.seconds(15)));
579 }).pipe(Effect.scoped),
580 );
581​
582 it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
583 Effect.gen(function* () {
584 const handled = yield* Deferred.make<boolean>();
585 const controlMessage = encodeDesktopTelemetryControl({
586 version: 1,
587 type: "setDiagnosticsDemand",
588 enabled: true,
589 });
590 const layerSpawner = Layer.succeed(
591 ChildProcessSpawner.ChildProcessSpawner,
592 ChildProcessSpawner.make(() =>
593 Effect.succeed(
594 makeProcess({
595 getOutputFd: (fd) =>
596 fd === 5
597 ? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`))
598 : Stream.empty,
599 exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
600 }),
601 ),
602 ),
603 );
604 const instance = yield* makeTestInstance({
605 spawnerLayer: layerSpawner,
606 desktopTelemetryPublisher: {
607 handleControlForSource: (_sourceId, message) =>
608 message.type === "setDiagnosticsDemand"
609 ? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid)
610 : Effect.void,
611 },
612 });
613​
614 yield* instance.start;
615 assert.isTrue(yield* Deferred.await(handled));
616 }),
617 );
618​
619 it.effect("stops the scoped process with output still pending", () =>
620 Effect.gen(function* () {
621 let startCount = 0;
622 let closedCount = 0;
623 const closed = yield* Deferred.make<void>();
624 const teardownStarted = yield* Deferred.make<void>();
625 const finishTeardown = yield* Deferred.make<void>();
626 const startedPids = yield* Queue.unbounded<number>();
627 const ready = yield* Deferred.make<void>();
628 const backendReadyFlag = yield* Ref.make(false);
629 let shutdownCount = 0;
630 let persistedFailureCount = 0;
631 let discardedSessionCount = 0;
632 let removedTelemetrySources = 0;
633​
634 const layerSpawner = Layer.succeed(
635 ChildProcessSpawner.ChildProcessSpawner,
636 ChildProcessSpawner.make(() =>
637 Effect.gen(function* () {
638 const scope = yield* Scope.Scope;
639 startCount += 1;
640 yield* Queue.offer(startedPids, 123);
641 const close = Deferred.succeed(teardownStarted, undefined).pipe(
642 Effect.andThen(Deferred.await(finishTeardown)),
643 Effect.andThen(
644 Effect.sync(() => {
645 closedCount += 1;
646 }),
647 ),
648 Effect.andThen(Deferred.succeed(closed, void 0)),
649 Effect.asVoid,
650 );
651​
652 yield* Scope.addFinalizer(scope, close);
653​
654 return makeProcess({
655 stdout: Stream.never,
656 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
657 kill: () => close,
658 });
659 }),
660 ),
661 );
662​
663 const instance = yield* makeTestInstance({
664 spawnerLayer: layerSpawner,
665 onReady: Ref.set(backendReadyFlag, true).pipe(
666 Effect.andThen(Deferred.succeed(ready, void 0)),
667 Effect.asVoid,
668 ),
669 onShutdown: Ref.set(backendReadyFlag, false).pipe(
670 Effect.andThen(
671 Effect.sync(() => {
672 shutdownCount += 1;
673 }),
674 ),
675 ),
676 backendOutputLog: {
677 persistFailure: () =>
678 Effect.sync(() => {
679 persistedFailureCount += 1;
680 }),
681 discardSession: Effect.sync(() => {
682 discardedSessionCount += 1;
683 }),
684 },
685 desktopTelemetryPublisher: {
686 removeControlSource: () =>
687 Effect.sync(() => {
688 removedTelemetrySources += 1;
689 }),
690 },
691 });
692 assert.isTrue(Option.isNone(yield* instance.currentConfig));
693​
694 yield* instance.start;
695 assert.equal(yield* Queue.take(startedPids), 123);
696 yield* Deferred.await(ready);
697 assert.isTrue(yield* Ref.get(backendReadyFlag));
698 assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
699​
700 const runningSnapshot = yield* instance.snapshot;
701 assert.equal(runningSnapshot.ready, true);
702 assert.deepEqual(runningSnapshot.activePid, Option.some(123));
703​
704 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
705 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
706 assert.isFalse(yield* Ref.get(backendReadyFlag));
707 assert.equal(shutdownCount, 1);
708 yield* Deferred.succeed(finishTeardown, undefined);
709 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
710 assert.equal(startCount, 1);
711 assert.equal(closedCount, 1);
712 assert.equal(persistedFailureCount, 0);
713 assert.equal(discardedSessionCount, 1);
714 assert.equal(removedTelemetrySources, 1);
715​
716 const stoppedSnapshot = yield* instance.snapshot;
717 assert.isFalse(yield* Ref.get(backendReadyFlag));
718 assert.equal(shutdownCount, 1);
719 assert.equal(stoppedSnapshot.desiredRunning, false);
720 assert.equal(stoppedSnapshot.ready, false);
721 assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
722 }),
723 );
724​
725 it.effect("restarts when start is requested during stop teardown", () =>
726 Effect.gen(function* () {
727 const starts = yield* Queue.unbounded<number>();
728 const teardownStarted = yield* Deferred.make<void>();
729 const finishTeardown = yield* Deferred.make<void>();
730 let startCount = 0;
731​
732 const layerSpawner = Layer.succeed(
733 ChildProcessSpawner.ChildProcessSpawner,
734 ChildProcessSpawner.make(() =>
735 Effect.gen(function* () {
736 const scope = yield* Scope.Scope;
737 const closed = yield* Deferred.make<void>();
738 startCount += 1;
739 yield* Queue.offer(starts, startCount);
740 if (startCount === 1) {
741 yield* Scope.addFinalizer(
742 scope,
743 Deferred.succeed(teardownStarted, undefined).pipe(
744 Effect.andThen(Deferred.await(finishTeardown)),
745 Effect.andThen(Deferred.succeed(closed, undefined)),
746 Effect.asVoid,
747 ),
748 );
749 } else {
750 yield* Scope.addFinalizer(
751 scope,
752 Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
753 );
754 }
755 return makeProcess({
756 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
757 });
758 }),
759 ),
760 );
761​
762 const instance = yield* makeTestInstance({
763 spawnerLayer: layerSpawner,
764 httpClientLayer: layerHttpClient(() => Effect.never),
765 });
766​
767 yield* instance.start;
768 assert.equal(yield* Queue.take(starts), 1);
769​
770 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
771 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
772 yield* instance.start;
773 assert.equal((yield* instance.snapshot).desiredRunning, true);
774​
775 yield* Deferred.succeed(finishTeardown, undefined);
776 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
777 yield* TestClock.adjust(Duration.millis(500));
778​
779 assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
780 const restarted = yield* instance.snapshot;
781 assert.equal(restarted.desiredRunning, true);
782 assert.deepEqual(restarted.activePid, Option.some(123));
783 }).pipe(Effect.provide(TestClock.layer())),
784 );
785​
786 it.effect("reports state-directory ownership once without scheduling another backend", () =>
787 Effect.gen(function* () {
788 let startCount = 0;
789 const refused = yield* Deferred.make<void>();
790 const instance = yield* makeTestInstance({
791 spawnerLayer: Layer.succeed(
792 ChildProcessSpawner.ChildProcessSpawner,
793 ChildProcessSpawner.make(() =>
794 Effect.sync(() => {
795 startCount += 1;
796 return makeProcess({
797 exitCode: Effect.succeed(
798 ChildProcessSpawner.ExitCode(SERVER_EXIT_CODE_STATE_DIR_OWNED),
799 ),
800 });
801 }),
802 ),
803 ),
804 httpClientLayer: layerHttpClient(() => Effect.never),
805 onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid),
806 });
807 yield* instance.start;
808 yield* Deferred.await(refused);
809 const snapshot = yield* instance.snapshot;
810 assert.isFalse(snapshot.desiredRunning);
811 assert.isFalse(snapshot.restartScheduled);
812 yield* TestClock.adjust(Duration.minutes(1));
813 assert.equal(startCount, 1);
814 }).pipe(Effect.provide(TestClock.layer())),
815 );
816​
817 // A policy refusal is reported on the first exit, since retrying cannot fix it.
818 it.effect.each([
819 { code: 1, exits: 3, managedPolicy: false },
820 { code: SERVER_EXIT_CODE_MANAGED_POLICY, exits: 1, managedPolicy: true },
821 ])(
822 "reports exit $code with the server output after $exits exits",
823 ({ code, exits, managedPolicy }) =>
824 Effect.gen(function* () {
825 const message = `${DATABASE_MIGRATION_PROGRESS_MESSAGE} (1 of 3)\n progress: 1 of 3\nError: Cannot find module 'zod/v4' in /Users/René`;
826 const progress: Array<{ current: number; total: number } | null> = [];
827 let exitCount = 0;
828 const firstExit = yield* Deferred.make<void>();
829 const reports = yield* Queue.unbounded<{
830 readonly exitCount: number;
831 readonly failure: DesktopBackendManager.BackendStartupFailure;
832 }>();
833 const instance = yield* makeTestInstance({
834 spawnerLayer: Layer.succeed(
835 ChildProcessSpawner.ChildProcessSpawner,
836 ChildProcessSpawner.make(() =>
837 Effect.succeed(
838 makeProcess({
839 // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut
840 // lands inside the emoji's surrogate pair.
841 stderr: Stream.make(
842 new TextEncoder().encode(
843 `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`,
844 ),
845 new Uint8Array([0xc3]),
846 new Uint8Array([0xa9]),
847 ),
848 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)),
849 }),
850 ),
851 ),
852 ),
853 httpClientLayer: layerHttpClient(() => Effect.never),
854 backendOutputLog: {
855 persistFailure: () => {
856 exitCount += 1;
857 return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid);
858 },
859 },
860 onMigrationProgress: (value) =>
861 Effect.sync(() => {
862 progress.push(value);
863 }),
864 onStartupFailure: (failure) =>
865 Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid),
866 });
867 yield* instance.start;
868 yield* Deferred.await(firstExit);
869 yield* TestClock.adjust(Duration.minutes(1));
870 const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports);
871 assert.equal(exitsWhenReported, exits);
872 assert.equal(failure.reason, `The server could not start (code=${code}).`);
873 assert.equal(failure.managedPolicy, managedPolicy);
874 assert.isTrue(failure.output.endsWith(message));
875 assert.isTrue(failure.output.isWellFormed());
876 assert.isTrue(progress.some((value) => value?.current === 1 && value.total === 3));
877 assert.isNull(progress.at(-1));
878 }).pipe(Effect.provide(TestClock.layer())),
879 );
880​
881 it.effect("waits out a slow startup and reports one that never becomes ready", () =>
882 Effect.gen(function* () {
883 const reports = yield* Queue.unbounded<DesktopBackendManager.BackendStartupFailure>();
884 const progress: Array<{ current: number; total: number } | null> = [];
885 const outputProcessed = yield* Queue.unbounded<void>();
886 const startInstance = (
887 status: Ref.Ref<number>,
888 onReady?: Effect.Effect<void>,
889 stdout: string | Stream.Stream<Uint8Array> = "",
890 ) =>
891 makeTestInstance({
892 config: pollingConfig,
893 spawnerLayer: Layer.succeed(
894 ChildProcessSpawner.ChildProcessSpawner,
895 ChildProcessSpawner.make(() =>
896 Effect.succeed(
897 makeProcess({
898 exitCode: Effect.never,
899 stdout:
900 typeof stdout === "string"
901 ? Stream.make(new TextEncoder().encode(stdout))
902 : stdout,
903 }),
904 ),
905 ),
906 ),
907 httpClientLayer: layerHttpClient((request) =>
908 Ref.get(status).pipe(Effect.map((code) => responseForRequest(request, code))),
909 ),
910 backendOutputLog: {
911 writeOutputChunk: () => Queue.offer(outputProcessed, undefined).pipe(Effect.asVoid),
912 },
913 onMigrationProgress: (value) =>
914 Effect.sync(() => {
915 progress.push(value);
916 }),
917 onStartupFailure: (failure) => Queue.offer(reports, failure).pipe(Effect.asVoid),
918 ...(onReady ? { onReady } : {}),
919 }).pipe(Effect.tap((instance) => instance.start));
920​
921 const slowStatus = yield* Ref.make(503);
922 const ready = yield* Deferred.make<void>();
923 yield* startInstance(slowStatus, Deferred.succeed(ready, undefined).pipe(Effect.asVoid));
924 yield* Queue.take(outputProcessed);
925 yield* TestClock.adjust(Duration.seconds(66));
926 yield* Ref.set(slowStatus, 200);
927 yield* TestClock.adjust(Duration.millis(100));
928 yield* Deferred.await(ready);
929 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
930​
931 const migratingStatus = yield* Ref.make(503);
932 const migrated = yield* Deferred.make<void>();
933 const output = yield* Queue.unbounded<Uint8Array>();
934 const writeOutput = (text: string) =>
935 Queue.offer(output, new TextEncoder().encode(text)).pipe(
936 Effect.andThen(Queue.take(outputProcessed)),
937 );
938 yield* startInstance(
939 migratingStatus,
940 Deferred.succeed(migrated, undefined).pipe(Effect.asVoid),
941 Stream.fromQueue(output),
942 );
943 yield* writeOutput(`INFO ${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n`);
944 yield* TestClock.adjust(Duration.minutes(3));
945 assert.isNull(progress.at(-1));
946 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
947 yield* writeOutput(
948 // Enough progress lines that the start line scrolls out of the output tail.
949 `INFO ${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n` +
950 Array.from(
951 { length: 80 },
952 (_, index) =>
953 `INFO ${DATABASE_MIGRATION_PROGRESS_MESSAGE} (${index + 1} of 80)\n migration: ${index}_Migration\n progress: ${index + 1} of 80\n`,
954 ).join(""),
955 );
956 yield* TestClock.adjust(Duration.minutes(10));
957 assert.deepStrictEqual(progress.at(-1), { current: 80, total: 80 });
958 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
959 const noise = "unrelated backend output\n".repeat(400);
960 yield* writeOutput(noise);
961 assert.deepStrictEqual(progress.at(-1), { current: 80, total: 80 });
962 yield* writeOutput(noise);
963 assert.deepStrictEqual(progress.at(-1), { current: 80, total: 80 });
964 yield* TestClock.adjust(Duration.minutes(3));
965 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
966 yield* writeOutput(`${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n${noise}`);
967 assert.isNull(progress.at(-1));
968 yield* writeOutput(`${DATABASE_MIGRATION_PROGRESS_MESSAGE} (1 of 2)\n${noise}`);
969 assert.deepStrictEqual(progress.at(-1), { current: 1, total: 2 });
970 yield* writeOutput(DATABASE_MIGRATIONS_FINISHED_MESSAGE.slice(0, 12));
971 yield* writeOutput(`${DATABASE_MIGRATIONS_FINISHED_MESSAGE.slice(12)}\n${noise}`);
972 assert.isNull(progress.at(-1));
973 yield* writeOutput(noise);
974 assert.isNull(progress.at(-1));
975 yield* writeOutput(
976 `${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n${DATABASE_MIGRATION_PROGRESS_MESSAGE} (1 of 1)\n`,
977 );
978 assert.deepStrictEqual(progress.at(-1), { current: 1, total: 1 });
979 yield* Ref.set(migratingStatus, 200);
980 yield* TestClock.adjust(Duration.millis(100));
981 yield* Deferred.await(migrated);
982 assert.isNull(progress.at(-1));
983​
984 yield* startInstance(
985 yield* Ref.make(503),
986 undefined,
987 `${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n${DATABASE_MIGRATIONS_FINISHED_MESSAGE}\n`,
988 );
989 yield* TestClock.adjust(Duration.seconds(179));
990 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
991 yield* TestClock.adjust(Duration.seconds(1));
992 const failure = yield* Queue.take(reports);
993 assert.isNull(progress.at(-1));
994 assert.equal(failure.reason, "The server started but did not become ready in time.");
995 }).pipe(Effect.provide(TestClock.layer())),
996 );
997​
998 it.effect("the quit stop keeps waiting for a backend that outlasts its deadline", () =>
999 Effect.gen(function* () {
1000 const spawned = yield* Deferred.make<void>();
1001 const teardownStarted = yield* Deferred.make<void>();
1002 const teardownFinished = yield* Deferred.make<void>();
1003 const instance = yield* makeTestInstance({
1004 spawnerLayer: Layer.succeed(
1005 ChildProcessSpawner.ChildProcessSpawner,
1006 ChildProcessSpawner.make(() =>
1007 Effect.gen(function* () {
1008 const scope = yield* Scope.Scope;
1009 yield* Deferred.succeed(spawned, undefined);
1010 yield* Scope.addFinalizer(
1011 scope,
1012 Deferred.succeed(teardownStarted, undefined).pipe(
1013 Effect.andThen(Effect.sleep(Duration.seconds(10))),
1014 Effect.andThen(Deferred.succeed(teardownFinished, undefined)),
1015 Effect.asVoid,
1016 ),
1017 );
1018 return makeProcess({
1019 exitCode: Deferred.await(teardownFinished).pipe(
1020 Effect.as(ChildProcessSpawner.ExitCode(0)),
1021 ),
1022 });
1023 }),
1024 ),
1025 ),
1026 httpClientLayer: layerHttpClient(() => Effect.never),
1027 });
1028 yield* instance.start;
1029 yield* Deferred.await(spawned);
1030​
1031 // App quit and the updater stop every backend with this deadline.
1032 const quitDone = yield* Deferred.make<void>();
1033 const quitFiber = yield* instance
1034 .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT })
1035 .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild);
1036​
1037 yield* Deferred.await(teardownStarted);
1038 // Past the quit deadline, quit must still wait for the backend to exit.
1039 yield* TestClock.adjust(Duration.seconds(9));
1040 assert.isFalse(yield* Deferred.isDone(quitDone));
1041​
1042 yield* TestClock.adjust(Duration.seconds(1));
1043 yield* Fiber.join(quitFiber);
1044 assert.isTrue(yield* Deferred.isDone(teardownFinished));
1045 }).pipe(Effect.provide(TestClock.layer())),
1046 );
1047});