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

DesktopBackendManager.test.ts

776 lines30.4 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 { assert, describe, it } from "@effect/vitest";
9import * as Deferred from "effect/Deferred";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Fiber from "effect/Fiber";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as PlatformError from "effect/PlatformError";
17import * as Queue from "effect/Queue";
18import * as Ref from "effect/Ref";
19import * as Schema from "effect/Schema";
20import * as Sink from "effect/Sink";
21import * as Scope from "effect/Scope";
22import * as Stream from "effect/Stream";
23import * as TestClock from "effect/testing/TestClock";
24import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
25import { ChildProcess, ChildProcessSpawner } from "effect/process";
26​
27import * as DesktopBackendManager from "./DesktopBackendManager.ts";
28import * as DesktopObservability from "../app/DesktopObservability.ts";
29import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
30import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
31import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
32​
33const decodeDesktopBackendBootstrap = Schema.decodeEffect(
34 Schema.fromJsonString(DesktopBackendBootstrap),
35);
36const encodeDesktopTelemetryControl = Schema.encodeSync(
37 Schema.fromJsonString(DesktopTelemetryControlMessage),
38);
39​
40const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
41 executablePath: "/electron",
42 args: ["/server/bin.mjs", "--bootstrap-fd", "3"],
43 entryPath: "/server/bin.mjs",
44 cwd: "/server",
45 env: { ELECTRON_RUN_AS_NODE: "1" },
46 bootstrap: {
47 mode: "desktop",
48 noBrowser: true,
49 port: 3773,
50 t3Home: "/tmp/t3",
51 host: "127.0.0.1",
52 desktopBootstrapToken: "token",
53 tailscaleServeEnabled: false,
54 tailscaleServePort: 443,
55 desktopTelemetryFd: 4,
56 desktopTelemetryControlFd: 5,
57 },
58 bootstrapDelivery: "fd3",
59 extendEnv: true,
60 httpBaseUrl: new URL("http://127.0.0.1:3773"),
61 captureOutput: true,
62 preflightFailure: Option.none(),
63};
64​
65const configWithObservability: DesktopBackendBootstrapValue = {
66 ...baseConfig.bootstrap,
67 tailscaleServeEnabled: true,
68 desktopTelemetryFd: 4,
69 otlpTracesUrl: "http://127.0.0.1:4318/v1/traces",
70};
71​
72function makeProcess(options?: {
73 readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
74 readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
75 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
76 readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
77 readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
78}): ChildProcessSpawner.ChildProcessHandle {
79 return ChildProcessSpawner.makeHandle({
80 pid: ChildProcessSpawner.ProcessId(123),
81 stdout: options?.stdout ?? Stream.empty,
82 stderr: options?.stderr ?? Stream.empty,
83 all: Stream.merge(options?.stdout ?? Stream.empty, options?.stderr ?? Stream.empty),
84 exitCode: options?.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(0)),
85 isRunning: Effect.succeed(false),
86 kill: options?.kill ?? (() => Effect.void),
87 stdin: Sink.drain,
88 getInputFd: () => Sink.drain,
89 getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
90 unref: Effect.succeed(Effect.void),
91 });
93​
94function responseForRequest(
95 request: HttpClientRequest.HttpClientRequest,
96 status: number,
97): HttpClientResponse.HttpClientResponse {
98 return HttpClientResponse.fromWeb(request, new Response(null, { status }));
100​
101function layerHttpClient(
102 handler: (
103 request: HttpClientRequest.HttpClientRequest,
104 ) => Effect.Effect<HttpClientResponse.HttpClientResponse>,
105) {
106 return Layer.succeed(
107 HttpClient.HttpClient,
108 HttpClient.make((request) => handler(request)),
109 );
111​
112const layerHealthyHttpClient = layerHttpClient((request) =>
113 Effect.succeed(responseForRequest(request, 200)),
114);
115​
116function decodeBootstrap(raw: string) {
117 return decodeDesktopBackendBootstrap(raw);
119​
120interface MakeInstanceInput {
121 readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
122 readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
123 readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
124 readonly onReady?: Effect.Effect<void>;
125 readonly onShutdown?: Effect.Effect<void>;
126 readonly onStateDirOwned?: Effect.Effect<void>;
127 readonly onStartupFailure?: (
128 failure: DesktopBackendManager.BackendStartupFailure,
129 ) => Effect.Effect<void>;
130 readonly onPreflightFailed?: (
131 failure: DesktopBackendManager.PreflightFailure,
132 ) => Effect.Effect<boolean>;
133 readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
134 readonly configResolve?: Effect.Effect<
135 DesktopBackendManager.DesktopBackendStartConfig,
136 PlatformError.PlatformError
137 >;
138 readonly desktopTelemetryStream?: Stream.Stream<Uint8Array>;
139 readonly desktopTelemetryPublisher?: Partial<
140 DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
141 >;
142 readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
144​
145function makeTestInstance(input: MakeInstanceInput) {
146 const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
147 beginSession: () => Effect.void,
148 writeOutputChunk: () => Effect.void,
149 persistFailureSnapshot: () => Effect.void,
150 persistFailure: () => Effect.void,
151 discardSession: Effect.void,
152 ...input.backendOutputLog,
153 };
154 const layerServices = Layer.mergeAll(
155 FileSystem.layerNoop({
156 exists: () => Effect.succeed(true),
157 }),
158 input.spawnerLayer,
159 input.httpClientLayer ?? layerHealthyHttpClient,
160 Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
161 forInstance: () => Effect.succeed(stubLog),
162 } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
163 Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
164 latest: Effect.succeedNone,
165 changes: Stream.empty,
166 encoded: input.desktopTelemetryStream ?? Stream.empty,
167 handleControlForSource: () => Effect.void,
168 removeControlSource: () => Effect.void,
169 publishUpdateReport: () => Effect.void,
170 updateRequests: Stream.empty,
171 updateCommits: Stream.empty,
172 updateCancellations: Stream.empty,
173 ...input.desktopTelemetryPublisher,
174 }),
175 DesktopBrowserHost.layer,
176 DesktopWslEnvironment.layerTest(
177 input.pruneRuntimes === undefined ? {} : { pruneRuntimes: input.pruneRuntimes },
178 ),
179 );
180​
181 const instance = DesktopBackendManager.makeBackendInstance({
182 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
183 label: Effect.succeed("Windows"),
184 configResolve: input.configResolve ?? Effect.succeed(input.config ?? baseConfig),
185 ...(input.onReady ? { onReady: () => input.onReady! } : {}),
186 ...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}),
187 ...(input.onStateDirOwned ? { onStateDirOwned: () => input.onStateDirOwned! } : {}),
188 ...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}),
189 ...(input.onStartupFailure ? { onStartupFailure: input.onStartupFailure } : {}),
190 });
191​
192 return instance.pipe(Effect.provide(layerServices));
194​
195describe("DesktopBackendManager", () => {
196 it.effect("notifies readiness waiters on HTTP readiness and stop without clock advancement", () =>
197 Effect.scoped(
198 Effect.gen(function* () {
199 const probe = yield* Deferred.make<void>();
200 const ready = yield* Deferred.make<void>();
201 const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
202 const instance = yield* makeTestInstance({
203 spawnerLayer: Layer.succeed(
204 ChildProcessSpawner.ChildProcessSpawner,
205 ChildProcessSpawner.make(() =>
206 Effect.acquireRelease(
207 Effect.succeed(
208 makeProcess({
209 exitCode: Deferred.await(exit),
210 kill: () =>
211 Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid),
212 }),
213 ),
214 () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
215 ),
216 ),
217 ),
218 httpClientLayer: Layer.succeed(
219 HttpClient.HttpClient,
220 HttpClient.make((request) =>
221 Deferred.succeed(probe, undefined).pipe(
222 Effect.andThen(Deferred.await(ready)),
223 Effect.as(HttpClientResponse.fromWeb(request, new Response("{}"))),
224 ),
225 ),
226 ),
227 });
228 yield* instance.start;
229 yield* Deferred.await(probe);
230 const waiter = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild);
231 yield* Deferred.succeed(ready, undefined);
232 assert.isTrue(yield* Fiber.join(waiter));
233 yield* instance.stop();
234 assert.isFalse(yield* instance.waitForReady(Duration.seconds(15)));
235 }),
236 ),
237 );
238​
239 it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
240 Effect.scoped(
241 Effect.gen(function* () {
242 let spawnedCommand: ChildProcess.Command | undefined;
243 let bootstrapJson = "";
244 let telemetryJson = "";
245 let readyCount = 0;
246 const ready = yield* Deferred.make<void>();
247 const exited = yield* Queue.unbounded<void>();
248​
249 const layerSpawner = Layer.succeed(
250 ChildProcessSpawner.ChildProcessSpawner,
251 ChildProcessSpawner.make((command) =>
252 Effect.gen(function* () {
253 spawnedCommand = command;
254 if (command._tag === "StandardCommand") {
255 const fd3 = command.options.additionalFds?.fd3;
256 if (fd3?.type === "input" && fd3.stream) {
257 bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
258 }
259 const fd4 = command.options.additionalFds?.fd4;
260 if (fd4?.type === "input" && fd4.stream) {
261 telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString);
262 }
263 }
264​
265 return makeProcess({
266 exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
267 });
268 }),
269 ),
270 );
271​
272 const instance = yield* makeTestInstance({
273 config: {
274 ...baseConfig,
275 bootstrap: configWithObservability,
276 },
277 spawnerLayer: layerSpawner,
278 desktopTelemetryStream: Stream.encodeText(
279 Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'),
280 ),
281 onReady: Effect.sync(() => {
282 readyCount += 1;
283 }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
284 backendOutputLog: {
285 persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
286 },
287 });
288​
289 yield* instance.start;
290 yield* Queue.take(exited);
291​
292 assert.equal(readyCount, 1);
293 assert.isDefined(spawnedCommand);
294 if (spawnedCommand._tag !== "StandardCommand") {
295 throw new Error("Expected backend to spawn a standard command.");
296 }
297​
298 assert.equal(spawnedCommand.command, "/electron");
299 assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]);
300 assert.equal(spawnedCommand.options.cwd, "/server");
301 assert.equal(spawnedCommand.options.extendEnv, true);
302 assert.equal(spawnedCommand.options.stdout, "pipe");
303 assert.equal(spawnedCommand.options.stderr, "pipe");
304 assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
305 assert.isDefined(spawnedCommand.options.forceKillAfter);
306 assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
307 assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
308 assert.equal(
309 Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
310 5_000,
311 );
312​
313 assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
314 assert.equal(
315 telemetryJson,
316 '{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n',
317 );
318 }),
319 ),
320 );
321​
322 it.effect("reports a SIGKILL exit without an exit code", () =>
323 Effect.gen(function* () {
324 const exitCause = PlatformError.systemError({
325 _tag: "Unknown",
326 module: "ChildProcess",
327 method: "exitCode",
328 cause: new Error("Process interrupted due to receipt of signal: 'SIGKILL'"),
329 });
330 const layerSpawner = Layer.succeed(
331 ChildProcessSpawner.ChildProcessSpawner,
332 ChildProcessSpawner.make(() =>
333 Effect.succeed(makeProcess({ exitCode: Effect.fail(exitCause) })),
334 ),
335 );
336​
337 const exit = yield* DesktopBackendManager.runBackendProcess({
338 ...baseConfig,
339 desktopTelemetryStream: Stream.empty,
340 }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)));
341​
342 assert.deepEqual(exit, { code: Option.none(), reason: "killed by SIGKILL" });
343 }),
344 );
345​
346 it.effect("reports child exit before waiting for trailing output to drain", () =>
347 Effect.scoped(
348 Effect.gen(function* () {
349 const exitObserved = yield* Deferred.make<void>();
350 const finishOutputDrain = yield* Deferred.make<void>();
351 const layerSpawner = Layer.succeed(
352 ChildProcessSpawner.ChildProcessSpawner,
353 ChildProcessSpawner.make(() =>
354 Effect.succeed(
355 makeProcess({
356 stdout: Stream.fromEffect(
357 Deferred.await(finishOutputDrain).pipe(
358 Effect.as(new TextEncoder().encode("trailing output\n")),
359 ),
360 ),
361 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
362 }),
363 ),
364 ),
365 );
366​
367 const runFiber = yield* DesktopBackendManager.runBackendProcess({
368 ...baseConfig,
369 desktopTelemetryStream: Stream.empty,
370 onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid),
371 }).pipe(
372 Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)),
373 Effect.forkChild,
374 );
375​
376 yield* Deferred.await(exitObserved);
377 assert.isUndefined(runFiber.pollUnsafe());
378​
379 yield* Deferred.succeed(finishOutputDrain, void 0);
380 assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1);
381 }),
382 ),
383 );
384​
385 it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
386 Effect.scoped(
387 Effect.gen(function* () {
388 const handled = yield* Deferred.make<boolean>();
389 const controlMessage = encodeDesktopTelemetryControl({
390 version: 1,
391 type: "setDiagnosticsDemand",
392 enabled: true,
393 });
394 const layerSpawner = Layer.succeed(
395 ChildProcessSpawner.ChildProcessSpawner,
396 ChildProcessSpawner.make(() =>
397 Effect.succeed(
398 makeProcess({
399 getOutputFd: (fd) =>
400 fd === 5
401 ? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`))
402 : Stream.empty,
403 exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
404 }),
405 ),
406 ),
407 );
408 const instance = yield* makeTestInstance({
409 spawnerLayer: layerSpawner,
410 desktopTelemetryPublisher: {
411 handleControlForSource: (_sourceId, message) =>
412 message.type === "setDiagnosticsDemand"
413 ? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid)
414 : Effect.void,
415 },
416 });
417​
418 yield* instance.start;
419 assert.isTrue(yield* Deferred.await(handled));
420 }),
421 ),
422 );
423​
424 it.effect("stops the scoped process with output still pending", () =>
425 Effect.scoped(
426 Effect.gen(function* () {
427 let startCount = 0;
428 let closedCount = 0;
429 const closed = yield* Deferred.make<void>();
430 const teardownStarted = yield* Deferred.make<void>();
431 const finishTeardown = yield* Deferred.make<void>();
432 const startedPids = yield* Queue.unbounded<number>();
433 const ready = yield* Deferred.make<void>();
434 const backendReadyFlag = yield* Ref.make(false);
435 let shutdownCount = 0;
436 let persistedFailureCount = 0;
437 let discardedSessionCount = 0;
438 let removedTelemetrySources = 0;
439​
440 const layerSpawner = Layer.succeed(
441 ChildProcessSpawner.ChildProcessSpawner,
442 ChildProcessSpawner.make(() =>
443 Effect.gen(function* () {
444 const scope = yield* Scope.Scope;
445 startCount += 1;
446 yield* Queue.offer(startedPids, 123);
447 const close = Deferred.succeed(teardownStarted, undefined).pipe(
448 Effect.andThen(Deferred.await(finishTeardown)),
449 Effect.andThen(
450 Effect.sync(() => {
451 closedCount += 1;
452 }),
453 ),
454 Effect.andThen(Deferred.succeed(closed, void 0)),
455 Effect.asVoid,
456 );
457​
458 yield* Scope.addFinalizer(scope, close);
459​
460 return makeProcess({
461 stdout: Stream.never,
462 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
463 kill: () => close,
464 });
465 }),
466 ),
467 );
468​
469 const instance = yield* makeTestInstance({
470 spawnerLayer: layerSpawner,
471 onReady: Ref.set(backendReadyFlag, true).pipe(
472 Effect.andThen(Deferred.succeed(ready, void 0)),
473 Effect.asVoid,
474 ),
475 onShutdown: Ref.set(backendReadyFlag, false).pipe(
476 Effect.andThen(
477 Effect.sync(() => {
478 shutdownCount += 1;
479 }),
480 ),
481 ),
482 backendOutputLog: {
483 persistFailure: () =>
484 Effect.sync(() => {
485 persistedFailureCount += 1;
486 }),
487 discardSession: Effect.sync(() => {
488 discardedSessionCount += 1;
489 }),
490 },
491 desktopTelemetryPublisher: {
492 removeControlSource: () =>
493 Effect.sync(() => {
494 removedTelemetrySources += 1;
495 }),
496 },
497 });
498 assert.isTrue(Option.isNone(yield* instance.currentConfig));
499​
500 yield* instance.start;
501 assert.equal(yield* Queue.take(startedPids), 123);
502 yield* Deferred.await(ready);
503 assert.isTrue(yield* Ref.get(backendReadyFlag));
504 assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
505​
506 const runningSnapshot = yield* instance.snapshot;
507 assert.equal(runningSnapshot.ready, true);
508 assert.deepEqual(runningSnapshot.activePid, Option.some(123));
509​
510 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
511 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
512 assert.isFalse(yield* Ref.get(backendReadyFlag));
513 assert.equal(shutdownCount, 1);
514 yield* Deferred.succeed(finishTeardown, undefined);
515 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
516 assert.equal(startCount, 1);
517 assert.equal(closedCount, 1);
518 assert.equal(persistedFailureCount, 0);
519 assert.equal(discardedSessionCount, 1);
520 assert.equal(removedTelemetrySources, 1);
521​
522 const stoppedSnapshot = yield* instance.snapshot;
523 assert.isFalse(yield* Ref.get(backendReadyFlag));
524 assert.equal(shutdownCount, 1);
525 assert.equal(stoppedSnapshot.desiredRunning, false);
526 assert.equal(stoppedSnapshot.ready, false);
527 assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
528 }),
529 ),
530 );
531​
532 it.effect("restarts when start is requested during stop teardown", () =>
533 Effect.scoped(
534 Effect.gen(function* () {
535 const starts = yield* Queue.unbounded<number>();
536 const teardownStarted = yield* Deferred.make<void>();
537 const finishTeardown = yield* Deferred.make<void>();
538 let startCount = 0;
539​
540 const layerSpawner = Layer.succeed(
541 ChildProcessSpawner.ChildProcessSpawner,
542 ChildProcessSpawner.make(() =>
543 Effect.gen(function* () {
544 const scope = yield* Scope.Scope;
545 const closed = yield* Deferred.make<void>();
546 startCount += 1;
547 yield* Queue.offer(starts, startCount);
548 if (startCount === 1) {
549 yield* Scope.addFinalizer(
550 scope,
551 Deferred.succeed(teardownStarted, undefined).pipe(
552 Effect.andThen(Deferred.await(finishTeardown)),
553 Effect.andThen(Deferred.succeed(closed, undefined)),
554 Effect.asVoid,
555 ),
556 );
557 } else {
558 yield* Scope.addFinalizer(
559 scope,
560 Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
561 );
562 }
563 return makeProcess({
564 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
565 });
566 }),
567 ),
568 );
569​
570 const instance = yield* makeTestInstance({
571 spawnerLayer: layerSpawner,
572 httpClientLayer: layerHttpClient(() => Effect.never),
573 });
574​
575 yield* instance.start;
576 assert.equal(yield* Queue.take(starts), 1);
577​
578 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
579 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
580 yield* instance.start;
581 assert.equal((yield* instance.snapshot).desiredRunning, true);
582​
583 yield* Deferred.succeed(finishTeardown, undefined);
584 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
585 yield* TestClock.adjust(Duration.millis(500));
586​
587 assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
588 const restarted = yield* instance.snapshot;
589 assert.equal(restarted.desiredRunning, true);
590 assert.deepEqual(restarted.activePid, Option.some(123));
591 }).pipe(Effect.provide(TestClock.layer())),
592 ),
593 );
594​
595 it.effect("reports state-directory ownership once without scheduling another backend", () =>
596 Effect.scoped(
597 Effect.gen(function* () {
598 let startCount = 0;
599 const refused = yield* Deferred.make<void>();
600 const instance = yield* makeTestInstance({
601 spawnerLayer: Layer.succeed(
602 ChildProcessSpawner.ChildProcessSpawner,
603 ChildProcessSpawner.make(() =>
604 Effect.sync(() => {
605 startCount += 1;
606 return makeProcess({
607 exitCode: Effect.succeed(
608 ChildProcessSpawner.ExitCode(SERVER_EXIT_CODE_STATE_DIR_OWNED),
609 ),
610 });
611 }),
612 ),
613 ),
614 httpClientLayer: layerHttpClient(() => Effect.never),
615 onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid),
616 });
617 yield* instance.start;
618 yield* Deferred.await(refused);
619 const snapshot = yield* instance.snapshot;
620 assert.isFalse(snapshot.desiredRunning);
621 assert.isFalse(snapshot.restartScheduled);
622 yield* TestClock.adjust(Duration.minutes(1));
623 assert.equal(startCount, 1);
624 }).pipe(Effect.provide(TestClock.layer())),
625 ),
626 );
627​
628 // A policy refusal is reported on the first exit, since retrying cannot fix it.
629 it.effect.each([
630 { code: 1, exits: 3, managedPolicy: false },
631 { code: SERVER_EXIT_CODE_MANAGED_POLICY, exits: 1, managedPolicy: true },
632 ])(
633 "reports exit $code with the server output after $exits exits",
634 ({ code, exits, managedPolicy }) =>
635 Effect.scoped(
636 Effect.gen(function* () {
637 const message = "Error: Cannot find module 'zod/v4' in /Users/René";
638 let exitCount = 0;
639 const firstExit = yield* Deferred.make<void>();
640 const reports = yield* Queue.unbounded<{
641 readonly exitCount: number;
642 readonly failure: DesktopBackendManager.BackendStartupFailure;
643 }>();
644 const instance = yield* makeTestInstance({
645 spawnerLayer: Layer.succeed(
646 ChildProcessSpawner.ChildProcessSpawner,
647 ChildProcessSpawner.make(() =>
648 Effect.succeed(
649 makeProcess({
650 // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut
651 // lands inside the emoji's surrogate pair.
652 stderr: Stream.make(
653 new TextEncoder().encode(
654 `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`,
655 ),
656 new Uint8Array([0xc3]),
657 new Uint8Array([0xa9]),
658 ),
659 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)),
660 }),
661 ),
662 ),
663 ),
664 httpClientLayer: layerHttpClient(() => Effect.never),
665 backendOutputLog: {
666 persistFailure: () => {
667 exitCount += 1;
668 return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid);
669 },
670 },
671 onStartupFailure: (failure) =>
672 Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid),
673 });
674 yield* instance.start;
675 yield* Deferred.await(firstExit);
676 yield* TestClock.adjust(Duration.minutes(1));
677 const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports);
678 assert.equal(exitsWhenReported, exits);
679 assert.equal(failure.reason, `The server could not start (code=${code}).`);
680 assert.equal(failure.managedPolicy, managedPolicy);
681 assert.isTrue(failure.output.endsWith(message));
682 assert.isTrue(failure.output.isWellFormed());
683 }).pipe(Effect.provide(TestClock.layer())),
684 ),
685 );
686​
687 it.effect("waits out a slow startup and reports one that never becomes ready", () =>
688 Effect.scoped(
689 Effect.gen(function* () {
690 const reports = yield* Queue.unbounded<DesktopBackendManager.BackendStartupFailure>();
691 const startInstance = (status: Ref.Ref<number>, onReady?: Effect.Effect<void>) =>
692 makeTestInstance({
693 spawnerLayer: Layer.succeed(
694 ChildProcessSpawner.ChildProcessSpawner,
695 ChildProcessSpawner.make(() =>
696 Effect.succeed(makeProcess({ exitCode: Effect.never })),
697 ),
698 ),
699 httpClientLayer: layerHttpClient((request) =>
700 Ref.get(status).pipe(Effect.map((code) => responseForRequest(request, code))),
701 ),
702 onStartupFailure: (failure) => Queue.offer(reports, failure).pipe(Effect.asVoid),
703 ...(onReady ? { onReady } : {}),
704 }).pipe(Effect.tap((instance) => instance.start));
705​
706 const slowStatus = yield* Ref.make(503);
707 const ready = yield* Deferred.make<void>();
708 yield* startInstance(slowStatus, Deferred.succeed(ready, undefined).pipe(Effect.asVoid));
709 yield* TestClock.adjust(Duration.seconds(66));
710 yield* Ref.set(slowStatus, 200);
711 yield* TestClock.adjust(Duration.millis(100));
712 yield* Deferred.await(ready);
713 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
714​
715 yield* startInstance(yield* Ref.make(503));
716 yield* TestClock.adjust(Duration.seconds(179));
717 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
718 yield* TestClock.adjust(Duration.seconds(1));
719 const failure = yield* Queue.take(reports);
720 assert.equal(failure.reason, "The server started but did not become ready in time.");
721 }).pipe(Effect.provide(TestClock.layer())),
722 ),
723 );
724​
725 it.effect("the quit stop keeps waiting for a backend that outlasts its deadline", () =>
726 Effect.scoped(
727 Effect.gen(function* () {
728 const spawned = yield* Deferred.make<void>();
729 const teardownStarted = yield* Deferred.make<void>();
730 const teardownFinished = yield* Deferred.make<void>();
731 const instance = yield* makeTestInstance({
732 spawnerLayer: Layer.succeed(
733 ChildProcessSpawner.ChildProcessSpawner,
734 ChildProcessSpawner.make(() =>
735 Effect.gen(function* () {
736 const scope = yield* Scope.Scope;
737 yield* Deferred.succeed(spawned, undefined);
738 yield* Scope.addFinalizer(
739 scope,
740 Deferred.succeed(teardownStarted, undefined).pipe(
741 Effect.andThen(Effect.sleep(Duration.seconds(10))),
742 Effect.andThen(Deferred.succeed(teardownFinished, undefined)),
743 Effect.asVoid,
744 ),
745 );
746 return makeProcess({
747 exitCode: Deferred.await(teardownFinished).pipe(
748 Effect.as(ChildProcessSpawner.ExitCode(0)),
749 ),
750 });
751 }),
752 ),
753 ),
754 httpClientLayer: layerHttpClient(() => Effect.never),
755 });
756 yield* instance.start;
757 yield* Deferred.await(spawned);
758​
759 // App quit and the updater stop every backend with this deadline.
760 const quitDone = yield* Deferred.make<void>();
761 const quitFiber = yield* instance
762 .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT })
763 .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild);
764​
765 yield* Deferred.await(teardownStarted);
766 // Past the quit deadline, quit must still wait for the backend to exit.
767 yield* TestClock.adjust(Duration.seconds(9));
768 assert.isFalse(yield* Deferred.isDone(quitDone));
769​
770 yield* TestClock.adjust(Duration.seconds(1));
771 yield* Fiber.join(quitFiber);
772 assert.isTrue(yield* Deferred.isDone(teardownFinished));
773 }).pipe(Effect.provide(TestClock.layer())),
774 ),
775 );
776});