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

DesktopBackendManager.test.ts

984 lines38.7 KB

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