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

DesktopBackendManager.test.ts

715 lines27.7 KB

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