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

DesktopBackendManager.test.ts

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