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

DesktopBackendManager.test.ts

494 lines17.3 KB

1import {
2 DesktopBackendBootstrap,
3 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
4} from "@t3tools/contracts";
5import { assert, describe, it } from "@effect/vitest";
6import * as Deferred from "effect/Deferred";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as Ref from "effect/Ref";
14import * as Schema from "effect/Schema";
15import * as Sink from "effect/Sink";
16import * as Scope from "effect/Scope";
17import * as Stream from "effect/Stream";
18import * as TestClock from "effect/testing/TestClock";
19import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
20import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
21​
22import * as DesktopBackendManager from "./DesktopBackendManager.ts";
23import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
24import * as DesktopObservability from "../app/DesktopObservability.ts";
25import * as DesktopState from "../app/DesktopState.ts";
26import * as DesktopWindow from "../window/DesktopWindow.ts";
27​
28const decodeDesktopBackendBootstrap = Schema.decodeEffect(
29 Schema.fromJsonString(DesktopBackendBootstrap),
30);
31​
32const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
33 executablePath: "/electron",
34 entryPath: "/server/bin.mjs",
35 cwd: "/server",
36 env: { ELECTRON_RUN_AS_NODE: "1" },
37 bootstrap: {
38 mode: "desktop",
39 noBrowser: true,
40 port: 3773,
41 t3Home: "/tmp/t3",
42 host: "127.0.0.1",
43 desktopBootstrapToken: "token",
44 tailscaleServeEnabled: false,
45 tailscaleServePort: 443,
46 },
47 httpBaseUrl: new URL("http://127.0.0.1:3773"),
48 captureOutput: true,
49};
50​
51const configWithObservability: DesktopBackendBootstrapValue = {
52 ...baseConfig.bootstrap,
53 tailscaleServeEnabled: true,
54 otlpTracesUrl: "http://127.0.0.1:4318/v1/traces",
55};
56​
57function makeProcess(options?: {
58 readonly stdout?: Stream.Stream<Uint8Array>;
59 readonly stderr?: Stream.Stream<Uint8Array>;
60 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
61 readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
62}): ChildProcessSpawner.ChildProcessHandle {
63 return ChildProcessSpawner.makeHandle({
64 pid: ChildProcessSpawner.ProcessId(123),
65 stdout: options?.stdout ?? Stream.empty,
66 stderr: options?.stderr ?? Stream.empty,
67 all: Stream.merge(options?.stdout ?? Stream.empty, options?.stderr ?? Stream.empty),
68 exitCode: options?.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(0)),
69 isRunning: Effect.succeed(false),
70 kill: options?.kill ?? (() => Effect.void),
71 stdin: Sink.drain,
72 getInputFd: () => Sink.drain,
73 getOutputFd: () => Stream.empty,
74 unref: Effect.succeed(Effect.void),
75 });
77​
78function responseForRequest(
79 request: HttpClientRequest.HttpClientRequest,
80 status: number,
81): HttpClientResponse.HttpClientResponse {
82 return HttpClientResponse.fromWeb(request, new Response(null, { status }));
84​
85function httpClientLayer(
86 handler: (
87 request: HttpClientRequest.HttpClientRequest,
88 ) => Effect.Effect<HttpClientResponse.HttpClientResponse>,
89) {
90 return Layer.succeed(
91 HttpClient.HttpClient,
92 HttpClient.make((request) => handler(request)),
93 );
95​
96const healthyHttpClientLayer = httpClientLayer((request) =>
97 Effect.succeed(responseForRequest(request, 200)),
98);
99​
100function decodeBootstrap(raw: string) {
101 return decodeDesktopBackendBootstrap(raw);
103​
104function makeManagerLayer(input: {
105 readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
106 readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
107 readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
108 readonly desktopState?: DesktopState.DesktopStateShape;
109 readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
110 readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
111}) {
112 return DesktopBackendManager.layer.pipe(
113 Layer.provide(
114 Layer.mergeAll(
115 FileSystem.layerNoop({
116 exists: () => Effect.succeed(true),
117 }),
118 Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
119 resolve: Effect.succeed(input.config ?? baseConfig),
120 }),
121 input.spawnerLayer,
122 input.httpClientLayer ?? healthyHttpClientLayer,
123 input.desktopState
124 ? Layer.succeed(DesktopState.DesktopState, input.desktopState)
125 : DesktopState.layer,
126 Layer.succeed(DesktopObservability.DesktopBackendOutputLog, {
127 writeSessionBoundary: () => Effect.void,
128 writeOutputChunk: () => Effect.void,
129 ...input.backendOutputLog,
130 } satisfies DesktopObservability.DesktopBackendOutputLogShape),
131 Layer.succeed(DesktopWindow.DesktopWindow, {
132 createMain: Effect.die("unexpected createMain"),
133 ensureMain: Effect.die("unexpected ensureMain"),
134 revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
135 activate: Effect.void,
136 createMainIfBackendReady: Effect.void,
137 handleBackendReady: Effect.void,
138 dispatchMenuAction: () => Effect.void,
139 syncAppearance: Effect.void,
140 ...input.desktopWindow,
141 } satisfies DesktopWindow.DesktopWindowShape),
142 ),
143 ),
144 );
146​
147describe("DesktopBackendManager", () => {
148 it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
149 Effect.gen(function* () {
150 let spawnedCommand: ChildProcess.Command | undefined;
151 let bootstrapJson = "";
152 let readyCount = 0;
153 const ready = yield* Deferred.make<void>();
154 const exited = yield* Queue.unbounded<void>();
155​
156 const spawnerLayer = Layer.succeed(
157 ChildProcessSpawner.ChildProcessSpawner,
158 ChildProcessSpawner.make((command) =>
159 Effect.gen(function* () {
160 spawnedCommand = command;
161 if (command._tag === "StandardCommand") {
162 const fd3 = command.options.additionalFds?.fd3;
163 if (fd3?.type === "input" && fd3.stream) {
164 bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
165 }
166 }
167​
168 return makeProcess({
169 exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
170 });
171 }),
172 ),
173 );
174​
175 const managerLayer = makeManagerLayer({
176 config: {
177 ...baseConfig,
178 bootstrap: configWithObservability,
179 },
180 spawnerLayer,
181 desktopWindow: {
182 handleBackendReady: Effect.sync(() => {
183 readyCount += 1;
184 }).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
185 },
186 backendOutputLog: {
187 writeSessionBoundary: ({ phase }) =>
188 phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
189 },
190 });
191​
192 yield* Effect.gen(function* () {
193 const manager = yield* DesktopBackendManager.DesktopBackendManager;
194 yield* manager.start;
195 yield* Queue.take(exited);
196​
197 assert.equal(readyCount, 1);
198 assert.isDefined(spawnedCommand);
199 if (spawnedCommand._tag !== "StandardCommand") {
200 throw new Error("Expected backend to spawn a standard command.");
201 }
202​
203 assert.equal(spawnedCommand.command, "/electron");
204 assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]);
205 assert.equal(spawnedCommand.options.cwd, "/server");
206 assert.equal(spawnedCommand.options.extendEnv, true);
207 assert.equal(spawnedCommand.options.stdout, "pipe");
208 assert.equal(spawnedCommand.options.stderr, "pipe");
209 assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
210 assert.isDefined(spawnedCommand.options.forceKillAfter);
211 assert.equal(
212 Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
213 2_000,
214 );
215​
216 assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
217 }).pipe(Effect.provide(managerLayer));
218 }),
219 );
220​
221 it.effect("retries HTTP readiness before reporting the backend ready", () =>
222 Effect.gen(function* () {
223 const requestUrls: Array<string> = [];
224 const statuses = [503, 200];
225 let readyCount = 0;
226 const firstRequest = yield* Deferred.make<void>();
227 const ready = yield* Deferred.make<void>();
228 const exited = yield* Queue.unbounded<void>();
229​
230 const spawnerLayer = Layer.succeed(
231 ChildProcessSpawner.ChildProcessSpawner,
232 ChildProcessSpawner.make(() =>
233 Effect.succeed(
234 makeProcess({
235 exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
236 }),
237 ),
238 ),
239 );
240​
241 const managerLayer = makeManagerLayer({
242 spawnerLayer,
243 httpClientLayer: httpClientLayer((request) =>
244 Effect.gen(function* () {
245 const status = statuses.shift();
246 assert.isDefined(status);
247 requestUrls.push(request.url);
248 yield* Deferred.succeed(firstRequest, void 0);
249 return responseForRequest(request, status);
250 }),
251 ),
252 desktopWindow: {
253 handleBackendReady: Effect.sync(() => {
254 readyCount += 1;
255 }).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
256 },
257 backendOutputLog: {
258 writeSessionBoundary: ({ phase }) =>
259 phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
260 },
261 });
262​
263 yield* Effect.gen(function* () {
264 const manager = yield* DesktopBackendManager.DesktopBackendManager;
265 yield* manager.start;
266 yield* Deferred.await(firstRequest);
267​
268 assert.equal(readyCount, 0);
269 assert.deepEqual(requestUrls, ["http://127.0.0.1:3773/.well-known/t3/environment"]);
270​
271 yield* TestClock.adjust(Duration.millis(100));
272 yield* Queue.take(exited);
273​
274 assert.equal(readyCount, 1);
275 assert.deepEqual(requestUrls, [
276 "http://127.0.0.1:3773/.well-known/t3/environment",
277 "http://127.0.0.1:3773/.well-known/t3/environment",
278 ]);
279 }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
280 }),
281 );
282​
283 it.effect("starts the configured backend and closes the scoped process on stop", () =>
284 Effect.gen(function* () {
285 let startCount = 0;
286 let closedCount = 0;
287 const closed = yield* Deferred.make<void>();
288 const startedPids = yield* Queue.unbounded<number>();
289 const ready = yield* Deferred.make<void>();
290 const backendReady = yield* Ref.make(false);
291 const quitting = yield* Ref.make(false);
292​
293 const spawnerLayer = Layer.succeed(
294 ChildProcessSpawner.ChildProcessSpawner,
295 ChildProcessSpawner.make(() =>
296 Effect.gen(function* () {
297 const scope = yield* Scope.Scope;
298 startCount += 1;
299 yield* Queue.offer(startedPids, 123);
300 const close = Effect.sync(() => {
301 closedCount += 1;
302 }).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
303​
304 yield* Scope.addFinalizer(scope, close);
305​
306 return makeProcess({
307 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
308 kill: () => close,
309 });
310 }),
311 ),
312 );
313​
314 const managerLayer = makeManagerLayer({
315 spawnerLayer,
316 desktopState: {
317 backendReady,
318 quitting,
319 },
320 desktopWindow: {
321 handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid),
322 },
323 });
324​
325 yield* Effect.gen(function* () {
326 const manager = yield* DesktopBackendManager.DesktopBackendManager;
327 assert.isTrue(Option.isNone(yield* manager.currentConfig));
328​
329 yield* manager.start;
330 assert.equal(yield* Queue.take(startedPids), 123);
331 yield* Deferred.await(ready);
332 assert.isTrue(yield* Ref.get(backendReady));
333 assert.deepEqual(yield* manager.currentConfig, Option.some(baseConfig));
334​
335 const runningSnapshot = yield* manager.snapshot;
336 assert.equal(runningSnapshot.ready, true);
337 assert.deepEqual(runningSnapshot.activePid, Option.some(123));
338​
339 yield* manager.stop();
340 assert.equal(startCount, 1);
341 assert.equal(closedCount, 1);
342​
343 const stoppedSnapshot = yield* manager.snapshot;
344 assert.isFalse(yield* Ref.get(backendReady));
345 assert.equal(stoppedSnapshot.desiredRunning, false);
346 assert.equal(stoppedSnapshot.ready, false);
347 assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
348 }).pipe(Effect.provide(managerLayer));
349 }),
350 );
351​
352 it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
353 Effect.gen(function* () {
354 const starts = yield* Queue.unbounded<number>();
355 let startCount = 0;
356​
357 const spawnerLayer = Layer.succeed(
358 ChildProcessSpawner.ChildProcessSpawner,
359 ChildProcessSpawner.make(() =>
360 Effect.sync(() => {
361 startCount += 1;
362 return makeProcess({
363 exitCode: Queue.offer(starts, startCount).pipe(
364 Effect.as(ChildProcessSpawner.ExitCode(1)),
365 ),
366 });
367 }),
368 ),
369 );
370​
371 const managerLayer = makeManagerLayer({
372 spawnerLayer,
373 httpClientLayer: httpClientLayer(() => Effect.never),
374 });
375​
376 yield* Effect.gen(function* () {
377 const manager = yield* DesktopBackendManager.DesktopBackendManager;
378 yield* manager.start;
379​
380 assert.equal(yield* Queue.take(starts), 1);
381​
382 yield* TestClock.adjust(Duration.millis(499));
383 assert.equal(yield* Queue.size(starts), 0);
384 yield* TestClock.adjust(Duration.millis(1));
385 assert.equal(yield* Queue.take(starts), 2);
386​
387 yield* TestClock.adjust(Duration.millis(999));
388 assert.equal(yield* Queue.size(starts), 0);
389 yield* TestClock.adjust(Duration.millis(1));
390 assert.equal(yield* Queue.take(starts), 3);
391 }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
392 }),
393 );
394​
395 it.effect("cancels a scheduled restart when start is requested manually", () =>
396 Effect.gen(function* () {
397 const starts = yield* Queue.unbounded<number>();
398 const secondClosed = yield* Deferred.make<void>();
399 let startCount = 0;
400​
401 const spawnerLayer = Layer.succeed(
402 ChildProcessSpawner.ChildProcessSpawner,
403 ChildProcessSpawner.make(() =>
404 Effect.gen(function* () {
405 startCount += 1;
406 yield* Queue.offer(starts, startCount);
407​
408 if (startCount === 1) {
409 return makeProcess({
410 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
411 });
412 }
413​
414 const scope = yield* Scope.Scope;
415 const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
416 yield* Scope.addFinalizer(scope, close);
417 return makeProcess({
418 exitCode: Deferred.await(secondClosed).pipe(
419 Effect.as(ChildProcessSpawner.ExitCode(0)),
420 ),
421 kill: () => close,
422 });
423 }),
424 ),
425 );
426​
427 const managerLayer = makeManagerLayer({
428 spawnerLayer,
429 httpClientLayer: httpClientLayer(() => Effect.never),
430 });
431​
432 yield* Effect.gen(function* () {
433 const manager = yield* DesktopBackendManager.DesktopBackendManager;
434 yield* manager.start;
435​
436 assert.equal(yield* Queue.take(starts), 1);
437​
438 yield* manager.start;
439 assert.equal(yield* Queue.take(starts), 2);
440​
441 yield* manager.stop();
442 yield* TestClock.adjust(Duration.millis(500));
443​
444 assert.equal(yield* Queue.size(starts), 0);
445 }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
446 }),
447 );
448​
449 it.effect("does not restart after stop cancels a scheduled restart", () =>
450 Effect.gen(function* () {
451 const starts = yield* Queue.unbounded<number>();
452 let startCount = 0;
453​
454 const spawnerLayer = Layer.succeed(
455 ChildProcessSpawner.ChildProcessSpawner,
456 ChildProcessSpawner.make(() =>
457 Effect.sync(() => {
458 startCount += 1;
459 return makeProcess({
460 exitCode: Queue.offer(starts, startCount).pipe(
461 Effect.as(ChildProcessSpawner.ExitCode(1)),
462 ),
463 });
464 }),
465 ),
466 );
467​
468 const managerLayer = makeManagerLayer({
469 spawnerLayer,
470 httpClientLayer: httpClientLayer(() => Effect.never),
471 });
472​
473 yield* Effect.gen(function* () {
474 const manager = yield* DesktopBackendManager.DesktopBackendManager;
475 yield* manager.start;
476 assert.equal(yield* Queue.take(starts), 1);
477​
478 let restartScheduled = false;
479 while (!restartScheduled) {
480 restartScheduled = (yield* manager.snapshot).restartScheduled;
481 if (!restartScheduled) {
482 yield* Effect.yieldNow;
483 }
484 }
485​
486 yield* manager.stop();
487 yield* TestClock.adjust(Duration.millis(500));
488​
489 assert.equal(yield* Queue.size(starts), 0);
490 assert.equal((yield* manager.snapshot).desiredRunning, false);
491 }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
492 }),
493 );
494});