Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
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 backend?: Effect.Success<ReturnType<typeof makeFakeBackendProcess>>,
114): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
115 return DesktopBackendPool.layer.pipe(
116 Layer.provideMerge(
117 Layer.mergeAll(
118 FileSystem.layerNoop({ exists: () => Effect.succeed(true) }),
119 Path.layer,
120 backend?.layer ??
121 Layer.succeed(
122 ChildProcessSpawner.ChildProcessSpawner,
123 ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
124 ),
125 Layer.succeed(
126 HttpClient.HttpClient,
127 HttpClient.make((request) =>
128 backend === undefined
129 ? Effect.die("unexpected HTTP request")
130 : Effect.succeed(
131 HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
132 ),
133 ),
134 ),
135 Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
136 forInstance: () =>
137 Effect.succeed({
138 beginSession: () => Effect.void,
139 writeOutputChunk: () => Effect.void,
140 persistFailureSnapshot: () => Effect.void,
141 persistFailure: () => Effect.void,
142 discardSession: Effect.void,
143 } satisfies DesktopObservability.DesktopBackendOutputLogShape),
144 } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
145 Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
146 latest: Effect.succeedNone,
147 changes: Stream.empty,
148 encoded: Stream.empty,
149 handleControlForSource: () => Effect.void,
150 removeControlSource: () => Effect.void,
151 publishUpdateReport: () => Effect.void,
152 updateRequests: Stream.empty,
153 updateCommits: Stream.empty,
154 updateCancellations: Stream.empty,
155 }),
156 DesktopBrowserHost.layer,
157 Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
158 resolvePrimary: Effect.die("unexpected primary config resolve"),
159 resolvePrimaryLabel: Ref.get(labelRef),
160 resolveWsl: () => Effect.die("unexpected WSL config resolve"),
161 currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
162 } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
163 DesktopAppSettings.layerTest(),
164 DesktopEnvironment.layer({
165 dirname: "/repo/apps/desktop/src",
166 homeDirectory: "/home/test",
167 platform: "linux",
168 processArch: "x64",
169 appVersion: "0.0.0",
170 appPath: "/repo",
171 isPackaged: true,
172 resourcesPath: "/missing/resources",
173 runningUnderArm64Translation: false,
174 }).pipe(
175 Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
176 Layer.orDie,
177 ),
178 DesktopState.layer,
179 DesktopWslEnvironment.layerTest(),
180 ElectronDialog.layer,
181 ElectronApp.layer,
182 Layer.succeed(DesktopWindow.DesktopWindow, {
183 createMain: Effect.die("unexpected window create"),
184 ensureMain: Effect.die("unexpected window ensure"),
185 revealOrCreateMain: Effect.die("unexpected window reveal"),
186 activate: Effect.die("unexpected window activate"),
187 createMainIfBackendReady: Effect.die("unexpected window create"),
188 showConnectingSplash: Effect.void,
189 handleBackendReady: () => Effect.void,
190 handleBackendNotReady: Effect.void,
191 flushMainWindowBounds: Effect.void,
192 prepareCaptureReveal: Effect.void,
193 dispatchMenuAction: () => Effect.die("unexpected menu action"),
194 dispatchSnapShotEvent: () => Effect.void,
195 zoomMain: () => Effect.die("unexpected zoom"),
196 runMainContentsCommand: () => Effect.die("unexpected main contents command"),
197 syncAppearance: Effect.void,
198 } satisfies DesktopWindow.DesktopWindow["Service"]),
199 ),
200 ),
201 );
202}
203
204describe("DesktopBackendPool", () => {
205 it.effect("unregister during pool quit does not interrupt sibling stops", () =>
206 Effect.scoped(
207 Effect.gen(function* () {
208 const backend = yield* makeFakeBackendProcess();
209 yield* Effect.gen(function* () {
210 const pool = yield* DesktopBackendPool.DesktopBackendPool;
211 const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
212 const ready = yield* Deferred.make<void>();
213 const siblingStarted = yield* Deferred.make<void>();
214 const finishSibling = yield* Deferred.make<void>();
215 let siblingCompleted = false;
216 const instance = yield* pool.register({
217 id,
218 label: Effect.succeed("WSL (Ubuntu)"),
219 configResolve: Effect.succeed(runningConfig),
220 onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
221 });
222 yield* instance.start;
223 yield* backend.started;
224 yield* Deferred.await(ready);
225 const quitFiber = yield* Effect.all(
226 [
227 instance.stop({ timeout: Duration.seconds(5) }),
228 Deferred.succeed(siblingStarted, undefined).pipe(
229 Effect.andThen(Deferred.await(finishSibling)),
230 Effect.andThen(
231 Effect.sync(() => {
232 siblingCompleted = true;
233 }),
234 ),
235 ),
236 ],
237 { concurrency: "unbounded" },
238 ).pipe(Effect.forkChild);
239 yield* Deferred.await(siblingStarted);
240 assert.equal(yield* Queue.take(backend.signals), "SIGTERM");
241 const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild);
242 yield* TestClock.adjust(Duration.seconds(5));
243 assert.equal(yield* Queue.take(backend.signals), "SIGKILL");
244 assert.isUndefined(quitFiber.pollUnsafe());
245 assert.isUndefined(unregisterFiber.pollUnsafe());
246 assert.isTrue(yield* backend.isRunning);
247 yield* TestClock.adjust(backend.killWait);
248 yield* Fiber.join(unregisterFiber);
249 yield* Deferred.succeed(finishSibling, undefined);
250 yield* Fiber.join(quitFiber);
251
252 assert.isTrue(siblingCompleted);
253 assert.isFalse(yield* backend.isRunning);
254 assert.isTrue(Option.isNone((yield* instance.snapshot).activePid));
255 assert.isTrue(Option.isNone(yield* pool.get(id)));
256 }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), backend)));
257 }),
258 ),
259 );
260
261 it.effect("unregister stops the registered instance", () =>
262 Effect.scoped(
263 Effect.gen(function* () {
264 const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
265 const pool = yield* DesktopBackendPool.DesktopBackendPool;
266 const instance = yield* pool.register({
267 id,
268 label: Effect.succeed("WSL (Ubuntu)"),
269 configResolve: Effect.succeed({
270 ...runningConfig,
271 preflightFailure: Option.some({ reason: "WSL starting", fatal: false }),
272 }),
273 });
274 yield* instance.start;
275 assert.equal((yield* instance.snapshot).restartScheduled, true);
276
277 yield* pool.unregister(id);
278
279 const stopped = yield* instance.snapshot;
280 assert.equal(stopped.desiredRunning, false);
281 assert.equal(stopped.restartScheduled, false);
282 assert.equal(Option.isNone(yield* pool.get(id)), true);
283 }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))),
284 ),
285 );
286});