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