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

DesktopBackendPool.test.ts

481 lines19.0 KB

1import { assert, describe, it } from "@effect/vitest";
2import { DESKTOP_UPDATE_IN_PROGRESS_TTL_MS } from "@t3tools/contracts";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as Queue from "effect/Queue";
8import * as TestClock from "effect/testing/TestClock";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Ref from "effect/Ref";
14import * as Sink from "effect/Sink";
15import * as Stream from "effect/Stream";
16import { HttpClient, HttpClientResponse } from "effect/http";
17import { ChildProcessSpawner } from "effect/process";
18​
19import * as DesktopConfig from "../app/DesktopConfig.ts";
20import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
21import * as DesktopObservability from "../app/DesktopObservability.ts";
22import * as DesktopState from "../app/DesktopState.ts";
23import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
24import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
25import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
26import * as ElectronDialog from "../electron/ElectronDialog.ts";
27import * as ElectronApp from "../electron/ElectronApp.ts";
28import * as DesktopWindow from "../window/DesktopWindow.ts";
29import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
30import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
31import * as DesktopBackendPool from "./DesktopBackendPool.ts";
32import type { DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
33​
34// Models the spawner's release for a backend that ignores SIGTERM, without OS signals.
35const makeFakeBackendProcess = Effect.fn("test.makeFakeBackendProcess")(function* () {
36 const started = yield* Deferred.make<void>();
37 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
38 const signals = yield* Queue.unbounded<"SIGTERM" | "SIGKILL">();
39 let running = false;
40 const killWait = Duration.seconds(1);
41 const exit = Effect.sync(() => {
42 running = false;
43 }).pipe(Effect.andThen(Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0))), Effect.asVoid);
44 const layer = Layer.succeed(
45 ChildProcessSpawner.ChildProcessSpawner,
46 ChildProcessSpawner.make((command) =>
47 Effect.gen(function* () {
48 if (command._tag !== "StandardCommand") {
49 return yield* Effect.die("Expected a standard backend command");
50 }
51 const terminateGrace = Duration.fromInputUnsafe(command.options.forceKillAfter ?? 0);
52 running = true;
53 yield* Effect.addFinalizer(() =>
54 Effect.gen(function* () {
55 yield* Queue.offer(signals, "SIGTERM");
56 yield* Effect.sleep(terminateGrace);
57 yield* Queue.offer(signals, "SIGKILL");
58 yield* Effect.sleep(killWait);
59 yield* exit;
60 }),
61 );
62 yield* Deferred.succeed(started, undefined);
63 return ChildProcessSpawner.makeHandle({
64 pid: ChildProcessSpawner.ProcessId(123),
65 stdout: Stream.empty,
66 stderr: Stream.empty,
67 all: Stream.empty,
68 stdin: Sink.drain,
69 getInputFd: () => Sink.drain,
70 getOutputFd: () => Stream.empty,
71 exitCode: Deferred.await(exited),
72 isRunning: Effect.sync(() => running),
73 kill: () => exit,
74 unref: Effect.succeed(Effect.void),
75 });
76 }),
77 ),
78 );
79 return {
80 layer,
81 started: Deferred.await(started),
82 signals,
83 isRunning: Effect.sync(() => running),
84 killWait,
85 };
86});
87​
88const runningConfig = {
89 executablePath: "/electron",
90 args: [],
91 entryPath: "/server/bin.mjs",
92 cwd: "/server",
93 env: {},
94 bootstrap: {
95 mode: "desktop",
96 noBrowser: true,
97 port: 3774,
98 t3Home: "/tmp/t3",
99 host: "127.0.0.1",
100 desktopBootstrapToken: "token",
101 tailscaleServeEnabled: false,
102 tailscaleServePort: 443,
103 },
104 bootstrapDelivery: "fd3",
105 extendEnv: true,
106 httpBaseUrl: new URL("http://127.0.0.1:3774"),
107 captureOutput: false,
108 preflightFailure: Option.none(),
109} satisfies DesktopBackendStartConfig;
110​
111function layerPool(
112 labelRef: Ref.Ref<string>,
113 options: {
114 readonly config?: DesktopBackendStartConfig;
115 readonly fileSystem?: Partial<FileSystem.FileSystem>;
116 readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
117 readonly httpClient?: HttpClient.HttpClient;
118 readonly onReady?: Effect.Effect<void>;
119 readonly backend?: Effect.Success<ReturnType<typeof makeFakeBackendProcess>>;
120 } = {},
121): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
122 return DesktopBackendPool.layer.pipe(
123 Layer.provideMerge(
124 Layer.mergeAll(
125 DesktopEnvironment.layer({
126 dirname: "/repo/apps/desktop/src",
127 homeDirectory: "/test-home",
128 platform: "linux",
129 processArch: "x64",
130 appVersion: "1.2.3",
131 appPath: "/repo",
132 isPackaged: true,
133 resourcesPath: "/missing/resources",
134 runningUnderArm64Translation: false,
135 }).pipe(
136 Layer.provide(
137 Layer.mergeAll(Path.layer, DesktopConfig.layerTest({ T3CODE_HOME: "/test-home" })),
138 ),
139 Layer.orDie,
140 ),
141 FileSystem.layerNoop(options.fileSystem ?? { exists: () => Effect.succeed(true) }),
142 Path.layer,
143 options.backend?.layer ??
144 Layer.succeed(
145 ChildProcessSpawner.ChildProcessSpawner,
146 options.spawner ??
147 ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
148 ),
149 Layer.succeed(
150 HttpClient.HttpClient,
151 options.httpClient ??
152 HttpClient.make((request) =>
153 options.backend === undefined
154 ? Effect.die("unexpected HTTP request")
155 : Effect.succeed(
156 HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
157 ),
158 ),
159 ),
160 Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
161 forInstance: () =>
162 Effect.succeed({
163 beginSession: () => Effect.void,
164 writeOutputChunk: () => Effect.void,
165 persistFailureSnapshot: () => Effect.void,
166 persistFailure: () => Effect.void,
167 discardSession: Effect.void,
168 } satisfies DesktopObservability.DesktopBackendOutputLogShape),
169 } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
170 Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
171 latest: Effect.succeedNone,
172 changes: Stream.empty,
173 encoded: Stream.empty,
174 handleControlForSource: () => Effect.void,
175 removeControlSource: () => Effect.void,
176 publishUpdateReport: () => Effect.void,
177 updateRequests: Stream.empty,
178 updateCommits: Stream.empty,
179 updateCancellations: Stream.empty,
180 }),
181 DesktopBrowserHost.layer,
182 Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
183 resolvePrimary: options.config
184 ? Effect.succeed(options.config)
185 : Effect.die("unexpected primary config resolve"),
186 resolvePrimaryLabel: Ref.get(labelRef),
187 resolveWsl: () => Effect.die("unexpected WSL config resolve"),
188 currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
189 } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
190 DesktopAppSettings.layerTest(),
191 DesktopState.layer,
192 DesktopWslEnvironment.layerTest(),
193 ElectronDialog.layer,
194 ElectronApp.layer,
195 Layer.succeed(DesktopWindow.DesktopWindow, {
196 createMain: Effect.die("unexpected window create"),
197 ensureMain: Effect.die("unexpected window ensure"),
198 revealOrCreateMain: Effect.die("unexpected window reveal"),
199 activate: Effect.die("unexpected window activate"),
200 createMainIfBackendReady: Effect.die("unexpected window create"),
201 showConnectingSplash: Effect.void,
202 handleBackendReady: () => options.onReady ?? Effect.void,
203 handleBackendNotReady: Effect.void,
204 flushMainWindowBounds: Effect.void,
205 prepareCaptureReveal: Effect.void,
206 dispatchMenuAction: () => Effect.die("unexpected menu action"),
207 dispatchSnapShotEvent: () => Effect.void,
208 zoomMain: () => Effect.die("unexpected zoom"),
209 runMainContentsCommand: () => Effect.die("unexpected main contents command"),
210 syncAppearance: Effect.void,
211 } satisfies DesktopWindow.DesktopWindow["Service"]),
212 ),
213 ),
214 );
216​
217const markerPath = "/test-home/runtime/desktop-update-in-progress";
218const runtimePath = "/test-home/userdata/server-runtime.json";
219​
220const makeUpdateMarkerFixture = () =>
221 Effect.gen(function* () {
222 const allowReady = yield* Deferred.make<void>();
223 const runtimeChecked = yield* Deferred.make<void>();
224 const markerRemoved = yield* Deferred.make<void>();
225 const readyRuns = yield* Queue.unbounded<void>();
226 let nextPid = 123;
227 const files = new Map([[markerPath, JSON.stringify({ startedAt: 0, expiresAt: 60_000 })]]);
228 const removed: string[] = [];
229 const config: DesktopBackendStartConfig = {
230 executablePath: "/electron",
231 args: [],
232 entryPath: "/server/bin.mjs",
233 cwd: "/server",
234 env: {},
235 bootstrap: {
236 mode: "desktop",
237 noBrowser: true,
238 port: 3774,
239 t3Home: "/test-home",
240 host: "127.0.0.1",
241 desktopBootstrapToken: "token",
242 tailscaleServeEnabled: false,
243 tailscaleServePort: 443,
244 },
245 bootstrapDelivery: "fd3",
246 extendEnv: true,
247 httpBaseUrl: new URL("http://127.0.0.1:3774"),
248 captureOutput: false,
249 preflightFailure: Option.none(),
250 };
251 const layer = layerPool(Ref.makeUnsafe("Local"), {
252 config,
253 fileSystem: {
254 exists: (path) => Effect.succeed(files.has(path) || path === config.entryPath),
255 readFileString: (path) =>
256 (path === runtimePath ? Deferred.succeed(runtimeChecked, undefined) : Effect.void).pipe(
257 Effect.andThen(Effect.sync(() => files.get(path) ?? "")),
258 ),
259 remove: (path) =>
260 Effect.sync(() => {
261 removed.push(path);
262 files.delete(path);
263 }).pipe(
264 Effect.andThen(
265 path === markerPath ? Deferred.succeed(markerRemoved, undefined) : Effect.void,
266 ),
267 Effect.asVoid,
268 ),
269 },
270 spawner: ChildProcessSpawner.make(() =>
271 Effect.gen(function* () {
272 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
273 const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
274 Effect.asVoid,
275 );
276 // Like the real spawner, closing the run's scope ends the process.
277 yield* Effect.addFinalizer(() => exit);
278 return ChildProcessSpawner.makeHandle({
279 pid: ChildProcessSpawner.ProcessId(nextPid++),
280 stdout: Stream.empty,
281 stderr: Stream.empty,
282 all: Stream.empty,
283 exitCode: Deferred.await(exited),
284 isRunning: Effect.succeed(true),
285 kill: () => exit,
286 stdin: Sink.drain,
287 getInputFd: () => Sink.drain,
288 getOutputFd: () => Stream.empty,
289 unref: Effect.succeed(Effect.void),
290 });
291 }),
292 ),
293 httpClient: HttpClient.make((request) =>
294 Deferred.await(allowReady).pipe(
295 Effect.as(HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }))),
296 ),
297 ),
298 onReady: Queue.offer(readyRuns, undefined).pipe(Effect.asVoid),
299 });
300 const publishRuntime = (pid: number) =>
301 files.set(
302 runtimePath,
303 JSON.stringify({
304 version: 1,
305 pid,
306 port: 3774,
307 origin: "http://127.0.0.1:3774",
308 startedAt: "2026-10-27T00:00:00.000Z",
309 }),
310 );
311 return {
312 layer,
313 files,
314 removed,
315 allowReady,
316 readyRuns,
317 runtimeChecked,
318 markerRemoved,
319 publishRuntime,
320 };
321 });
322​
323describe("DesktopBackendPool", () => {
324 it.effect(
325 "keeps the update marker after HTTP readiness until the backend publishes its runtime",
326 () =>
327 Effect.gen(function* () {
328 const fixture = yield* makeUpdateMarkerFixture();
329 yield* Effect.gen(function* () {
330 const pool = yield* DesktopBackendPool.DesktopBackendPool;
331 const primary = yield* pool.primary;
332 yield* primary.start;
333 yield* Deferred.succeed(fixture.allowReady, undefined);
334 yield* Queue.take(fixture.readyRuns);
335 assert.isTrue(
336 fixture.files.has(markerPath),
337 "a launcher could neither wait nor adopt between readiness and publication",
338 );
339 yield* Deferred.await(fixture.runtimeChecked);
340 yield* TestClock.adjust(Duration.seconds(5));
341 assert.isTrue(fixture.files.has(markerPath));
342 fixture.publishRuntime(456);
343 yield* TestClock.adjust(Duration.seconds(1));
344 assert.isTrue(
345 fixture.files.has(markerPath),
346 "another process's runtime is not the replacement",
347 );
348 fixture.publishRuntime(123);
349 yield* TestClock.adjust(Duration.seconds(1));
350 yield* Deferred.await(fixture.markerRemoved);
351 assert.deepEqual(fixture.removed, [markerPath]);
352 }).pipe(Effect.provide(fixture.layer));
353 }),
354 );
355​
356 it.effect("leaves a replacement update marker written while an earlier wait is pending", () =>
357 Effect.gen(function* () {
358 const fixture = yield* makeUpdateMarkerFixture();
359 yield* Effect.gen(function* () {
360 const pool = yield* DesktopBackendPool.DesktopBackendPool;
361 const primary = yield* pool.primary;
362 yield* primary.start;
363 yield* Deferred.succeed(fixture.allowReady, undefined);
364 yield* Queue.take(fixture.readyRuns);
365 yield* Deferred.await(fixture.runtimeChecked);
366 yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS - 1_000));
367 const replacement = JSON.stringify({ startedAt: 59_000, expiresAt: 119_000 });
368 fixture.files.set(markerPath, replacement);
369 yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS));
370 assert.equal(fixture.files.get(markerPath), replacement);
371 assert.deepEqual(fixture.removed, []);
372 }).pipe(Effect.provide(fixture.layer));
373 }),
374 );
375​
376 it.effect("a later backend run's readiness supersedes the earlier run's marker wait", () =>
377 Effect.gen(function* () {
378 const fixture = yield* makeUpdateMarkerFixture();
379 yield* Effect.gen(function* () {
380 const pool = yield* DesktopBackendPool.DesktopBackendPool;
381 const primary = yield* pool.primary;
382 yield* primary.start;
383 yield* Deferred.succeed(fixture.allowReady, undefined);
384 yield* Queue.take(fixture.readyRuns);
385 yield* Deferred.await(fixture.runtimeChecked);
386 yield* TestClock.adjust(Duration.seconds(30));
387 yield* primary.stop();
388 yield* primary.start;
389 yield* Queue.take(fixture.readyRuns);
390 yield* TestClock.adjust(Duration.seconds(31));
391 assert.isTrue(
392 fixture.files.has(markerPath),
393 "the earlier run's wait must not end the later run's handoff",
394 );
395 assert.deepEqual(fixture.removed, []);
396 fixture.publishRuntime(124);
397 yield* TestClock.adjust(Duration.millis(100));
398 yield* Deferred.await(fixture.markerRemoved);
399 assert.deepEqual(fixture.removed, [markerPath]);
400 }).pipe(Effect.provide(fixture.layer));
401 }),
402 );
403​
404 it.effect("unregister during pool quit does not interrupt sibling stops", () =>
405 Effect.gen(function* () {
406 const backend = yield* makeFakeBackendProcess();
407 yield* Effect.gen(function* () {
408 const pool = yield* DesktopBackendPool.DesktopBackendPool;
409 const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
410 const ready = yield* Deferred.make<void>();
411 const siblingStarted = yield* Deferred.make<void>();
412 const finishSibling = yield* Deferred.make<void>();
413 let siblingCompleted = false;
414 const instance = yield* pool.register({
415 id,
416 label: Effect.succeed("WSL (Ubuntu)"),
417 configResolve: Effect.succeed(runningConfig),
418 onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
419 });
420 yield* instance.start;
421 yield* backend.started;
422 yield* Deferred.await(ready);
423 const quitFiber = yield* Effect.all(
424 [
425 instance.stop({ timeout: Duration.seconds(5) }),
426 Deferred.succeed(siblingStarted, undefined).pipe(
427 Effect.andThen(Deferred.await(finishSibling)),
428 Effect.andThen(
429 Effect.sync(() => {
430 siblingCompleted = true;
431 }),
432 ),
433 ),
434 ],
435 { concurrency: "unbounded" },
436 ).pipe(Effect.forkChild);
437 yield* Deferred.await(siblingStarted);
438 assert.equal(yield* Queue.take(backend.signals), "SIGTERM");
439 const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild);
440 yield* TestClock.adjust(Duration.seconds(5));
441 assert.equal(yield* Queue.take(backend.signals), "SIGKILL");
442 assert.isUndefined(quitFiber.pollUnsafe());
443 assert.isUndefined(unregisterFiber.pollUnsafe());
444 assert.isTrue(yield* backend.isRunning);
445 yield* TestClock.adjust(backend.killWait);
446 yield* Fiber.join(unregisterFiber);
447 yield* Deferred.succeed(finishSibling, undefined);
448 yield* Fiber.join(quitFiber);
449​
450 assert.isTrue(siblingCompleted);
451 assert.isFalse(yield* backend.isRunning);
452 assert.isTrue(Option.isNone((yield* instance.snapshot).activePid));
453 assert.isTrue(Option.isNone(yield* pool.get(id)));
454 }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), { backend })));
455 }),
456 );
457​
458 it.effect("unregister stops the registered instance", () =>
459 Effect.gen(function* () {
460 const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
461 const pool = yield* DesktopBackendPool.DesktopBackendPool;
462 const instance = yield* pool.register({
463 id,
464 label: Effect.succeed("WSL (Ubuntu)"),
465 configResolve: Effect.succeed({
466 ...runningConfig,
467 preflightFailure: Option.some({ reason: "WSL starting", fatal: false }),
468 }),
469 });
470 yield* instance.start;
471 assert.equal((yield* instance.snapshot).restartScheduled, true);
472​
473 yield* pool.unregister(id);
474​
475 const stopped = yield* instance.snapshot;
476 assert.equal(stopped.desiredRunning, false);
477 assert.equal(stopped.restartScheduled, false);
478 assert.equal(Option.isNone(yield* pool.get(id)), true);
479 }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))),
480 );
481});