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 * 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 DesktopObservability from "../app/DesktopObservability.ts";
24
25const decodeDesktopBackendBootstrap = Schema.decodeEffect(
26 Schema.fromJsonString(DesktopBackendBootstrap),
27);
28
29const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
30 executablePath: "/electron",
31 args: ["/server/bin.mjs", "--bootstrap-fd", "3"],
32 entryPath: "/server/bin.mjs",
33 cwd: "/server",
34 env: { ELECTRON_RUN_AS_NODE: "1" },
35 bootstrap: {
36 mode: "desktop",
37 noBrowser: true,
38 port: 3773,
39 t3Home: "/tmp/t3",
40 host: "127.0.0.1",
41 desktopBootstrapToken: "token",
42 tailscaleServeEnabled: false,
43 tailscaleServePort: 443,
44 },
45 bootstrapDelivery: "fd3",
46 extendEnv: true,
47 httpBaseUrl: new URL("http://127.0.0.1:3773"),
48 captureOutput: true,
49 preflightFailure: Option.none(),
50};
51
52const configWithObservability: DesktopBackendBootstrapValue = {
53 ...baseConfig.bootstrap,
54 tailscaleServeEnabled: true,
55 otlpTracesUrl: "http://127.0.0.1:4318/v1/traces",
56};
57
58function makeProcess(options?: {
59 readonly stdout?: Stream.Stream<Uint8Array>;
60 readonly stderr?: Stream.Stream<Uint8Array>;
61 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
62 readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
63}): ChildProcessSpawner.ChildProcessHandle {
64 return ChildProcessSpawner.makeHandle({
65 pid: ChildProcessSpawner.ProcessId(123),
66 stdout: options?.stdout ?? Stream.empty,
67 stderr: options?.stderr ?? Stream.empty,
68 all: Stream.merge(options?.stdout ?? Stream.empty, options?.stderr ?? Stream.empty),
69 exitCode: options?.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(0)),
70 isRunning: Effect.succeed(false),
71 kill: options?.kill ?? (() => Effect.void),
72 stdin: Sink.drain,
73 getInputFd: () => Sink.drain,
74 getOutputFd: () => Stream.empty,
75 unref: Effect.succeed(Effect.void),
76 });
77}
78
79function responseForRequest(
80 request: HttpClientRequest.HttpClientRequest,
81 status: number,
82): HttpClientResponse.HttpClientResponse {
83 return HttpClientResponse.fromWeb(request, new Response(null, { status }));
84}
85
86function httpClientLayer(
87 handler: (
88 request: HttpClientRequest.HttpClientRequest,
89 ) => Effect.Effect<HttpClientResponse.HttpClientResponse>,
90) {
91 return Layer.succeed(
92 HttpClient.HttpClient,
93 HttpClient.make((request) => handler(request)),
94 );
95}
96
97const healthyHttpClientLayer = httpClientLayer((request) =>
98 Effect.succeed(responseForRequest(request, 200)),
99);
100
101function decodeBootstrap(raw: string) {
102 return decodeDesktopBackendBootstrap(raw);
103}
104
105interface MakeInstanceInput {
106 readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
107 readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
108 readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
109 readonly onReady?: Effect.Effect<void>;
110 readonly onShutdown?: Effect.Effect<void>;
111 readonly onPreflightFailed?: (
112 failure: DesktopBackendManager.PreflightFailure,
113 ) => Effect.Effect<boolean>;
114 readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
115 readonly configResolve?: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
116}
117
118// Helper that constructs a primary backend instance using the factory
119// directly. The factory's deps (FileSystem, ChildProcessSpawner,
120// HttpClient, DesktopBackendOutputLogFactory) are provided per-test via
121// a scoped layer; tests yield the returned Effect inside `Effect.scoped`
122// to drive the instance's lifecycle.
123function makeTestInstance(input: MakeInstanceInput) {
124 const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
125 writeSessionBoundary: () => Effect.void,
126 writeOutputChunk: () => Effect.void,
127 ...input.backendOutputLog,
128 };
129 const servicesLayer = Layer.mergeAll(
130 FileSystem.layerNoop({
131 exists: () => Effect.succeed(true),
132 }),
133 input.spawnerLayer,
134 input.httpClientLayer ?? healthyHttpClientLayer,
135 Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
136 forInstance: () => Effect.succeed(stubLog),
137 } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
138 );
139
140 const instance = DesktopBackendManager.makeBackendInstance({
141 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
142 label: Effect.succeed("Windows"),
143 configResolve: input.configResolve ?? Effect.succeed(input.config ?? baseConfig),
144 ...(input.onReady ? { onReady: () => input.onReady! } : {}),
145 ...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}),
146 ...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}),
147 });
148
149 return instance.pipe(Effect.provide(servicesLayer));
150}
151
152describe("DesktopBackendManager", () => {
153 it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
154 Effect.scoped(
155 Effect.gen(function* () {
156 let spawnedCommand: ChildProcess.Command | undefined;
157 let bootstrapJson = "";
158 let readyCount = 0;
159 const ready = yield* Deferred.make<void>();
160 const exited = yield* Queue.unbounded<void>();
161
162 const spawnerLayer = Layer.succeed(
163 ChildProcessSpawner.ChildProcessSpawner,
164 ChildProcessSpawner.make((command) =>
165 Effect.gen(function* () {
166 spawnedCommand = command;
167 if (command._tag === "StandardCommand") {
168 const fd3 = command.options.additionalFds?.fd3;
169 if (fd3?.type === "input" && fd3.stream) {
170 bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
171 }
172 }
173
174 return makeProcess({
175 exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
176 });
177 }),
178 ),
179 );
180
181 const instance = yield* makeTestInstance({
182 config: {
183 ...baseConfig,
184 bootstrap: configWithObservability,
185 },
186 spawnerLayer,
187 onReady: Effect.sync(() => {
188 readyCount += 1;
189 }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
190 backendOutputLog: {
191 writeSessionBoundary: ({ phase }) =>
192 phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
193 },
194 });
195
196 yield* instance.start;
197 yield* Queue.take(exited);
198
199 assert.equal(readyCount, 1);
200 assert.isDefined(spawnedCommand);
201 if (spawnedCommand._tag !== "StandardCommand") {
202 throw new Error("Expected backend to spawn a standard command.");
203 }
204
205 assert.equal(spawnedCommand.command, "/electron");
206 assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]);
207 assert.equal(spawnedCommand.options.cwd, "/server");
208 assert.equal(spawnedCommand.options.extendEnv, true);
209 assert.equal(spawnedCommand.options.stdout, "pipe");
210 assert.equal(spawnedCommand.options.stderr, "pipe");
211 assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
212 assert.isDefined(spawnedCommand.options.forceKillAfter);
213 assert.equal(
214 Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
215 2_000,
216 );
217
218 assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
219 }),
220 ),
221 );
222
223 it.effect("retries HTTP readiness before reporting the backend ready", () =>
224 Effect.scoped(
225 Effect.gen(function* () {
226 const requestUrls: Array<string> = [];
227 const statuses = [503, 200];
228 let readyCount = 0;
229 const firstRequest = yield* Deferred.make<void>();
230 const ready = yield* Deferred.make<void>();
231 const exited = yield* Queue.unbounded<void>();
232
233 const spawnerLayer = Layer.succeed(
234 ChildProcessSpawner.ChildProcessSpawner,
235 ChildProcessSpawner.make(() =>
236 Effect.succeed(
237 makeProcess({
238 exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
239 }),
240 ),
241 ),
242 );
243
244 const instance = yield* makeTestInstance({
245 spawnerLayer,
246 httpClientLayer: httpClientLayer((request) =>
247 Effect.gen(function* () {
248 const status = statuses.shift();
249 assert.isDefined(status);
250 requestUrls.push(request.url);
251 yield* Deferred.succeed(firstRequest, void 0);
252 return responseForRequest(request, status);
253 }),
254 ),
255 onReady: Effect.sync(() => {
256 readyCount += 1;
257 }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
258 backendOutputLog: {
259 writeSessionBoundary: ({ phase }) =>
260 phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
261 },
262 });
263
264 yield* instance.start;
265 yield* Deferred.await(firstRequest);
266
267 assert.equal(readyCount, 0);
268 assert.deepEqual(requestUrls, ["http://127.0.0.1:3773/.well-known/t3/environment"]);
269
270 yield* TestClock.adjust(Duration.millis(100));
271 yield* Queue.take(exited);
272
273 assert.equal(readyCount, 1);
274 assert.deepEqual(requestUrls, [
275 "http://127.0.0.1:3773/.well-known/t3/environment",
276 "http://127.0.0.1:3773/.well-known/t3/environment",
277 ]);
278 }).pipe(Effect.provide(TestClock.layer())),
279 ),
280 );
281
282 it.effect("starts the configured backend and closes the scoped process on stop", () =>
283 Effect.scoped(
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 backendReadyFlag = yield* Ref.make(false);
291
292 const spawnerLayer = Layer.succeed(
293 ChildProcessSpawner.ChildProcessSpawner,
294 ChildProcessSpawner.make(() =>
295 Effect.gen(function* () {
296 const scope = yield* Scope.Scope;
297 startCount += 1;
298 yield* Queue.offer(startedPids, 123);
299 const close = Effect.sync(() => {
300 closedCount += 1;
301 }).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
302
303 yield* Scope.addFinalizer(scope, close);
304
305 return makeProcess({
306 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
307 kill: () => close,
308 });
309 }),
310 ),
311 );
312
313 const instance = yield* makeTestInstance({
314 spawnerLayer,
315 onReady: Ref.set(backendReadyFlag, true).pipe(
316 Effect.andThen(Deferred.succeed(ready, void 0)),
317 Effect.asVoid,
318 ),
319 onShutdown: Ref.set(backendReadyFlag, false),
320 });
321 assert.isTrue(Option.isNone(yield* instance.currentConfig));
322
323 yield* instance.start;
324 assert.equal(yield* Queue.take(startedPids), 123);
325 yield* Deferred.await(ready);
326 assert.isTrue(yield* Ref.get(backendReadyFlag));
327 assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
328
329 const runningSnapshot = yield* instance.snapshot;
330 assert.equal(runningSnapshot.ready, true);
331 assert.deepEqual(runningSnapshot.activePid, Option.some(123));
332
333 yield* instance.stop();
334 assert.equal(startCount, 1);
335 assert.equal(closedCount, 1);
336
337 const stoppedSnapshot = yield* instance.snapshot;
338 assert.isFalse(yield* Ref.get(backendReadyFlag));
339 assert.equal(stoppedSnapshot.desiredRunning, false);
340 assert.equal(stoppedSnapshot.ready, false);
341 assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
342 }),
343 ),
344 );
345
346 it.effect("does not notify shutdown before the first start has prior state", () =>
347 Effect.scoped(
348 Effect.gen(function* () {
349 let shutdownCount = 0;
350 const closed = yield* Deferred.make<void>();
351 const startedPids = yield* Queue.unbounded<number>();
352
353 const spawnerLayer = Layer.succeed(
354 ChildProcessSpawner.ChildProcessSpawner,
355 ChildProcessSpawner.make(() =>
356 Effect.gen(function* () {
357 yield* Queue.offer(startedPids, 123);
358 const close = Deferred.succeed(closed, void 0).pipe(Effect.asVoid);
359 return makeProcess({
360 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
361 kill: () => close,
362 });
363 }),
364 ),
365 );
366
367 const instance = yield* makeTestInstance({
368 spawnerLayer,
369 httpClientLayer: httpClientLayer(() => Effect.never),
370 onShutdown: Effect.sync(() => {
371 shutdownCount += 1;
372 }),
373 });
374
375 yield* instance.start;
376 assert.equal(yield* Queue.take(startedPids), 123);
377 assert.equal(shutdownCount, 0);
378 }),
379 ),
380 );
381
382 it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
383 Effect.scoped(
384 Effect.gen(function* () {
385 const starts = yield* Queue.unbounded<number>();
386 let startCount = 0;
387
388 const spawnerLayer = Layer.succeed(
389 ChildProcessSpawner.ChildProcessSpawner,
390 ChildProcessSpawner.make(() =>
391 Effect.sync(() => {
392 startCount += 1;
393 return makeProcess({
394 exitCode: Queue.offer(starts, startCount).pipe(
395 Effect.as(ChildProcessSpawner.ExitCode(1)),
396 ),
397 });
398 }),
399 ),
400 );
401
402 const instance = yield* makeTestInstance({
403 spawnerLayer,
404 httpClientLayer: httpClientLayer(() => Effect.never),
405 });
406
407 yield* instance.start;
408
409 assert.equal(yield* Queue.take(starts), 1);
410
411 yield* TestClock.adjust(Duration.millis(499));
412 assert.equal(yield* Queue.size(starts), 0);
413 yield* TestClock.adjust(Duration.millis(1));
414 assert.equal(yield* Queue.take(starts), 2);
415
416 yield* TestClock.adjust(Duration.millis(999));
417 assert.equal(yield* Queue.size(starts), 0);
418 yield* TestClock.adjust(Duration.millis(1));
419 assert.equal(yield* Queue.take(starts), 3);
420 }).pipe(Effect.provide(TestClock.layer())),
421 ),
422 );
423
424 it.effect("does not notify shutdown when a scheduled restart starts from non-ready state", () =>
425 Effect.scoped(
426 Effect.gen(function* () {
427 let shutdownCount = 0;
428
429 const spawnerLayer = Layer.succeed(
430 ChildProcessSpawner.ChildProcessSpawner,
431 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
432 );
433
434 const instance = yield* makeTestInstance({
435 spawnerLayer,
436 config: {
437 ...baseConfig,
438 preflightFailure: Option.some({ reason: "preflight failed", fatal: false }),
439 },
440 onShutdown: Effect.sync(() => {
441 shutdownCount += 1;
442 }),
443 });
444
445 yield* instance.start;
446 assert.equal(shutdownCount, 0);
447
448 yield* TestClock.adjust(Duration.millis(500));
449 assert.equal(shutdownCount, 0);
450 }).pipe(Effect.provide(TestClock.layer())),
451 ),
452 );
453
454 it.effect("surfaces a fatal preflight failure once and stops looping after the cap", () =>
455 Effect.scoped(
456 Effect.gen(function* () {
457 const failures: string[] = [];
458 const spawnerLayer = Layer.succeed(
459 ChildProcessSpawner.ChildProcessSpawner,
460 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
461 );
462
463 const instance = yield* makeTestInstance({
464 spawnerLayer,
465 config: {
466 ...baseConfig,
467 preflightFailure: Option.some({ reason: "Node.js not found", fatal: true }),
468 },
469 onPreflightFailed: (failure) =>
470 Effect.sync(() => {
471 failures.push(failure.reason);
472 }).pipe(Effect.as(false)),
473 });
474
475 yield* instance.start;
476 assert.deepEqual(failures, []);
477
478 // Five fatal attempts with exponential backoff (500ms, 1s, 2s, 4s) reach
479 // the cap, at which point the failure is surfaced exactly once.
480 yield* TestClock.adjust(Duration.millis(500));
481 yield* TestClock.adjust(Duration.seconds(1));
482 yield* TestClock.adjust(Duration.seconds(2));
483 yield* TestClock.adjust(Duration.seconds(4));
484 assert.deepEqual(failures, ["Node.js not found"]);
485
486 // Past the cap the loop stops and nothing else is surfaced.
487 yield* TestClock.adjust(Duration.seconds(8));
488 yield* TestClock.adjust(Duration.seconds(30));
489 assert.deepEqual(failures, ["Node.js not found"]);
490 }).pipe(Effect.provide(TestClock.layer())),
491 ),
492 );
493
494 it.effect("can be started again after a fatal preflight cap once config recovers", () =>
495 Effect.scoped(
496 Effect.gen(function* () {
497 const failing = yield* Ref.make(true);
498 const starts = yield* Queue.unbounded<number>();
499 const spawnerLayer = Layer.succeed(
500 ChildProcessSpawner.ChildProcessSpawner,
501 ChildProcessSpawner.make(() =>
502 Queue.offer(starts, 123).pipe(
503 Effect.as(
504 makeProcess({
505 exitCode: Effect.never,
506 }),
507 ),
508 ),
509 ),
510 );
511
512 const instance = yield* makeTestInstance({
513 spawnerLayer,
514 configResolve: Ref.get(failing).pipe(
515 Effect.map((isFailing) =>
516 isFailing
517 ? {
518 ...baseConfig,
519 preflightFailure: Option.some({
520 reason: "Node.js not found",
521 fatal: true,
522 }),
523 }
524 : baseConfig,
525 ),
526 ),
527 });
528
529 yield* instance.start;
530 yield* TestClock.adjust(Duration.millis(500));
531 yield* TestClock.adjust(Duration.seconds(1));
532 yield* TestClock.adjust(Duration.seconds(2));
533 yield* TestClock.adjust(Duration.seconds(4));
534 yield* TestClock.adjust(Duration.seconds(8));
535
536 const parked = yield* instance.snapshot;
537 assert.equal(parked.desiredRunning, false);
538 assert.equal(parked.ready, false);
539 assert.isTrue(Option.isNone(parked.activePid));
540 assert.equal(parked.restartScheduled, false);
541 assert.equal(yield* Queue.size(starts), 0);
542
543 yield* Ref.set(failing, false);
544 yield* instance.start;
545
546 assert.equal(yield* Queue.take(starts), 123);
547 const running = yield* instance.snapshot;
548 assert.equal(running.desiredRunning, true);
549 assert.deepEqual(running.activePid, Option.some(123));
550 }).pipe(Effect.provide(TestClock.layer())),
551 ),
552 );
553
554 it.effect("keeps retrying a transient (non-fatal) preflight failure without surfacing", () =>
555 Effect.scoped(
556 Effect.gen(function* () {
557 const failures: string[] = [];
558 const spawnerLayer = Layer.succeed(
559 ChildProcessSpawner.ChildProcessSpawner,
560 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
561 );
562
563 const instance = yield* makeTestInstance({
564 spawnerLayer,
565 config: {
566 ...baseConfig,
567 preflightFailure: Option.some({ reason: "wslpath conversion failed", fatal: false }),
568 },
569 onPreflightFailed: (failure) =>
570 Effect.sync(() => {
571 failures.push(failure.reason);
572 }).pipe(Effect.as(false)),
573 });
574
575 yield* instance.start;
576 // Well beyond the fatal cap's worth of time: a transient failure must
577 // keep retrying (self-heal) and never surface.
578 yield* TestClock.adjust(Duration.minutes(2));
579 assert.deepEqual(failures, []);
580 }).pipe(Effect.provide(TestClock.layer())),
581 ),
582 );
583
584 it.effect("surfaces a bounded transient preflight failure after its retry limit", () =>
585 Effect.scoped(
586 Effect.gen(function* () {
587 const failures: string[] = [];
588 const spawnerLayer = Layer.succeed(
589 ChildProcessSpawner.ChildProcessSpawner,
590 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
591 );
592
593 const instance = yield* makeTestInstance({
594 spawnerLayer,
595 config: {
596 ...baseConfig,
597 preflightFailure: Option.some({
598 reason: "WSL toolchain probe timed out",
599 fatal: false,
600 retryLimit: 3,
601 }),
602 },
603 onPreflightFailed: (failure) =>
604 Effect.sync(() => {
605 failures.push(failure.reason);
606 }).pipe(Effect.as(false)),
607 });
608
609 yield* instance.start;
610 yield* TestClock.adjust(Duration.millis(500));
611 assert.deepEqual(failures, []);
612
613 yield* TestClock.adjust(Duration.seconds(1));
614 assert.deepEqual(failures, ["WSL toolchain probe timed out"]);
615 }).pipe(Effect.provide(TestClock.layer())),
616 ),
617 );
618
619 it.effect("cancels a scheduled restart when start is requested manually", () =>
620 Effect.scoped(
621 Effect.gen(function* () {
622 const starts = yield* Queue.unbounded<number>();
623 const secondClosed = yield* Deferred.make<void>();
624 let startCount = 0;
625
626 const spawnerLayer = Layer.succeed(
627 ChildProcessSpawner.ChildProcessSpawner,
628 ChildProcessSpawner.make(() =>
629 Effect.gen(function* () {
630 startCount += 1;
631 yield* Queue.offer(starts, startCount);
632
633 if (startCount === 1) {
634 return makeProcess({
635 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
636 });
637 }
638
639 const scope = yield* Scope.Scope;
640 const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
641 yield* Scope.addFinalizer(scope, close);
642 return makeProcess({
643 exitCode: Deferred.await(secondClosed).pipe(
644 Effect.as(ChildProcessSpawner.ExitCode(0)),
645 ),
646 kill: () => close,
647 });
648 }),
649 ),
650 );
651
652 const instance = yield* makeTestInstance({
653 spawnerLayer,
654 httpClientLayer: httpClientLayer(() => Effect.never),
655 });
656
657 yield* instance.start;
658
659 assert.equal(yield* Queue.take(starts), 1);
660
661 yield* instance.start;
662 assert.equal(yield* Queue.take(starts), 2);
663
664 yield* instance.stop();
665 yield* TestClock.adjust(Duration.millis(500));
666
667 assert.equal(yield* Queue.size(starts), 0);
668 }).pipe(Effect.provide(TestClock.layer())),
669 ),
670 );
671
672 it.effect("does not restart after stop cancels a scheduled restart", () =>
673 Effect.scoped(
674 Effect.gen(function* () {
675 const starts = yield* Queue.unbounded<number>();
676 let startCount = 0;
677
678 const spawnerLayer = Layer.succeed(
679 ChildProcessSpawner.ChildProcessSpawner,
680 ChildProcessSpawner.make(() =>
681 Effect.sync(() => {
682 startCount += 1;
683 return makeProcess({
684 exitCode: Queue.offer(starts, startCount).pipe(
685 Effect.as(ChildProcessSpawner.ExitCode(1)),
686 ),
687 });
688 }),
689 ),
690 );
691
692 const instance = yield* makeTestInstance({
693 spawnerLayer,
694 httpClientLayer: httpClientLayer(() => Effect.never),
695 });
696
697 yield* instance.start;
698 assert.equal(yield* Queue.take(starts), 1);
699
700 let restartScheduled = false;
701 while (!restartScheduled) {
702 restartScheduled = (yield* instance.snapshot).restartScheduled;
703 if (!restartScheduled) {
704 yield* Effect.yieldNow;
705 }
706 }
707
708 yield* instance.stop();
709 yield* TestClock.adjust(Duration.millis(500));
710
711 assert.equal(yield* Queue.size(starts), 0);
712 assert.equal((yield* instance.snapshot).desiredRunning, false);
713 }).pipe(Effect.provide(TestClock.layer())),
714 ),
715 );
716});