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

DesktopBackendManager.test.ts

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