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

DesktopBackendManager.test.ts

578 lines21.8 KB

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