Open History to see the last commit
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 });
97}
98
99function responseForRequest(
100 request: HttpClientRequest.HttpClientRequest,
101 status: number,
102): HttpClientResponse.HttpClientResponse {
103 return HttpClientResponse.fromWeb(request, new Response(null, { status }));
104}
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 );
115}
116
117const layerHealthyHttpClient = layerHttpClient((request) =>
118 Effect.succeed(responseForRequest(request, 200)),
119);
120
121function decodeBootstrap(raw: string) {
122 return decodeDesktopBackendBootstrap(raw);
123}
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>;
148}
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));
198}
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("becomes ready from the server ready line while HTTP probes stall", () =>
382 Effect.scoped(
383 Effect.gen(function* () {
384 const probeStarted = yield* Deferred.make<void>();
385 const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
386 const readyLine = encodeDesktopTelemetryControl({ version: 1, type: "serverReady" });
387 const instance = yield* makeTestInstance({
388 spawnerLayer: Layer.succeed(
389 ChildProcessSpawner.ChildProcessSpawner,
390 ChildProcessSpawner.make(() =>
391 Effect.succeed(
392 makeProcess({
393 getOutputFd: (fd) =>
394 fd === 5
395 ? Stream.fromEffect(Deferred.await(probeStarted)).pipe(
396 Stream.flatMap(() => Stream.encodeText(Stream.make(`${readyLine}\n`))),
397 )
398 : Stream.empty,
399 exitCode: Deferred.await(exit),
400 kill: () =>
401 Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid),
402 }),
403 ),
404 ),
405 ),
406 httpClientLayer: layerHttpClient(() =>
407 Deferred.succeed(probeStarted, undefined).pipe(Effect.andThen(Effect.never)),
408 ),
409 });
410
411 yield* instance.start;
412 assert.isTrue(yield* instance.waitForReady(Duration.seconds(15)));
413 }),
414 ),
415 );
416
417 it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
418 Effect.gen(function* () {
419 const handled = yield* Deferred.make<boolean>();
420 const controlMessage = encodeDesktopTelemetryControl({
421 version: 1,
422 type: "setDiagnosticsDemand",
423 enabled: true,
424 });
425 const layerSpawner = Layer.succeed(
426 ChildProcessSpawner.ChildProcessSpawner,
427 ChildProcessSpawner.make(() =>
428 Effect.succeed(
429 makeProcess({
430 getOutputFd: (fd) =>
431 fd === 5
432 ? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`))
433 : Stream.empty,
434 exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
435 }),
436 ),
437 ),
438 );
439 const instance = yield* makeTestInstance({
440 spawnerLayer: layerSpawner,
441 desktopTelemetryPublisher: {
442 handleControlForSource: (_sourceId, message) =>
443 message.type === "setDiagnosticsDemand"
444 ? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid)
445 : Effect.void,
446 },
447 });
448
449 yield* instance.start;
450 assert.isTrue(yield* Deferred.await(handled));
451 }),
452 );
453
454 it.effect("stops the scoped process with output still pending", () =>
455 Effect.gen(function* () {
456 let startCount = 0;
457 let closedCount = 0;
458 const closed = yield* Deferred.make<void>();
459 const teardownStarted = yield* Deferred.make<void>();
460 const finishTeardown = yield* Deferred.make<void>();
461 const startedPids = yield* Queue.unbounded<number>();
462 const ready = yield* Deferred.make<void>();
463 const backendReadyFlag = yield* Ref.make(false);
464 let shutdownCount = 0;
465 let persistedFailureCount = 0;
466 let discardedSessionCount = 0;
467 let removedTelemetrySources = 0;
468
469 const layerSpawner = Layer.succeed(
470 ChildProcessSpawner.ChildProcessSpawner,
471 ChildProcessSpawner.make(() =>
472 Effect.gen(function* () {
473 const scope = yield* Scope.Scope;
474 startCount += 1;
475 yield* Queue.offer(startedPids, 123);
476 const close = Deferred.succeed(teardownStarted, undefined).pipe(
477 Effect.andThen(Deferred.await(finishTeardown)),
478 Effect.andThen(
479 Effect.sync(() => {
480 closedCount += 1;
481 }),
482 ),
483 Effect.andThen(Deferred.succeed(closed, void 0)),
484 Effect.asVoid,
485 );
486
487 yield* Scope.addFinalizer(scope, close);
488
489 return makeProcess({
490 stdout: Stream.never,
491 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
492 kill: () => close,
493 });
494 }),
495 ),
496 );
497
498 const instance = yield* makeTestInstance({
499 spawnerLayer: layerSpawner,
500 onReady: Ref.set(backendReadyFlag, true).pipe(
501 Effect.andThen(Deferred.succeed(ready, void 0)),
502 Effect.asVoid,
503 ),
504 onShutdown: Ref.set(backendReadyFlag, false).pipe(
505 Effect.andThen(
506 Effect.sync(() => {
507 shutdownCount += 1;
508 }),
509 ),
510 ),
511 backendOutputLog: {
512 persistFailure: () =>
513 Effect.sync(() => {
514 persistedFailureCount += 1;
515 }),
516 discardSession: Effect.sync(() => {
517 discardedSessionCount += 1;
518 }),
519 },
520 desktopTelemetryPublisher: {
521 removeControlSource: () =>
522 Effect.sync(() => {
523 removedTelemetrySources += 1;
524 }),
525 },
526 });
527 assert.isTrue(Option.isNone(yield* instance.currentConfig));
528
529 yield* instance.start;
530 assert.equal(yield* Queue.take(startedPids), 123);
531 yield* Deferred.await(ready);
532 assert.isTrue(yield* Ref.get(backendReadyFlag));
533 assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
534
535 const runningSnapshot = yield* instance.snapshot;
536 assert.equal(runningSnapshot.ready, true);
537 assert.deepEqual(runningSnapshot.activePid, Option.some(123));
538
539 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
540 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
541 assert.isFalse(yield* Ref.get(backendReadyFlag));
542 assert.equal(shutdownCount, 1);
543 yield* Deferred.succeed(finishTeardown, undefined);
544 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
545 assert.equal(startCount, 1);
546 assert.equal(closedCount, 1);
547 assert.equal(persistedFailureCount, 0);
548 assert.equal(discardedSessionCount, 1);
549 assert.equal(removedTelemetrySources, 1);
550
551 const stoppedSnapshot = yield* instance.snapshot;
552 assert.isFalse(yield* Ref.get(backendReadyFlag));
553 assert.equal(shutdownCount, 1);
554 assert.equal(stoppedSnapshot.desiredRunning, false);
555 assert.equal(stoppedSnapshot.ready, false);
556 assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
557 }),
558 );
559
560 it.effect("restarts when start is requested during stop teardown", () =>
561 Effect.gen(function* () {
562 const starts = yield* Queue.unbounded<number>();
563 const teardownStarted = yield* Deferred.make<void>();
564 const finishTeardown = yield* Deferred.make<void>();
565 let startCount = 0;
566
567 const layerSpawner = Layer.succeed(
568 ChildProcessSpawner.ChildProcessSpawner,
569 ChildProcessSpawner.make(() =>
570 Effect.gen(function* () {
571 const scope = yield* Scope.Scope;
572 const closed = yield* Deferred.make<void>();
573 startCount += 1;
574 yield* Queue.offer(starts, startCount);
575 if (startCount === 1) {
576 yield* Scope.addFinalizer(
577 scope,
578 Deferred.succeed(teardownStarted, undefined).pipe(
579 Effect.andThen(Deferred.await(finishTeardown)),
580 Effect.andThen(Deferred.succeed(closed, undefined)),
581 Effect.asVoid,
582 ),
583 );
584 } else {
585 yield* Scope.addFinalizer(
586 scope,
587 Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
588 );
589 }
590 return makeProcess({
591 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
592 });
593 }),
594 ),
595 );
596
597 const instance = yield* makeTestInstance({
598 spawnerLayer: layerSpawner,
599 httpClientLayer: layerHttpClient(() => Effect.never),
600 });
601
602 yield* instance.start;
603 assert.equal(yield* Queue.take(starts), 1);
604
605 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
606 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
607 yield* instance.start;
608 assert.equal((yield* instance.snapshot).desiredRunning, true);
609
610 yield* Deferred.succeed(finishTeardown, undefined);
611 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
612 yield* TestClock.adjust(Duration.millis(500));
613
614 assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
615 const restarted = yield* instance.snapshot;
616 assert.equal(restarted.desiredRunning, true);
617 assert.deepEqual(restarted.activePid, Option.some(123));
618 }).pipe(Effect.provide(TestClock.layer())),
619 );
620
621 it.effect("reports state-directory ownership once without scheduling another backend", () =>
622 Effect.gen(function* () {
623 let startCount = 0;
624 const refused = yield* Deferred.make<void>();
625 const instance = yield* makeTestInstance({
626 spawnerLayer: Layer.succeed(
627 ChildProcessSpawner.ChildProcessSpawner,
628 ChildProcessSpawner.make(() =>
629 Effect.sync(() => {
630 startCount += 1;
631 return makeProcess({
632 exitCode: Effect.succeed(
633 ChildProcessSpawner.ExitCode(SERVER_EXIT_CODE_STATE_DIR_OWNED),
634 ),
635 });
636 }),
637 ),
638 ),
639 httpClientLayer: layerHttpClient(() => Effect.never),
640 onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid),
641 });
642 yield* instance.start;
643 yield* Deferred.await(refused);
644 const snapshot = yield* instance.snapshot;
645 assert.isFalse(snapshot.desiredRunning);
646 assert.isFalse(snapshot.restartScheduled);
647 yield* TestClock.adjust(Duration.minutes(1));
648 assert.equal(startCount, 1);
649 }).pipe(Effect.provide(TestClock.layer())),
650 );
651
652 // A policy refusal is reported on the first exit, since retrying cannot fix it.
653 it.effect.each([
654 { code: 1, exits: 3, managedPolicy: false },
655 { code: SERVER_EXIT_CODE_MANAGED_POLICY, exits: 1, managedPolicy: true },
656 ])(
657 "reports exit $code with the server output after $exits exits",
658 ({ code, exits, managedPolicy }) =>
659 Effect.gen(function* () {
660 const message = "Error: Cannot find module 'zod/v4' in /Users/René";
661 let exitCount = 0;
662 const firstExit = yield* Deferred.make<void>();
663 const reports = yield* Queue.unbounded<{
664 readonly exitCount: number;
665 readonly failure: DesktopBackendManager.BackendStartupFailure;
666 }>();
667 const instance = yield* makeTestInstance({
668 spawnerLayer: Layer.succeed(
669 ChildProcessSpawner.ChildProcessSpawner,
670 ChildProcessSpawner.make(() =>
671 Effect.succeed(
672 makeProcess({
673 // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut
674 // lands inside the emoji's surrogate pair.
675 stderr: Stream.make(
676 new TextEncoder().encode(
677 `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`,
678 ),
679 new Uint8Array([0xc3]),
680 new Uint8Array([0xa9]),
681 ),
682 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)),
683 }),
684 ),
685 ),
686 ),
687 httpClientLayer: layerHttpClient(() => Effect.never),
688 backendOutputLog: {
689 persistFailure: () => {
690 exitCount += 1;
691 return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid);
692 },
693 },
694 onStartupFailure: (failure) =>
695 Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid),
696 });
697 yield* instance.start;
698 yield* Deferred.await(firstExit);
699 yield* TestClock.adjust(Duration.minutes(1));
700 const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports);
701 assert.equal(exitsWhenReported, exits);
702 assert.equal(failure.reason, `The server could not start (code=${code}).`);
703 assert.equal(failure.managedPolicy, managedPolicy);
704 assert.isTrue(failure.output.endsWith(message));
705 assert.isTrue(failure.output.isWellFormed());
706 }).pipe(Effect.provide(TestClock.layer())),
707 );
708
709 it.effect("waits out a slow startup and reports one that never becomes ready", () =>
710 Effect.gen(function* () {
711 const reports = yield* Queue.unbounded<DesktopBackendManager.BackendStartupFailure>();
712 const startInstance = (status: Ref.Ref<number>, onReady?: Effect.Effect<void>, stdout = "") =>
713 makeTestInstance({
714 spawnerLayer: Layer.succeed(
715 ChildProcessSpawner.ChildProcessSpawner,
716 ChildProcessSpawner.make(() =>
717 Effect.succeed(
718 makeProcess({
719 exitCode: Effect.never,
720 stdout: Stream.make(new TextEncoder().encode(stdout)),
721 }),
722 ),
723 ),
724 ),
725 httpClientLayer: layerHttpClient((request) =>
726 Ref.get(status).pipe(Effect.map((code) => responseForRequest(request, code))),
727 ),
728 onStartupFailure: (failure) => Queue.offer(reports, failure).pipe(Effect.asVoid),
729 ...(onReady ? { onReady } : {}),
730 }).pipe(Effect.tap((instance) => instance.start));
731
732 const slowStatus = yield* Ref.make(503);
733 const ready = yield* Deferred.make<void>();
734 yield* startInstance(slowStatus, Deferred.succeed(ready, undefined).pipe(Effect.asVoid));
735 yield* TestClock.adjust(Duration.seconds(66));
736 yield* Ref.set(slowStatus, 200);
737 yield* TestClock.adjust(Duration.millis(100));
738 yield* Deferred.await(ready);
739 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
740
741 const migratingStatus = yield* Ref.make(503);
742 const migrated = yield* Deferred.make<void>();
743 yield* startInstance(
744 migratingStatus,
745 Deferred.succeed(migrated, undefined).pipe(Effect.asVoid),
746 // Enough progress lines that the start line scrolls out of the output tail.
747 `INFO ${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n` +
748 Array.from(
749 { length: 80 },
750 (_, index) =>
751 `INFO ${DATABASE_MIGRATION_PROGRESS_MESSAGE} migration=${index}_Migration progress="${index + 1} of 80"\n`,
752 ).join(""),
753 );
754 yield* TestClock.adjust(Duration.minutes(10));
755 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
756 yield* Ref.set(migratingStatus, 200);
757 yield* TestClock.adjust(Duration.millis(100));
758 yield* Deferred.await(migrated);
759
760 yield* startInstance(
761 yield* Ref.make(503),
762 undefined,
763 `${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n${DATABASE_MIGRATIONS_FINISHED_MESSAGE}\n`,
764 );
765 yield* TestClock.adjust(Duration.seconds(179));
766 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
767 yield* TestClock.adjust(Duration.seconds(1));
768 const failure = yield* Queue.take(reports);
769 assert.equal(failure.reason, "The server started but did not become ready in time.");
770 }).pipe(Effect.provide(TestClock.layer())),
771 );
772
773 it.effect("the quit stop keeps waiting for a backend that outlasts its deadline", () =>
774 Effect.gen(function* () {
775 const spawned = yield* Deferred.make<void>();
776 const teardownStarted = yield* Deferred.make<void>();
777 const teardownFinished = yield* Deferred.make<void>();
778 const instance = yield* makeTestInstance({
779 spawnerLayer: Layer.succeed(
780 ChildProcessSpawner.ChildProcessSpawner,
781 ChildProcessSpawner.make(() =>
782 Effect.gen(function* () {
783 const scope = yield* Scope.Scope;
784 yield* Deferred.succeed(spawned, undefined);
785 yield* Scope.addFinalizer(
786 scope,
787 Deferred.succeed(teardownStarted, undefined).pipe(
788 Effect.andThen(Effect.sleep(Duration.seconds(10))),
789 Effect.andThen(Deferred.succeed(teardownFinished, undefined)),
790 Effect.asVoid,
791 ),
792 );
793 return makeProcess({
794 exitCode: Deferred.await(teardownFinished).pipe(
795 Effect.as(ChildProcessSpawner.ExitCode(0)),
796 ),
797 });
798 }),
799 ),
800 ),
801 httpClientLayer: layerHttpClient(() => Effect.never),
802 });
803 yield* instance.start;
804 yield* Deferred.await(spawned);
805
806 // App quit and the updater stop every backend with this deadline.
807 const quitDone = yield* Deferred.make<void>();
808 const quitFiber = yield* instance
809 .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT })
810 .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild);
811
812 yield* Deferred.await(teardownStarted);
813 // Past the quit deadline, quit must still wait for the backend to exit.
814 yield* TestClock.adjust(Duration.seconds(9));
815 assert.isFalse(yield* Deferred.isDone(quitDone));
816
817 yield* TestClock.adjust(Duration.seconds(1));
818 yield* Fiber.join(quitFiber);
819 assert.isTrue(yield* Deferred.isDone(teardownFinished));
820 }).pipe(Effect.provide(TestClock.layer())),
821 );
822});