Open History to see the last commit
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 });
71}
72
73function blocked(message = "Authentication required.") {
74 return new ConnectionBlockedError({
75 reason: "authentication",
76 detail: message,
77 });
78}
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 );
89}
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 ready: options?.ready?.(attempt) ?? Effect.void,
167 probe: options?.probe?.(attempt) ?? Effect.void,
168 closed: Deferred.await(closed),
169 } satisfies RpcSession.RpcSession),
170 () => Ref.update(releaseCount, (count) => count + 1),
171 );
172
173 yield* reportProgress({ stage: "synchronizing", prepared });
174 yield* session.ready;
175 return { prepared, session } satisfies ConnectionDriver.EnvironmentConnectionLease;
176 });
177
178 const dependencies = Layer.mergeAll(
179 Layer.succeed(Connectivity.Connectivity, connectivity),
180 Layer.succeed(
181 ConnectionWakeups.ConnectionWakeups,
182 ConnectionWakeups.ConnectionWakeups.of({
183 changes: SubscriptionRef.changes(wakeups).pipe(
184 Stream.drop(1),
185 Stream.map((event) => event.reason),
186 ),
187 }),
188 ),
189 Layer.succeed(
190 ConnectionDriver.ConnectionDriver,
191 ConnectionDriver.ConnectionDriver.of({ connect }),
192 ),
193 );
194
195 return {
196 dependencies,
197 prepareCount,
198 sessionCount,
199 releaseCount,
200 setNetworkStatus: (status: NetworkStatus) => SubscriptionRef.set(networkStatus, status),
201 wake: (reason: ConnectionWakeups.ConnectionWakeup) =>
202 SubscriptionRef.update(wakeups, (event) => ({
203 sequence: event.sequence + 1,
204 reason,
205 })),
206 closeLatestSession: Effect.fn("TestConnectionHarness.closeLatestSession")(function* (
207 error = transient("Session closed."),
208 ) {
209 const sessions = yield* Ref.get(closedSessions);
210 const latest = sessions.at(-1);
211 if (latest) {
212 yield* Deferred.fail(latest, error);
213 }
214 }),
215 };
216});
217
218describe("EnvironmentSupervisor", () => {
219 it.effect("exports each relay setup as a standalone linked trace that ends at readiness", () =>
220 Effect.gen(function* () {
221 const spans: Array<Tracer.NativeSpan> = [];
222 const tracer = Tracer.make({
223 span: (options) => {
224 const span = new Tracer.NativeSpan(options);
225 const end = span.end.bind(span);
226 span.end = (endTime, exit) => {
227 end(endTime, exit);
228 spans.push(span);
229 };
230 return span;
231 },
232 });
233 const harness = yield* makeHarness({
234 prepare: (attempt) =>
235 attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION),
236 });
237 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
238 initiallyDesired: true,
239 }).pipe(
240 Effect.provide(harness.dependencies),
241 Effect.provideService(RelayClientTracer, Option.some(tracer)),
242 );
243
244 yield* awaitState(
245 supervisor.state,
246 (state) => state.phase === "backoff" && state.attempt === 1,
247 );
248 const firstAttempt = spans.find((span) => span.name === "relay.connection.attempt");
249 expect(firstAttempt).toBeDefined();
250
251 yield* TestClock.adjust("1 second");
252 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
253
254 const attempts = spans.filter((span) => span.name === "relay.connection.attempt");
255 expect(attempts).toHaveLength(2);
256 expect(attempts[0]?.traceId).not.toBe(attempts[1]?.traceId);
257 expect(attempts[1]?.links.map((link) => link.span.spanId)).toContain(attempts[0]?.spanId);
258 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
259 }).pipe(Effect.provide(TestClock.layer())),
260 );
261
262 it.effect("does not attempt a connection until it is desired", () =>
263 Effect.gen(function* () {
264 const harness = yield* makeHarness();
265 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY).pipe(
266 Effect.provide(harness.dependencies),
267 );
268
269 expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("available");
270 expect(yield* Ref.get(harness.prepareCount)).toBe(0);
271 }),
272 );
273
274 it.effect("does not let the initial connect signal cancel the first attempt", () =>
275 Effect.gen(function* () {
276 const harness = yield* makeHarness();
277 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY).pipe(
278 Effect.provide(harness.dependencies),
279 );
280
281 yield* supervisor.connect;
282 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
283
284 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
285 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
286 }),
287 );
288
289 it.effect("waits while offline and connects immediately when the network returns", () =>
290 Effect.gen(function* () {
291 const harness = yield* makeHarness({ networkStatus: "offline" });
292 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
293 initiallyDesired: true,
294 }).pipe(Effect.provide(harness.dependencies));
295
296 yield* awaitState(supervisor.state, (state) => state.phase === "offline");
297 expect(yield* Ref.get(harness.prepareCount)).toBe(0);
298
299 yield* harness.setNetworkStatus("online");
300 const ready = yield* awaitState(supervisor.state, (state) => state.phase === "connected");
301
302 expect(ready).toMatchObject({
303 desired: true,
304 network: "online",
305 phase: "connected",
306 attempt: 1,
307 generation: 1,
308 lastFailure: null,
309 });
310 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
311 }),
312 );
313
314 it.effect("resets retries when activation arrives before the network returns", () =>
315 Effect.gen(function* () {
316 const harness = yield* makeHarness();
317 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
318 initiallyDesired: true,
319 }).pipe(Effect.provide(harness.dependencies));
320
321 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
322 yield* harness.closeLatestSession();
323 yield* awaitState(
324 supervisor.state,
325 (state) => state.phase === "backoff" && state.attempt === 1,
326 );
327 yield* harness.setNetworkStatus("offline");
328 yield* awaitState(
329 supervisor.state,
330 (state) => state.phase === "offline" && state.attempt === 2,
331 );
332
333 yield* harness.wake("application-active-reconnect");
334 yield* awaitState(
335 supervisor.state,
336 (state) => state.phase === "offline" && state.attempt === 1,
337 );
338 yield* harness.setNetworkStatus("online");
339 yield* awaitState(
340 supervisor.state,
341 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
342 );
343 }),
344 );
345
346 it.effect("retries forever with exponential backoff capped at sixteen seconds", () =>
347 Effect.gen(function* () {
348 const harness = yield* makeHarness({
349 prepare: () => Effect.fail(transient()),
350 });
351 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
352 initiallyDesired: true,
353 }).pipe(Effect.provide(harness.dependencies));
354
355 yield* awaitState(
356 supervisor.state,
357 (state) => state.phase === "backoff" && state.attempt === 1,
358 );
359 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
360
361 for (const [index, delay] of [1_000, 2_000, 4_000, 8_000, 16_000, 16_000].entries()) {
362 yield* TestClock.adjust(delay);
363 yield* eventuallyState(
364 supervisor.state,
365 (state) => state.phase === "backoff" && state.attempt === index + 2,
366 );
367 }
368
369 expect(yield* Ref.get(harness.prepareCount)).toBe(7);
370 }).pipe(Effect.provide(TestClock.layer())),
371 );
372
373 it.effect("keeps the latest failure visible throughout the next connection attempt", () =>
374 Effect.gen(function* () {
375 const harness = yield* makeHarness({
376 prepare: (attempt) =>
377 attempt === 1 ? Effect.fail(transient("Relay connection timed out.")) : Effect.never,
378 });
379 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
380 initiallyDesired: true,
381 }).pipe(Effect.provide(harness.dependencies));
382
383 yield* awaitState(
384 supervisor.state,
385 (state) => state.phase === "backoff" && state.attempt === 1,
386 );
387 yield* TestClock.adjust("1 second");
388
389 const retrying = yield* awaitState(
390 supervisor.state,
391 (state) =>
392 state.phase === "connecting" && state.stage === "preparing" && state.attempt === 2,
393 );
394 expect(retrying).toMatchObject({
395 phase: "connecting",
396 stage: "preparing",
397 attempt: 2,
398 lastFailure: {
399 _tag: "ConnectionTransientError",
400 reason: "transport",
401 message: "Relay connection timed out.",
402 },
403 });
404 }).pipe(Effect.provide(TestClock.layer())),
405 );
406
407 it.effect("retries when a session never becomes ready", () =>
408 Effect.gen(function* () {
409 const harness = yield* makeHarness({
410 ready: () => Effect.never,
411 });
412 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
413 initiallyDesired: true,
414 }).pipe(Effect.provide(harness.dependencies));
415
416 yield* awaitState(
417 supervisor.state,
418 (state) => state.phase === "connecting" && state.stage === "synchronizing",
419 );
420 yield* TestClock.adjust("14 seconds");
421 expect((yield* SubscriptionRef.get(supervisor.state)).stage).toBe("synchronizing");
422
423 yield* TestClock.adjust("1 second");
424 const retrying = yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
425
426 expect(retrying).toMatchObject({
427 phase: "backoff",
428 lastFailure: {
429 _tag: "ConnectionTransientError",
430 reason: "timeout",
431 message: "Test environment did not respond during connection setup.",
432 },
433 });
434 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
435 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
436 }).pipe(Effect.provide(TestClock.layer())),
437 );
438
439 it.effect("interrupts and releases a connection attempt when setup times out", () =>
440 Effect.gen(function* () {
441 const harness = yield* makeHarness({
442 prepare: () => Effect.never,
443 });
444 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
445 initiallyDesired: true,
446 }).pipe(Effect.provide(harness.dependencies));
447
448 yield* awaitState(
449 supervisor.state,
450 (state) => state.phase === "connecting" && state.stage === "preparing",
451 );
452 yield* TestClock.adjust("15 seconds");
453 const retrying = yield* eventuallyState(
454 supervisor.state,
455 (state) => state.phase === "backoff" && state.attempt === 1,
456 );
457
458 expect(retrying).toMatchObject({
459 lastFailure: {
460 _tag: "ConnectionTransientError",
461 reason: "timeout",
462 message: "Test environment did not respond during connection setup.",
463 },
464 });
465 }).pipe(Effect.provide(TestClock.layer())),
466 );
467
468 it.effect("converts unexpected driver defects into retryable failures", () =>
469 Effect.gen(function* () {
470 const harness = yield* makeHarness({
471 prepare: (attempt) =>
472 attempt === 1
473 ? Effect.die(new Error("Native transport defect."))
474 : Effect.succeed(PREPARED_CONNECTION),
475 });
476 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
477 initiallyDesired: true,
478 }).pipe(Effect.provide(harness.dependencies));
479
480 const failed = yield* awaitState(
481 supervisor.state,
482 (state) => state.phase === "backoff" && state.attempt === 1,
483 );
484 expect(failed).toMatchObject({
485 lastFailure: {
486 _tag: "ConnectionTransientError",
487 reason: "transport",
488 message: "Test environment connection failed unexpectedly.",
489 },
490 });
491
492 yield* TestClock.adjust("1 second");
493 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
494 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
495 }).pipe(Effect.provide(TestClock.layer())),
496 );
497
498 it.effect("explicit retry interrupts the current backoff", () =>
499 Effect.gen(function* () {
500 const harness = yield* makeHarness({
501 prepare: (attempt) =>
502 attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION),
503 });
504 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
505 initiallyDesired: true,
506 }).pipe(Effect.provide(harness.dependencies));
507
508 yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
509 yield* supervisor.retryNow;
510 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
511
512 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
513 }),
514 );
515
516 it.effect("explicit retry starts a fresh backoff sequence", () =>
517 Effect.gen(function* () {
518 const harness = yield* makeHarness({
519 prepare: () => Effect.fail(transient()),
520 });
521 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
522 initiallyDesired: true,
523 }).pipe(Effect.provide(harness.dependencies));
524
525 yield* awaitState(
526 supervisor.state,
527 (state) => state.phase === "backoff" && state.attempt === 1,
528 );
529 yield* TestClock.adjust("1 second");
530 yield* eventuallyState(
531 supervisor.state,
532 (state) => state.phase === "backoff" && state.attempt === 2,
533 );
534
535 yield* supervisor.retryNow;
536 yield* eventuallyState(
537 supervisor.state,
538 (state) => state.phase === "backoff" && state.attempt === 1,
539 );
540 expect(yield* Ref.get(harness.prepareCount)).toBe(3);
541
542 yield* TestClock.adjust("999 millis");
543 expect(yield* Ref.get(harness.prepareCount)).toBe(3);
544 yield* TestClock.adjust("1 milli");
545 yield* eventuallyState(
546 supervisor.state,
547 (state) => state.phase === "backoff" && state.attempt === 2,
548 );
549 expect(yield* Ref.get(harness.prepareCount)).toBe(4);
550 }).pipe(Effect.provide(TestClock.layer())),
551 );
552
553 it.effect("keeps blocked failures idle until an external signal requests another attempt", () =>
554 Effect.gen(function* () {
555 const harness = yield* makeHarness({
556 prepare: (attempt) =>
557 attempt === 1 ? Effect.fail(blocked()) : Effect.succeed(PREPARED_CONNECTION),
558 });
559 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
560 initiallyDesired: true,
561 }).pipe(Effect.provide(harness.dependencies));
562
563 yield* awaitState(supervisor.state, (state) => state.phase === "blocked");
564 yield* TestClock.adjust("1 hour");
565 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
566
567 yield* supervisor.retryNow;
568 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
569 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
570 }).pipe(Effect.provide(TestClock.layer())),
571 );
572
573 it.effect("resets retries when activation wakes a blocked connection", () =>
574 Effect.gen(function* () {
575 const harness = yield* makeHarness({
576 prepare: (attempt) =>
577 attempt === 1
578 ? Effect.fail(transient())
579 : attempt === 2
580 ? Effect.fail(blocked())
581 : Effect.succeed(PREPARED_CONNECTION),
582 });
583 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
584 initiallyDesired: true,
585 }).pipe(Effect.provide(harness.dependencies));
586
587 yield* awaitState(
588 supervisor.state,
589 (state) => state.phase === "backoff" && state.attempt === 1,
590 );
591 yield* TestClock.adjust("1 second");
592 yield* awaitState(
593 supervisor.state,
594 (state) => state.phase === "blocked" && state.attempt === 2,
595 );
596
597 yield* harness.wake("application-active-reconnect");
598 yield* awaitState(
599 supervisor.state,
600 (state) => state.phase === "connected" && state.attempt === 1,
601 );
602 }).pipe(Effect.provide(TestClock.layer())),
603 );
604
605 it.effect("releases a live session while offline and starts a new generation when online", () =>
606 Effect.gen(function* () {
607 const harness = yield* makeHarness();
608 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
609 initiallyDesired: true,
610 }).pipe(Effect.provide(harness.dependencies));
611
612 yield* awaitState(
613 supervisor.state,
614 (state) => state.phase === "connected" && state.generation === 1,
615 );
616 yield* harness.setNetworkStatus("offline");
617 yield* awaitState(supervisor.state, (state) => state.phase === "offline");
618
619 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
620 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
621
622 yield* harness.setNetworkStatus("online");
623 yield* awaitState(
624 supervisor.state,
625 (state) => state.phase === "connected" && state.generation === 2,
626 );
627 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
628 }),
629 );
630
631 it.effect("retries a blocked connection when platform credentials change", () =>
632 Effect.gen(function* () {
633 const harness = yield* makeHarness({
634 prepare: (attempt) =>
635 attempt === 1 ? Effect.fail(blocked()) : Effect.succeed(PREPARED_CONNECTION),
636 });
637 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
638 initiallyDesired: true,
639 }).pipe(Effect.provide(harness.dependencies));
640
641 yield* awaitState(supervisor.state, (state) => state.phase === "blocked");
642 yield* harness.wake("credentials-changed");
643 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
644
645 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
646 }),
647 );
648
649 it.effect("does not let platform wakeups reset an in-flight attempt", () =>
650 Effect.gen(function* () {
651 const firstAttemptStarted = yield* Deferred.make<void>();
652 const harness = yield* makeHarness({
653 prepare: () =>
654 Deferred.succeed(firstAttemptStarted, undefined).pipe(Effect.andThen(Effect.never)),
655 });
656 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
657 initiallyDesired: true,
658 }).pipe(Effect.provide(harness.dependencies));
659
660 yield* Deferred.await(firstAttemptStarted);
661 yield* Effect.all(
662 [
663 harness.wake("credentials-changed"),
664 harness.wake("application-active"),
665 harness.wake("credentials-changed"),
666 ],
667 { concurrency: "unbounded" },
668 );
669 yield* Effect.yieldNow;
670
671 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
672
673 yield* TestClock.adjust("15 seconds");
674 const retrying = yield* eventuallyState(
675 supervisor.state,
676 (state) => state.phase === "backoff" && state.attempt === 1,
677 );
678
679 expect(retrying).toMatchObject({
680 lastFailure: {
681 _tag: "ConnectionTransientError",
682 reason: "timeout",
683 message: "Test environment did not respond during connection setup.",
684 },
685 });
686 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
687 expect(yield* Ref.get(harness.sessionCount)).toBe(0);
688 }).pipe(Effect.provide(TestClock.layer())),
689 );
690
691 it.effect("treats an involuntary session close as transient and reconnects", () =>
692 Effect.gen(function* () {
693 const harness = yield* makeHarness();
694 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
695 initiallyDesired: true,
696 }).pipe(Effect.provide(harness.dependencies));
697
698 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
699 yield* harness.closeLatestSession();
700 yield* awaitState(
701 supervisor.state,
702 (state) => state.phase === "backoff" && state.attempt === 1,
703 );
704 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
705
706 yield* TestClock.adjust("1 second");
707 yield* awaitState(
708 supervisor.state,
709 (state) => state.phase === "connected" && state.generation === 2,
710 );
711
712 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
713 expect(Option.isSome(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
714 }).pipe(Effect.provide(TestClock.layer())),
715 );
716
717 it.effect("keeps escalating backoff when a newly opened session flaps", () =>
718 Effect.gen(function* () {
719 const harness = yield* makeHarness();
720 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
721 initiallyDesired: true,
722 }).pipe(Effect.provide(harness.dependencies));
723
724 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
725 yield* harness.closeLatestSession();
726 yield* awaitState(
727 supervisor.state,
728 (state) => state.phase === "backoff" && state.attempt === 1,
729 );
730
731 yield* TestClock.adjust("1 second");
732 yield* awaitState(
733 supervisor.state,
734 (state) => state.phase === "connected" && state.generation === 2,
735 );
736 yield* harness.closeLatestSession();
737 const secondFailure = yield* awaitState(
738 supervisor.state,
739 (state) => state.phase === "backoff" && state.attempt === 2,
740 );
741
742 expect(secondFailure.retryAt).not.toBeNull();
743
744 yield* TestClock.adjust("1 second");
745 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
746
747 yield* TestClock.adjust("1 second");
748 yield* awaitState(
749 supervisor.state,
750 (state) => state.phase === "connected" && state.generation === 3,
751 );
752 expect(yield* Ref.get(harness.sessionCount)).toBe(3);
753 }).pipe(Effect.provide(TestClock.layer())),
754 );
755
756 it.effect("restarts the retry ladder when mobile returns to the foreground", () =>
757 Effect.gen(function* () {
758 const harness = yield* makeHarness();
759 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
760 initiallyDesired: true,
761 }).pipe(Effect.provide(harness.dependencies));
762
763 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
764 yield* harness.closeLatestSession();
765 yield* awaitState(
766 supervisor.state,
767 (state) => state.phase === "backoff" && state.attempt === 1,
768 );
769 yield* TestClock.adjust("1 second");
770 yield* awaitState(
771 supervisor.state,
772 (state) => state.phase === "connected" && state.generation === 2,
773 );
774 yield* harness.closeLatestSession();
775 yield* awaitState(
776 supervisor.state,
777 (state) => state.phase === "backoff" && state.attempt === 2,
778 );
779
780 yield* harness.wake("application-active-reconnect");
781 yield* awaitState(
782 supervisor.state,
783 (state) => state.phase === "connected" && state.generation === 3 && state.attempt === 1,
784 );
785 yield* harness.closeLatestSession();
786 yield* awaitState(
787 supervisor.state,
788 (state) => state.phase === "backoff" && state.attempt === 1,
789 );
790
791 expect(yield* Ref.get(harness.sessionCount)).toBe(3);
792 }).pipe(Effect.provide(TestClock.layer())),
793 );
794
795 it.effect("restarts the retry ladder when a long resume replaces a connected session", () =>
796 Effect.gen(function* () {
797 const harness = yield* makeHarness();
798 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
799 initiallyDesired: true,
800 }).pipe(Effect.provide(harness.dependencies));
801
802 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
803 yield* harness.closeLatestSession();
804 yield* awaitState(
805 supervisor.state,
806 (state) => state.phase === "backoff" && state.attempt === 1,
807 );
808 yield* TestClock.adjust("1 second");
809 yield* awaitState(
810 supervisor.state,
811 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 2,
812 );
813
814 yield* harness.wake("application-active-reconnect");
815 yield* awaitState(
816 supervisor.state,
817 (state) => state.phase === "connected" && state.generation === 3 && state.attempt === 1,
818 );
819 }).pipe(Effect.provide(TestClock.layer())),
820 );
821
822 it.effect("restarts the retry ladder when a long resume interrupts connection setup", () =>
823 Effect.gen(function* () {
824 const harness = yield* makeHarness({
825 prepare: (attempt) => (attempt === 2 ? Effect.never : Effect.succeed(PREPARED_CONNECTION)),
826 });
827 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
828 initiallyDesired: true,
829 }).pipe(Effect.provide(harness.dependencies));
830
831 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
832 yield* harness.closeLatestSession();
833 yield* awaitState(
834 supervisor.state,
835 (state) => state.phase === "backoff" && state.attempt === 1,
836 );
837 yield* TestClock.adjust("1 second");
838 yield* awaitState(
839 supervisor.state,
840 (state) => state.phase === "connecting" && state.attempt === 2,
841 );
842
843 yield* harness.wake("application-active-reconnect");
844 yield* awaitState(
845 supervisor.state,
846 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
847 );
848 }).pipe(Effect.provide(TestClock.layer())),
849 );
850
851 it.effect("probes the active session without reconnecting on application activation", () =>
852 Effect.gen(function* () {
853 const probeCount = yield* Ref.make(0);
854 const probeCalled = yield* Deferred.make<void>();
855 const harness = yield* makeHarness({
856 probe: () =>
857 Ref.update(probeCount, (count) => count + 1).pipe(
858 Effect.andThen(Deferred.succeed(probeCalled, undefined)),
859 ),
860 });
861 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
862 initiallyDesired: true,
863 }).pipe(Effect.provide(harness.dependencies));
864
865 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
866 yield* harness.wake("application-active");
867 yield* Deferred.await(probeCalled);
868
869 expect(yield* Ref.get(probeCount)).toBe(1);
870 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
871 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
872 expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("connected");
873 }),
874 );
875
876 it.effect("immediately replaces a mobile session after a long background resume", () =>
877 Effect.gen(function* () {
878 const probeCount = yield* Ref.make(0);
879 const harness = yield* makeHarness({
880 probe: () => Ref.update(probeCount, (count) => count + 1),
881 });
882 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
883 initiallyDesired: true,
884 }).pipe(Effect.provide(harness.dependencies));
885
886 yield* awaitState(
887 supervisor.state,
888 (state) => state.phase === "connected" && state.generation === 1,
889 );
890 yield* harness.wake("application-active-reconnect");
891 yield* awaitState(
892 supervisor.state,
893 (state) => state.phase === "connected" && state.generation === 2,
894 );
895
896 expect(yield* Ref.get(probeCount)).toBe(0);
897 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
898 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
899 }),
900 );
901
902 it.effect("replaces a mobile session when a long resume interrupts an active probe", () =>
903 Effect.gen(function* () {
904 const harness = yield* makeHarness({
905 probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
906 });
907 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
908 initiallyDesired: true,
909 }).pipe(Effect.provide(harness.dependencies));
910
911 yield* awaitState(
912 supervisor.state,
913 (state) => state.phase === "connected" && state.generation === 1,
914 );
915 yield* harness.wake("application-active-probe");
916 yield* Effect.yieldNow;
917 yield* harness.wake("application-active-reconnect");
918 yield* awaitState(
919 supervisor.state,
920 (state) => state.phase === "connected" && state.generation === 2,
921 );
922
923 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
924 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
925 }),
926 );
927
928 it.effect("reconnects when the foreground liveness probe fails", () =>
929 Effect.gen(function* () {
930 const harness = yield* makeHarness({
931 probe: (attempt) =>
932 attempt === 1 ? Effect.fail(transient("The live session is stale.")) : Effect.void,
933 });
934 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
935 initiallyDesired: true,
936 }).pipe(Effect.provide(harness.dependencies));
937
938 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
939 yield* harness.wake("application-active");
940 yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
941 yield* TestClock.adjust("1 second");
942 yield* eventuallyState(
943 supervisor.state,
944 (state) => state.phase === "connected" && state.generation === 2,
945 );
946
947 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
948 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
949 }).pipe(Effect.provide(TestClock.layer())),
950 );
951
952 it.effect("quickly times out a stalled mobile foreground liveness probe", () =>
953 Effect.gen(function* () {
954 const harness = yield* makeHarness({
955 probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
956 });
957 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
958 initiallyDesired: true,
959 }).pipe(Effect.provide(harness.dependencies));
960
961 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
962 yield* harness.wake("application-active-probe");
963 yield* TestClock.adjust("3 seconds");
964 yield* awaitState(
965 supervisor.state,
966 (state) => state.phase === "backoff" && state.lastFailure?.reason === "timeout",
967 );
968 yield* TestClock.adjust("1 second");
969 yield* eventuallyState(
970 supervisor.state,
971 (state) => state.phase === "connected" && state.generation === 2,
972 );
973 }).pipe(Effect.provide(TestClock.layer())),
974 );
975
976 it.effect("honors an explicit disconnect while a foreground probe is stalled", () =>
977 Effect.gen(function* () {
978 const probeStarted = yield* Deferred.make<void>();
979 const harness = yield* makeHarness({
980 probe: () => Deferred.succeed(probeStarted, undefined).pipe(Effect.andThen(Effect.never)),
981 });
982 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
983 initiallyDesired: true,
984 }).pipe(Effect.provide(harness.dependencies));
985
986 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
987 yield* harness.wake("application-active");
988 yield* Deferred.await(probeStarted);
989 yield* supervisor.disconnect;
990 yield* awaitState(supervisor.state, (state) => state.phase === "available");
991
992 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
993 }),
994 );
995
996 it.effect("does not churn a healthy session when credentials change", () =>
997 Effect.gen(function* () {
998 const harness = yield* makeHarness();
999 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1000 initiallyDesired: true,
1001 }).pipe(Effect.provide(harness.dependencies));
1002
1003 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1004 yield* harness.wake("credentials-changed");
1005 yield* Effect.yieldNow;
1006
1007 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
1008 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
1009 expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("connected");
1010 }),
1011 );
1012
1013 it.effect("releases and reconnects a relay session when credentials change", () =>
1014 Effect.gen(function* () {
1015 const harness = yield* makeHarness();
1016 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
1017 initiallyDesired: true,
1018 }).pipe(Effect.provide(harness.dependencies));
1019
1020 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1021 yield* harness.wake("credentials-changed");
1022 yield* awaitState(
1023 supervisor.state,
1024 (state) => state.phase === "connected" && state.generation === 2,
1025 );
1026
1027 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
1028 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1029 }),
1030 );
1031
1032 it.effect("interrupts relay setup when credentials change", () =>
1033 Effect.gen(function* () {
1034 const firstAttemptStarted = yield* Deferred.make<void>();
1035 const harness = yield* makeHarness({
1036 prepare: (attempt) =>
1037 attempt === 1
1038 ? Deferred.succeed(firstAttemptStarted, undefined).pipe(Effect.andThen(Effect.never))
1039 : Effect.succeed(PREPARED_CONNECTION),
1040 });
1041 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
1042 initiallyDesired: true,
1043 }).pipe(Effect.provide(harness.dependencies));
1044
1045 yield* Deferred.await(firstAttemptStarted);
1046 yield* harness.wake("credentials-changed");
1047 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1048
1049 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
1050 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
1051 }),
1052 );
1053
1054 it.effect("explicit disconnect releases the session and returns to available", () =>
1055 Effect.gen(function* () {
1056 const harness = yield* makeHarness();
1057 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1058 initiallyDesired: true,
1059 }).pipe(Effect.provide(harness.dependencies));
1060
1061 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1062 yield* supervisor.disconnect;
1063 yield* awaitState(supervisor.state, (state) => state.phase === "available");
1064
1065 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1066 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
1067 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
1068 }),
1069 );
1070
1071 it.effect("does not lose an explicit disconnect among concurrent wakeup signals", () =>
1072 Effect.gen(function* () {
1073 const harness = yield* makeHarness();
1074 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1075 initiallyDesired: true,
1076 }).pipe(Effect.provide(harness.dependencies));
1077
1078 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1079 yield* Effect.all(
1080 [
1081 supervisor.disconnect,
1082 harness.wake("credentials-changed"),
1083 harness.wake("application-active"),
1084 harness.wake("credentials-changed"),
1085 ],
1086 { concurrency: "unbounded" },
1087 );
1088 yield* awaitState(supervisor.state, (state) => state.phase === "available");
1089
1090 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1091 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
1092 }),
1093 );
1094});