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

supervisor.test.ts

1,161 lines42.7 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import { RelayClientTracer } from "@t3tools/shared/relayTracing";
3import { describe, expect, it } from "@effect/vitest";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Ref from "effect/Ref";
9import * as Stream from "effect/Stream";
10import * as SubscriptionRef from "effect/SubscriptionRef";
11import * as TestClock from "effect/testing/TestClock";
12import * as Tracer from "effect/Tracer";
13​
14import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
15import type { ConnectionCatalogEntry } from "./catalog.ts";
16import * as Connectivity from "./connectivity.ts";
17import * as ConnectionDriver from "./driver.ts";
18import {
19 ConnectionBlockedError,
20 ConnectionTransientError,
21 PrimaryConnectionTarget,
22 RelayConnectionTarget,
23 type ConnectionAttemptError,
24 type ConnectionTarget,
25 type NetworkStatus,
26 type PreparedConnection,
27 type SupervisorConnectionState,
28} from "./model.ts";
29import * as RpcSession from "../rpc/session.ts";
30import * as EnvironmentSupervisor from "./supervisor.ts";
31import * as ConnectionWakeups from "./wakeups.ts";
32​
33const TARGET = new PrimaryConnectionTarget({
34 environmentId: EnvironmentId.make("environment-1"),
35 label: "Test environment",
36 httpBaseUrl: "https://environment.example.test",
37 wsBaseUrl: "wss://environment.example.test",
38});
39​
40const RELAY_TARGET = new RelayConnectionTarget({
41 environmentId: TARGET.environmentId,
42 label: TARGET.label,
43});
44​
45const TARGET_ENTRY: ConnectionCatalogEntry = {
46 target: TARGET,
47 profile: Option.none(),
48};
49​
50const RELAY_ENTRY: ConnectionCatalogEntry = {
51 target: RELAY_TARGET,
52 profile: Option.none(),
53};
54​
55const PREPARED_CONNECTION: PreparedConnection = {
56 environmentId: TARGET.environmentId,
57 label: TARGET.label,
58 httpBaseUrl: TARGET.httpBaseUrl,
59 socketUrl: "wss://environment.example.test/ws",
60 httpAuthorization: null,
61 target: TARGET,
62};
63​
64const TEST_RPC_CLIENT = {} as WsRpcProtocolClient;
65​
66function transient(message = "Connection failed.") {
67 return new ConnectionTransientError({
68 reason: "transport",
69 detail: message,
70 });
72​
73function blocked(message = "Authentication required.") {
74 return new ConnectionBlockedError({
75 reason: "authentication",
76 detail: message,
77 });
79​
80function awaitState(
81 state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>,
82 predicate: (value: SupervisorConnectionState) => boolean,
83) {
84 return SubscriptionRef.changes(state).pipe(
85 Stream.filter(predicate),
86 Stream.runHead,
87 Effect.map(Option.getOrThrow),
88 );
90​
91const eventuallyState = Effect.fn("TestConnectionHarness.eventuallyState")(function* (
92 state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>,
93 predicate: (value: SupervisorConnectionState) => boolean,
94) {
95 let lastState = yield* SubscriptionRef.get(state);
96 for (let iteration = 0; iteration < 100; iteration += 1) {
97 lastState = yield* SubscriptionRef.get(state);
98 if (predicate(lastState)) {
99 return lastState;
100 }
101 yield* Effect.yieldNow;
102 }
103 return yield* Effect.die(
104 new Error(
105 `Expected supervisor state was not observed. Last state: phase=${lastState.phase}, stage=${lastState.stage ?? "none"}, attempt=${lastState.attempt}, generation=${lastState.generation}`,
106 ),
107 );
108});
109​
110const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: {
111 readonly networkStatus?: NetworkStatus;
112 readonly prepare?: (
113 attempt: number,
114 target: ConnectionTarget,
115 ) => Effect.Effect<PreparedConnection, ConnectionAttemptError>;
116 readonly ready?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
117 readonly probe?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
118}) {
119 const networkStatus = yield* SubscriptionRef.make<NetworkStatus>(
120 options?.networkStatus ?? "online",
121 );
122 const prepareCount = yield* Ref.make(0);
123 const sessionCount = yield* Ref.make(0);
124 const releaseCount = yield* Ref.make(0);
125 const wakeups = yield* SubscriptionRef.make<{
126 readonly sequence: number;
127 readonly reason: ConnectionWakeups.ConnectionWakeup;
128 }>({
129 sequence: 0,
130 reason: "application-active",
131 });
132 const closedSessions = yield* Ref.make<
133 ReadonlyArray<Deferred.Deferred<never, ConnectionTransientError>>
134 >([]);
135​
136 const connectivity = Connectivity.Connectivity.of({
137 status: SubscriptionRef.get(networkStatus),
138 changes: SubscriptionRef.changes(networkStatus),
139 });
140​
141 const prepare = Effect.fn("TestConnectionDriver.prepare")(function* (target: ConnectionTarget) {
142 const attempt = yield* Ref.updateAndGet(prepareCount, (count) => count + 1);
143 if (options?.prepare) {
144 return yield* options.prepare(attempt, target);
145 }
146 return PREPARED_CONNECTION;
147 });
148​
149 const connect = Effect.fn("TestConnectionDriver.connect")(function* (
150 entry: ConnectionCatalogEntry,
151 reportProgress: (progress: ConnectionDriver.ConnectionDriverProgress) => Effect.Effect<void>,
152 ) {
153 const target = entry.target;
154 yield* reportProgress({ stage: "preparing" });
155 const prepared = yield* prepare(target);
156 yield* reportProgress({ stage: "opening", prepared });
157​
158 const attempt = yield* Ref.updateAndGet(sessionCount, (count) => count + 1);
159 const closed = yield* Deferred.make<never, ConnectionTransientError>();
160 yield* Ref.update(closedSessions, (sessions) => [...sessions, closed]);
161​
162 const session = yield* Effect.acquireRelease(
163 Effect.succeed({
164 client: TEST_RPC_CLIENT,
165 initialConfig: Effect.die(new Error("Initial config is not used by supervisor tests.")),
166 subscribeServerConfig: (input) => TEST_RPC_CLIENT.subscribeServerConfig(input),
167 ready: options?.ready?.(attempt) ?? Effect.void,
168 probe: options?.probe?.(attempt) ?? Effect.void,
169 closed: Deferred.await(closed),
170 } satisfies RpcSession.RpcSession),
171 () => Ref.update(releaseCount, (count) => count + 1),
172 );
173​
174 yield* reportProgress({ stage: "synchronizing", prepared });
175 yield* session.ready;
176 return { prepared, session } satisfies ConnectionDriver.EnvironmentConnectionLease;
177 });
178​
179 const dependencies = Layer.mergeAll(
180 Layer.succeed(Connectivity.Connectivity, connectivity),
181 Layer.succeed(
182 ConnectionWakeups.ConnectionWakeups,
183 ConnectionWakeups.ConnectionWakeups.of({
184 changes: SubscriptionRef.changes(wakeups).pipe(
185 Stream.drop(1),
186 Stream.map((event) => event.reason),
187 ),
188 }),
189 ),
190 Layer.succeed(
191 ConnectionDriver.ConnectionDriver,
192 ConnectionDriver.ConnectionDriver.of({ connect }),
193 ),
194 );
195​
196 return {
197 dependencies,
198 prepareCount,
199 sessionCount,
200 releaseCount,
201 setNetworkStatus: (status: NetworkStatus) => SubscriptionRef.set(networkStatus, status),
202 wake: (reason: ConnectionWakeups.ConnectionWakeup) =>
203 SubscriptionRef.update(wakeups, (event) => ({
204 sequence: event.sequence + 1,
205 reason,
206 })),
207 closeLatestSession: Effect.fn("TestConnectionHarness.closeLatestSession")(function* (
208 error = transient("Session closed."),
209 ) {
210 const sessions = yield* Ref.get(closedSessions);
211 const latest = sessions.at(-1);
212 if (latest) {
213 yield* Deferred.fail(latest, error);
214 }
215 }),
216 };
217});
218​
219describe("EnvironmentSupervisor", () => {
220 it.effect("exports each relay setup as a standalone linked trace that ends at readiness", () =>
221 Effect.gen(function* () {
222 const spans: Array<Tracer.NativeSpan> = [];
223 const tracer = Tracer.make({
224 span: (options) => {
225 const span = new Tracer.NativeSpan(options);
226 const end = span.end.bind(span);
227 span.end = (endTime, exit) => {
228 end(endTime, exit);
229 spans.push(span);
230 };
231 return span;
232 },
233 });
234 const harness = yield* makeHarness({
235 prepare: (attempt) =>
236 attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION),
237 });
238 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
239 initiallyDesired: true,
240 }).pipe(
241 Effect.provide(harness.dependencies),
242 Effect.provideService(RelayClientTracer, Option.some(tracer)),
243 );
244​
245 yield* awaitState(
246 supervisor.state,
247 (state) => state.phase === "backoff" && state.attempt === 1,
248 );
249 const firstAttempt = spans.find((span) => span.name === "relay.connection.attempt");
250 expect(firstAttempt).toBeDefined();
251​
252 yield* TestClock.adjust("3 seconds");
253 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
254​
255 const attempts = spans.filter((span) => span.name === "relay.connection.attempt");
256 expect(attempts).toHaveLength(2);
257 expect(attempts[0]?.traceId).not.toBe(attempts[1]?.traceId);
258 expect(attempts[1]?.links.map((link) => link.span.spanId)).toContain(attempts[0]?.spanId);
259 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
260 }).pipe(Effect.provide(TestClock.layer())),
261 );
262​
263 it.effect("does not attempt a connection until it is desired", () =>
264 Effect.gen(function* () {
265 const harness = yield* makeHarness();
266 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY).pipe(
267 Effect.provide(harness.dependencies),
268 );
269​
270 expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("available");
271 expect(yield* Ref.get(harness.prepareCount)).toBe(0);
272 }),
273 );
274​
275 it.effect("does not let the initial connect signal cancel the first attempt", () =>
276 Effect.gen(function* () {
277 const harness = yield* makeHarness();
278 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY).pipe(
279 Effect.provide(harness.dependencies),
280 );
281​
282 yield* supervisor.connect;
283 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
284​
285 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
286 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
287 }),
288 );
289​
290 it.effect("waits while offline and connects immediately when the network returns", () =>
291 Effect.gen(function* () {
292 const harness = yield* makeHarness({ networkStatus: "offline" });
293 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
294 initiallyDesired: true,
295 }).pipe(Effect.provide(harness.dependencies));
296​
297 yield* awaitState(supervisor.state, (state) => state.phase === "offline");
298 expect(yield* Ref.get(harness.prepareCount)).toBe(0);
299​
300 yield* harness.setNetworkStatus("online");
301 const ready = yield* awaitState(supervisor.state, (state) => state.phase === "connected");
302​
303 expect(ready).toMatchObject({
304 desired: true,
305 network: "online",
306 phase: "connected",
307 attempt: 1,
308 generation: 1,
309 lastFailure: null,
310 });
311 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
312 }),
313 );
314​
315 it.effect("resets retries when activation arrives before the network returns", () =>
316 Effect.gen(function* () {
317 const harness = yield* makeHarness();
318 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
319 initiallyDesired: true,
320 }).pipe(Effect.provide(harness.dependencies));
321​
322 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
323 yield* harness.closeLatestSession();
324 yield* awaitState(
325 supervisor.state,
326 (state) => state.phase === "backoff" && state.attempt === 1,
327 );
328 yield* harness.setNetworkStatus("offline");
329 yield* awaitState(
330 supervisor.state,
331 (state) => state.phase === "offline" && state.attempt === 2,
332 );
333​
334 yield* harness.wake("application-active-reconnect");
335 yield* awaitState(
336 supervisor.state,
337 (state) => state.phase === "offline" && state.attempt === 1,
338 );
339 yield* harness.setNetworkStatus("online");
340 yield* awaitState(
341 supervisor.state,
342 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
343 );
344 }),
345 );
346​
347 it.effect("retries forever with exponential backoff capped at sixteen seconds", () =>
348 Effect.gen(function* () {
349 const harness = yield* makeHarness({
350 prepare: () => Effect.fail(transient()),
351 });
352 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
353 initiallyDesired: true,
354 }).pipe(Effect.provide(harness.dependencies));
355​
356 yield* awaitState(
357 supervisor.state,
358 (state) => state.phase === "backoff" && state.attempt === 1,
359 );
360 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
361​
362 for (const [index, delay] of [3_000, 4_000, 8_000, 16_000, 16_000, 16_000].entries()) {
363 yield* TestClock.adjust(delay);
364 yield* eventuallyState(
365 supervisor.state,
366 (state) => state.phase === "backoff" && state.attempt === index + 2,
367 );
368 }
369​
370 expect(yield* Ref.get(harness.prepareCount)).toBe(7);
371 }).pipe(Effect.provide(TestClock.layer())),
372 );
373​
374 it.effect("keeps the latest failure visible throughout the next connection attempt", () =>
375 Effect.gen(function* () {
376 const harness = yield* makeHarness({
377 prepare: (attempt) =>
378 attempt === 1 ? Effect.fail(transient("Relay connection timed out.")) : Effect.never,
379 });
380 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
381 initiallyDesired: true,
382 }).pipe(Effect.provide(harness.dependencies));
383​
384 yield* awaitState(
385 supervisor.state,
386 (state) => state.phase === "backoff" && state.attempt === 1,
387 );
388 yield* TestClock.adjust("3 seconds");
389​
390 const retrying = yield* awaitState(
391 supervisor.state,
392 (state) =>
393 state.phase === "connecting" && state.stage === "preparing" && state.attempt === 2,
394 );
395 expect(retrying).toMatchObject({
396 phase: "connecting",
397 stage: "preparing",
398 attempt: 2,
399 lastFailure: {
400 _tag: "ConnectionTransientError",
401 reason: "transport",
402 message: "Relay connection timed out.",
403 },
404 });
405 }).pipe(Effect.provide(TestClock.layer())),
406 );
407​
408 it.effect("retries when a session never becomes ready", () =>
409 Effect.gen(function* () {
410 const harness = yield* makeHarness({
411 ready: () => Effect.never,
412 });
413 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
414 initiallyDesired: true,
415 }).pipe(Effect.provide(harness.dependencies));
416​
417 yield* awaitState(
418 supervisor.state,
419 (state) => state.phase === "connecting" && state.stage === "synchronizing",
420 );
421 yield* TestClock.adjust("14 seconds");
422 expect((yield* SubscriptionRef.get(supervisor.state)).stage).toBe("synchronizing");
423​
424 yield* TestClock.adjust("1 second");
425 const retrying = yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
426​
427 expect(retrying).toMatchObject({
428 phase: "backoff",
429 lastFailure: {
430 _tag: "ConnectionTransientError",
431 reason: "timeout",
432 message: "Test environment did not respond during connection setup.",
433 },
434 });
435 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
436 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
437 }).pipe(Effect.provide(TestClock.layer())),
438 );
439​
440 it.effect("interrupts and releases a connection attempt when setup times out", () =>
441 Effect.gen(function* () {
442 const harness = yield* makeHarness({
443 prepare: () => Effect.never,
444 });
445 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
446 initiallyDesired: true,
447 }).pipe(Effect.provide(harness.dependencies));
448​
449 yield* awaitState(
450 supervisor.state,
451 (state) => state.phase === "connecting" && state.stage === "preparing",
452 );
453 yield* TestClock.adjust("15 seconds");
454 const retrying = yield* eventuallyState(
455 supervisor.state,
456 (state) => state.phase === "backoff" && state.attempt === 1,
457 );
458​
459 expect(retrying).toMatchObject({
460 lastFailure: {
461 _tag: "ConnectionTransientError",
462 reason: "timeout",
463 message: "Test environment did not respond during connection setup.",
464 },
465 });
466 }).pipe(Effect.provide(TestClock.layer())),
467 );
468​
469 it.effect("converts unexpected driver defects into retryable failures", () =>
470 Effect.gen(function* () {
471 const harness = yield* makeHarness({
472 prepare: (attempt) =>
473 attempt === 1
474 ? Effect.die(new Error("Native transport defect."))
475 : Effect.succeed(PREPARED_CONNECTION),
476 });
477 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
478 initiallyDesired: true,
479 }).pipe(Effect.provide(harness.dependencies));
480​
481 const failed = yield* awaitState(
482 supervisor.state,
483 (state) => state.phase === "backoff" && state.attempt === 1,
484 );
485 expect(failed).toMatchObject({
486 lastFailure: {
487 _tag: "ConnectionTransientError",
488 reason: "transport",
489 message: "Test environment connection failed unexpectedly.",
490 },
491 });
492​
493 yield* TestClock.adjust("3 seconds");
494 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
495 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
496 }).pipe(Effect.provide(TestClock.layer())),
497 );
498​
499 it.effect("explicit retry interrupts the current backoff", () =>
500 Effect.gen(function* () {
501 const harness = yield* makeHarness({
502 prepare: (attempt) =>
503 attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION),
504 });
505 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
506 initiallyDesired: true,
507 }).pipe(Effect.provide(harness.dependencies));
508​
509 yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
510 yield* supervisor.retryNow;
511 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
512​
513 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
514 }),
515 );
516​
517 it.effect("explicit retry starts a fresh backoff sequence", () =>
518 Effect.gen(function* () {
519 const harness = yield* makeHarness({
520 prepare: () => Effect.fail(transient()),
521 });
522 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
523 initiallyDesired: true,
524 }).pipe(Effect.provide(harness.dependencies));
525​
526 yield* awaitState(
527 supervisor.state,
528 (state) => state.phase === "backoff" && state.attempt === 1,
529 );
530 yield* TestClock.adjust("3 seconds");
531 yield* eventuallyState(
532 supervisor.state,
533 (state) => state.phase === "backoff" && state.attempt === 2,
534 );
535​
536 yield* supervisor.retryNow;
537 yield* eventuallyState(
538 supervisor.state,
539 (state) => state.phase === "backoff" && state.attempt === 1,
540 );
541 expect(yield* Ref.get(harness.prepareCount)).toBe(3);
542​
543 yield* TestClock.adjust("2999 millis");
544 expect(yield* Ref.get(harness.prepareCount)).toBe(3);
545 yield* TestClock.adjust("1 milli");
546 yield* eventuallyState(
547 supervisor.state,
548 (state) => state.phase === "backoff" && state.attempt === 2,
549 );
550 expect(yield* Ref.get(harness.prepareCount)).toBe(4);
551 }).pipe(Effect.provide(TestClock.layer())),
552 );
553​
554 it.effect("keeps blocked failures idle until an external signal requests another attempt", () =>
555 Effect.gen(function* () {
556 const harness = yield* makeHarness({
557 prepare: (attempt) =>
558 attempt === 1 ? Effect.fail(blocked()) : Effect.succeed(PREPARED_CONNECTION),
559 });
560 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
561 initiallyDesired: true,
562 }).pipe(Effect.provide(harness.dependencies));
563​
564 yield* awaitState(supervisor.state, (state) => state.phase === "blocked");
565 yield* TestClock.adjust("1 hour");
566 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
567​
568 yield* supervisor.retryNow;
569 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
570 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
571 }).pipe(Effect.provide(TestClock.layer())),
572 );
573​
574 it.effect("resets retries when activation wakes a blocked connection", () =>
575 Effect.gen(function* () {
576 const harness = yield* makeHarness({
577 prepare: (attempt) =>
578 attempt === 1
579 ? Effect.fail(transient())
580 : attempt === 2
581 ? Effect.fail(blocked())
582 : Effect.succeed(PREPARED_CONNECTION),
583 });
584 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
585 initiallyDesired: true,
586 }).pipe(Effect.provide(harness.dependencies));
587​
588 yield* awaitState(
589 supervisor.state,
590 (state) => state.phase === "backoff" && state.attempt === 1,
591 );
592 yield* TestClock.adjust("3 seconds");
593 yield* awaitState(
594 supervisor.state,
595 (state) => state.phase === "blocked" && state.attempt === 2,
596 );
597​
598 yield* harness.wake("application-active-reconnect");
599 yield* awaitState(
600 supervisor.state,
601 (state) => state.phase === "connected" && state.attempt === 1,
602 );
603 }).pipe(Effect.provide(TestClock.layer())),
604 );
605​
606 it.effect("releases a live session while offline and starts a new generation when online", () =>
607 Effect.gen(function* () {
608 const harness = yield* makeHarness();
609 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
610 initiallyDesired: true,
611 }).pipe(Effect.provide(harness.dependencies));
612​
613 yield* awaitState(
614 supervisor.state,
615 (state) => state.phase === "connected" && state.generation === 1,
616 );
617 yield* harness.setNetworkStatus("offline");
618 yield* awaitState(supervisor.state, (state) => state.phase === "offline");
619​
620 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
621 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
622​
623 yield* harness.setNetworkStatus("online");
624 yield* awaitState(
625 supervisor.state,
626 (state) => state.phase === "connected" && state.generation === 2,
627 );
628 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
629 }),
630 );
631​
632 it.effect("retries a blocked connection when platform credentials change", () =>
633 Effect.gen(function* () {
634 const harness = yield* makeHarness({
635 prepare: (attempt) =>
636 attempt === 1 ? Effect.fail(blocked()) : Effect.succeed(PREPARED_CONNECTION),
637 });
638 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
639 initiallyDesired: true,
640 }).pipe(Effect.provide(harness.dependencies));
641​
642 yield* awaitState(supervisor.state, (state) => state.phase === "blocked");
643 yield* harness.wake("credentials-changed");
644 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
645​
646 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
647 }),
648 );
649​
650 it.effect("does not let platform wakeups reset an in-flight attempt", () =>
651 Effect.gen(function* () {
652 const firstAttemptStarted = yield* Deferred.make<void>();
653 const harness = yield* makeHarness({
654 prepare: () =>
655 Deferred.succeed(firstAttemptStarted, undefined).pipe(Effect.andThen(Effect.never)),
656 });
657 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
658 initiallyDesired: true,
659 }).pipe(Effect.provide(harness.dependencies));
660​
661 yield* Deferred.await(firstAttemptStarted);
662 yield* Effect.all(
663 [
664 harness.wake("credentials-changed"),
665 harness.wake("application-active"),
666 harness.wake("credentials-changed"),
667 ],
668 { concurrency: "unbounded" },
669 );
670 yield* Effect.yieldNow;
671​
672 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
673​
674 yield* TestClock.adjust("15 seconds");
675 const retrying = yield* eventuallyState(
676 supervisor.state,
677 (state) => state.phase === "backoff" && state.attempt === 1,
678 );
679​
680 expect(retrying).toMatchObject({
681 lastFailure: {
682 _tag: "ConnectionTransientError",
683 reason: "timeout",
684 message: "Test environment did not respond during connection setup.",
685 },
686 });
687 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
688 expect(yield* Ref.get(harness.sessionCount)).toBe(0);
689 }).pipe(Effect.provide(TestClock.layer())),
690 );
691​
692 it.effect("treats an involuntary session close as transient and reconnects", () =>
693 Effect.gen(function* () {
694 const harness = yield* makeHarness();
695 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
696 initiallyDesired: true,
697 }).pipe(Effect.provide(harness.dependencies));
698​
699 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
700 yield* harness.closeLatestSession();
701 yield* awaitState(
702 supervisor.state,
703 (state) => state.phase === "backoff" && state.attempt === 1,
704 );
705 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
706​
707 yield* TestClock.adjust("3 seconds");
708 yield* awaitState(
709 supervisor.state,
710 (state) => state.phase === "connected" && state.generation === 2,
711 );
712​
713 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
714 expect(Option.isSome(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
715 }).pipe(Effect.provide(TestClock.layer())),
716 );
717​
718 it.effect("keeps escalating backoff when a newly opened session flaps", () =>
719 Effect.gen(function* () {
720 const harness = yield* makeHarness();
721 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
722 initiallyDesired: true,
723 }).pipe(Effect.provide(harness.dependencies));
724​
725 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
726 yield* harness.closeLatestSession();
727 yield* awaitState(
728 supervisor.state,
729 (state) => state.phase === "backoff" && state.attempt === 1,
730 );
731​
732 yield* TestClock.adjust("3 seconds");
733 yield* awaitState(
734 supervisor.state,
735 (state) => state.phase === "connected" && state.generation === 2,
736 );
737 yield* harness.closeLatestSession();
738 const secondFailure = yield* awaitState(
739 supervisor.state,
740 (state) => state.phase === "backoff" && state.attempt === 2,
741 );
742​
743 expect(secondFailure.retryAt).not.toBeNull();
744​
745 yield* TestClock.adjust("3 seconds");
746 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
747​
748 yield* TestClock.adjust("1 second");
749 yield* awaitState(
750 supervisor.state,
751 (state) => state.phase === "connected" && state.generation === 3,
752 );
753 expect(yield* Ref.get(harness.sessionCount)).toBe(3);
754 }).pipe(Effect.provide(TestClock.layer())),
755 );
756​
757 it.effect("restarts the retry ladder when mobile returns to the foreground", () =>
758 Effect.gen(function* () {
759 const harness = yield* makeHarness();
760 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
761 initiallyDesired: true,
762 }).pipe(Effect.provide(harness.dependencies));
763​
764 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
765 yield* harness.closeLatestSession();
766 yield* awaitState(
767 supervisor.state,
768 (state) => state.phase === "backoff" && state.attempt === 1,
769 );
770 yield* TestClock.adjust("3 seconds");
771 yield* awaitState(
772 supervisor.state,
773 (state) => state.phase === "connected" && state.generation === 2,
774 );
775 yield* harness.closeLatestSession();
776 yield* awaitState(
777 supervisor.state,
778 (state) => state.phase === "backoff" && state.attempt === 2,
779 );
780​
781 yield* harness.wake("application-active-reconnect");
782 yield* awaitState(
783 supervisor.state,
784 (state) => state.phase === "connected" && state.generation === 3 && state.attempt === 1,
785 );
786 yield* harness.closeLatestSession();
787 yield* awaitState(
788 supervisor.state,
789 (state) => state.phase === "backoff" && state.attempt === 1,
790 );
791​
792 expect(yield* Ref.get(harness.sessionCount)).toBe(3);
793 }).pipe(Effect.provide(TestClock.layer())),
794 );
795​
796 it.effect("restarts the retry ladder when a long resume replaces a connected session", () =>
797 Effect.gen(function* () {
798 const harness = yield* makeHarness();
799 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
800 initiallyDesired: true,
801 }).pipe(Effect.provide(harness.dependencies));
802​
803 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
804 yield* harness.closeLatestSession();
805 yield* awaitState(
806 supervisor.state,
807 (state) => state.phase === "backoff" && state.attempt === 1,
808 );
809 yield* TestClock.adjust("3 seconds");
810 yield* awaitState(
811 supervisor.state,
812 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 2,
813 );
814​
815 yield* harness.wake("application-active-reconnect");
816 yield* awaitState(
817 supervisor.state,
818 (state) => state.phase === "connected" && state.generation === 3 && state.attempt === 1,
819 );
820 }).pipe(Effect.provide(TestClock.layer())),
821 );
822​
823 it.effect("restarts the retry ladder when a long resume interrupts connection setup", () =>
824 Effect.gen(function* () {
825 const harness = yield* makeHarness({
826 prepare: (attempt) => (attempt === 2 ? Effect.never : Effect.succeed(PREPARED_CONNECTION)),
827 });
828 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
829 initiallyDesired: true,
830 }).pipe(Effect.provide(harness.dependencies));
831​
832 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
833 yield* harness.closeLatestSession();
834 yield* awaitState(
835 supervisor.state,
836 (state) => state.phase === "backoff" && state.attempt === 1,
837 );
838 yield* TestClock.adjust("3 seconds");
839 yield* awaitState(
840 supervisor.state,
841 (state) => state.phase === "connecting" && state.attempt === 2,
842 );
843​
844 yield* harness.wake("application-active-reconnect");
845 yield* awaitState(
846 supervisor.state,
847 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
848 );
849 }).pipe(Effect.provide(TestClock.layer())),
850 );
851​
852 it.effect("probes the active session without reconnecting on application activation", () =>
853 Effect.gen(function* () {
854 const probeCount = yield* Ref.make(0);
855 const probeCalled = yield* Deferred.make<void>();
856 const harness = yield* makeHarness({
857 probe: () =>
858 Ref.update(probeCount, (count) => count + 1).pipe(
859 Effect.andThen(Deferred.succeed(probeCalled, undefined)),
860 ),
861 });
862 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
863 initiallyDesired: true,
864 }).pipe(Effect.provide(harness.dependencies));
865​
866 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
867 yield* harness.wake("application-active");
868 yield* Deferred.await(probeCalled);
869​
870 expect(yield* Ref.get(probeCount)).toBe(1);
871 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
872 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
873 expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("connected");
874 }),
875 );
876​
877 it.effect("immediately replaces a mobile session after a long background resume", () =>
878 Effect.gen(function* () {
879 const probeCount = yield* Ref.make(0);
880 const harness = yield* makeHarness({
881 probe: () => Ref.update(probeCount, (count) => count + 1),
882 });
883 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
884 initiallyDesired: true,
885 }).pipe(Effect.provide(harness.dependencies));
886​
887 yield* awaitState(
888 supervisor.state,
889 (state) => state.phase === "connected" && state.generation === 1,
890 );
891 yield* harness.wake("application-active-reconnect");
892 yield* awaitState(
893 supervisor.state,
894 (state) => state.phase === "connected" && state.generation === 2,
895 );
896​
897 expect(yield* Ref.get(probeCount)).toBe(0);
898 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
899 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
900 }),
901 );
902​
903 it.effect("replaces a mobile session when a long resume interrupts an active probe", () =>
904 Effect.gen(function* () {
905 const harness = yield* makeHarness({
906 probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
907 });
908 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
909 initiallyDesired: true,
910 }).pipe(Effect.provide(harness.dependencies));
911​
912 yield* awaitState(
913 supervisor.state,
914 (state) => state.phase === "connected" && state.generation === 1,
915 );
916 yield* harness.wake("application-active-probe");
917 yield* Effect.yieldNow;
918 yield* harness.wake("application-active-reconnect");
919 yield* awaitState(
920 supervisor.state,
921 (state) => state.phase === "connected" && state.generation === 2,
922 );
923​
924 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
925 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
926 }),
927 );
928​
929 it.effect("reconnects immediately when the foreground liveness probe fails", () =>
930 Effect.gen(function* () {
931 const allowReconnect = yield* Deferred.make<void>();
932 const harness = yield* makeHarness({
933 prepare: (attempt) =>
934 attempt === 2
935 ? Deferred.await(allowReconnect).pipe(Effect.as(PREPARED_CONNECTION))
936 : Effect.succeed(PREPARED_CONNECTION),
937 probe: (attempt) =>
938 attempt === 1 ? Effect.fail(transient("The live session is stale.")) : Effect.void,
939 });
940 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
941 initiallyDesired: true,
942 }).pipe(Effect.provide(harness.dependencies));
943​
944 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
945 yield* harness.wake("application-active");
946 const reconnecting = yield* awaitState(
947 supervisor.state,
948 (state) => state.phase === "connecting",
949 );
950 expect(reconnecting.attempt).toBe(1);
951 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
952​
953 // No TestClock advance: a failed wake probe skips the first backoff rung.
954 yield* Deferred.succeed(allowReconnect, undefined);
955 yield* awaitState(
956 supervisor.state,
957 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
958 );
959​
960 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
961 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
962 }).pipe(Effect.provide(TestClock.layer())),
963 );
964​
965 it.effect("keeps normal backoff when a reconnect after a failed wake probe also fails", () =>
966 Effect.gen(function* () {
967 const harness = yield* makeHarness({
968 prepare: (attempt) =>
969 attempt === 2 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION),
970 probe: (attempt) =>
971 attempt === 1 ? Effect.fail(transient("The live session is stale.")) : Effect.void,
972 });
973 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
974 initiallyDesired: true,
975 }).pipe(Effect.provide(harness.dependencies));
976​
977 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
978 yield* harness.wake("application-active");
979 // The immediate follow-up attempt fails: only the first attempt after
980 // the wake probe skips the ladder, so this failure backs off normally.
981 yield* awaitState(
982 supervisor.state,
983 (state) => state.phase === "backoff" && state.attempt === 1,
984 );
985 yield* TestClock.adjust("2999 millis");
986 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
987 yield* TestClock.adjust("1 milli");
988 yield* eventuallyState(
989 supervisor.state,
990 (state) => state.phase === "connected" && state.generation === 2,
991 );
992​
993 expect(yield* Ref.get(harness.prepareCount)).toBe(3);
994 }).pipe(Effect.provide(TestClock.layer())),
995 );
996​
997 it.effect("uses the full tolerance window for a stalled desktop foreground probe", () =>
998 Effect.gen(function* () {
999 const harness = yield* makeHarness({
1000 probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
1001 });
1002 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1003 initiallyDesired: true,
1004 }).pipe(Effect.provide(harness.dependencies));
1005​
1006 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1007 yield* harness.wake("application-active");
1008 yield* TestClock.adjust("14999 millis");
1009 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
1010 yield* TestClock.adjust("1 milli");
1011 yield* awaitState(
1012 supervisor.state,
1013 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
1014 );
1015​
1016 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
1017 }).pipe(Effect.provide(TestClock.layer())),
1018 );
1019​
1020 it.effect("quickly times out a stalled mobile foreground liveness probe", () =>
1021 Effect.gen(function* () {
1022 const harness = yield* makeHarness({
1023 probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
1024 });
1025 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1026 initiallyDesired: true,
1027 }).pipe(Effect.provide(harness.dependencies));
1028​
1029 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1030 yield* harness.wake("application-active-probe");
1031 yield* TestClock.adjust("3 seconds");
1032 // The timed-out wake probe reconnects immediately without a backoff
1033 // sleep: no further clock advance is needed.
1034 yield* awaitState(
1035 supervisor.state,
1036 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
1037 );
1038​
1039 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
1040 }).pipe(Effect.provide(TestClock.layer())),
1041 );
1042​
1043 it.effect("honors an explicit disconnect while a foreground probe is stalled", () =>
1044 Effect.gen(function* () {
1045 const probeStarted = yield* Deferred.make<void>();
1046 const harness = yield* makeHarness({
1047 probe: () => Deferred.succeed(probeStarted, undefined).pipe(Effect.andThen(Effect.never)),
1048 });
1049 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1050 initiallyDesired: true,
1051 }).pipe(Effect.provide(harness.dependencies));
1052​
1053 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1054 yield* harness.wake("application-active");
1055 yield* Deferred.await(probeStarted);
1056 yield* supervisor.disconnect;
1057 yield* awaitState(supervisor.state, (state) => state.phase === "available");
1058​
1059 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1060 }),
1061 );
1062​
1063 it.effect("does not churn a healthy session when credentials change", () =>
1064 Effect.gen(function* () {
1065 const harness = yield* makeHarness();
1066 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1067 initiallyDesired: true,
1068 }).pipe(Effect.provide(harness.dependencies));
1069​
1070 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1071 yield* harness.wake("credentials-changed");
1072 yield* Effect.yieldNow;
1073​
1074 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
1075 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
1076 expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("connected");
1077 }),
1078 );
1079​
1080 it.effect("releases and reconnects a relay session when credentials change", () =>
1081 Effect.gen(function* () {
1082 const harness = yield* makeHarness();
1083 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
1084 initiallyDesired: true,
1085 }).pipe(Effect.provide(harness.dependencies));
1086​
1087 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1088 yield* harness.wake("credentials-changed");
1089 yield* awaitState(
1090 supervisor.state,
1091 (state) => state.phase === "connected" && state.generation === 2,
1092 );
1093​
1094 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
1095 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1096 }),
1097 );
1098​
1099 it.effect("interrupts relay setup when credentials change", () =>
1100 Effect.gen(function* () {
1101 const firstAttemptStarted = yield* Deferred.make<void>();
1102 const harness = yield* makeHarness({
1103 prepare: (attempt) =>
1104 attempt === 1
1105 ? Deferred.succeed(firstAttemptStarted, undefined).pipe(Effect.andThen(Effect.never))
1106 : Effect.succeed(PREPARED_CONNECTION),
1107 });
1108 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
1109 initiallyDesired: true,
1110 }).pipe(Effect.provide(harness.dependencies));
1111​
1112 yield* Deferred.await(firstAttemptStarted);
1113 yield* harness.wake("credentials-changed");
1114 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1115​
1116 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
1117 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
1118 }),
1119 );
1120​
1121 it.effect("explicit disconnect releases the session and returns to available", () =>
1122 Effect.gen(function* () {
1123 const harness = yield* makeHarness();
1124 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1125 initiallyDesired: true,
1126 }).pipe(Effect.provide(harness.dependencies));
1127​
1128 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1129 yield* supervisor.disconnect;
1130 yield* awaitState(supervisor.state, (state) => state.phase === "available");
1131​
1132 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1133 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
1134 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
1135 }),
1136 );
1137​
1138 it.effect("does not lose an explicit disconnect among concurrent wakeup signals", () =>
1139 Effect.gen(function* () {
1140 const harness = yield* makeHarness();
1141 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1142 initiallyDesired: true,
1143 }).pipe(Effect.provide(harness.dependencies));
1144​
1145 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1146 yield* Effect.all(
1148 supervisor.disconnect,
1149 harness.wake("credentials-changed"),
1150 harness.wake("application-active"),
1151 harness.wake("credentials-changed"),
1152 ],
1153 { concurrency: "unbounded" },
1154 );
1155 yield* awaitState(supervisor.state, (state) => state.phase === "available");
1156​
1157 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1158 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
1159 }),
1160 );
1161});