Open History to see the last commit
1import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
2import * as Cause from "effect/Cause";
3import * as Clock from "effect/Clock";
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Queue from "effect/Queue";
11import * as Ref from "effect/Ref";
12import * as Scope from "effect/Scope";
13import * as Stream from "effect/Stream";
14import * as SubscriptionRef from "effect/SubscriptionRef";
15import * as Tracer from "effect/Tracer";
16
17import type { ConnectionCatalogEntry } from "./catalog.ts";
18import * as Connectivity from "./connectivity.ts";
19import * as ConnectionDriver from "./driver.ts";
20import {
21 type ConnectionAttemptError,
22 type ConnectionTarget,
23 ConnectionTransientError,
24 type NetworkStatus,
25 type PreparedConnection,
26 type SupervisorConnectionState,
27} from "./model.ts";
28import * as RpcSession from "../rpc/session.ts";
29import { safeErrorLogAttributes } from "../errors/safeLog.ts";
30import * as ConnectionWakeups from "./wakeups.ts";
31
32const RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000] as const;
33const CONNECTION_ESTABLISHMENT_TIMEOUT = "15 seconds";
34const CONNECTION_PROBE_TIMEOUT = "15 seconds";
35const BACKOFF_RESET_AFTER_MS = 30_000;
36
37interface SupervisorIntent {
38 readonly desired: boolean;
39 readonly network: NetworkStatus;
40}
41
42type SupervisorSignal =
43 | { readonly _tag: "ConnectRequested" }
44 | { readonly _tag: "DisconnectRequested" }
45 | { readonly _tag: "RetryRequested" }
46 | { readonly _tag: "NetworkChanged"; readonly network: NetworkStatus }
47 | { readonly _tag: "Wakeup"; readonly reason: ConnectionWakeups.ConnectionWakeup };
48
49interface PendingRetryTrace {
50 readonly previousAttempt: Tracer.Span;
51 readonly failureCount: number;
52 readonly delayMs: number;
53 readonly reason: ConnectionAttemptError["reason"];
54}
55
56interface TracedAttemptFailure {
57 readonly error: ConnectionAttemptError;
58 readonly attemptSpan: Option.Option<Tracer.Span>;
59}
60
61type AttemptOutcome =
62 | {
63 readonly _tag: "Interrupted";
64 readonly established: boolean;
65 readonly stable: boolean;
66 }
67 | {
68 readonly _tag: "Failure";
69 readonly established: boolean;
70 readonly stable: boolean;
71 readonly failure: TracedAttemptFailure;
72 };
73
74type EstablishmentEvent =
75 | {
76 readonly _tag: "Completed";
77 readonly exit: Exit.Exit<
78 {
79 readonly attemptSpan: Option.Option<Tracer.Span>;
80 readonly lease: ConnectionDriver.EnvironmentConnectionLease;
81 },
82 TracedAttemptFailure
83 >;
84 }
85 | { readonly _tag: "Interrupted" }
86 | { readonly _tag: "TimedOut" };
87
88function exitUnlessInterrupted<A, E, R>(
89 effect: Effect.Effect<A, E, R>,
90): Effect.Effect<Exit.Exit<A, E>, never, R> {
91 return Effect.matchCauseEffect(effect, {
92 onFailure: (cause) =>
93 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Exit.failCause(cause)),
94 onSuccess: (value) => Effect.succeed(Exit.succeed(value)),
95 });
96}
97
98export interface EnvironmentSupervisorOptions {
99 readonly initiallyDesired?: boolean;
100}
101
102function retryDelayMs(failureCount: number): number {
103 return RETRY_DELAYS_MS[Math.min(failureCount, RETRY_DELAYS_MS.length - 1)] ?? 16_000;
104}
105
106function annotateTarget(target: ConnectionTarget) {
107 return Effect.annotateCurrentSpan({
108 "environment.id": target.environmentId,
109 "environment.label": target.label,
110 "environment.target.kind": target._tag,
111 });
112}
113
114function availableState(intent: SupervisorIntent, generation: number): SupervisorConnectionState {
115 return {
116 desired: false,
117 network: intent.network,
118 phase: "available",
119 stage: null,
120 attempt: 0,
121 generation,
122 lastFailure: null,
123 retryAt: null,
124 };
125}
126
127function offlineState(
128 intent: SupervisorIntent,
129 generation: number,
130 attempt: number,
131 lastFailure: ConnectionAttemptError | null,
132): SupervisorConnectionState {
133 return {
134 desired: true,
135 network: intent.network,
136 phase: "offline",
137 stage: null,
138 attempt,
139 generation,
140 lastFailure,
141 retryAt: null,
142 };
143}
144
145function connectingState(
146 intent: SupervisorIntent,
147 generation: number,
148 attempt: number,
149 lastFailure: ConnectionAttemptError | null,
150 stage: SupervisorConnectionState["stage"] = "preparing",
151): SupervisorConnectionState {
152 return {
153 desired: true,
154 network: intent.network,
155 phase: "connecting",
156 stage,
157 attempt,
158 generation,
159 lastFailure,
160 retryAt: null,
161 };
162}
163
164function failureFromExit<A>(
165 target: ConnectionTarget,
166 exit: Exit.Exit<A, TracedAttemptFailure>,
167 established: boolean,
168 stable: boolean,
169): AttemptOutcome {
170 if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) {
171 return { _tag: "Interrupted", established, stable };
172 }
173 const typedFailure = exit.cause.reasons.find(Cause.isFailReason);
174 if (typedFailure) {
175 return {
176 _tag: "Failure",
177 established,
178 stable,
179 failure: typedFailure.error,
180 };
181 }
182 return {
183 _tag: "Failure",
184 established,
185 stable,
186 failure: {
187 error: new ConnectionTransientError({
188 reason: "transport",
189 detail: `${target.label} connection failed unexpectedly.`,
190 }),
191 attemptSpan: Option.none(),
192 },
193 };
194}
195
196export class EnvironmentSupervisor extends Context.Service<
197 EnvironmentSupervisor,
198 {
199 readonly target: ConnectionTarget;
200 readonly state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>;
201 readonly session: SubscriptionRef.SubscriptionRef<Option.Option<RpcSession.RpcSession>>;
202 readonly prepared: SubscriptionRef.SubscriptionRef<Option.Option<PreparedConnection>>;
203 readonly connect: Effect.Effect<void>;
204 readonly disconnect: Effect.Effect<void>;
205 readonly retryNow: Effect.Effect<void>;
206 }
207>()("@t3tools/client-runtime/connection/supervisor/EnvironmentSupervisor") {}
208
209export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
210 entry: ConnectionCatalogEntry,
211 options?: EnvironmentSupervisorOptions,
212): Effect.fn.Return<
213 EnvironmentSupervisor["Service"],
214 never,
215 | Connectivity.Connectivity
216 | ConnectionDriver.ConnectionDriver
217 | Scope.Scope
218 | ConnectionWakeups.ConnectionWakeups
219> {
220 const target = entry.target;
221 yield* annotateTarget(target);
222
223 const connectivity = yield* Connectivity.Connectivity;
224 const driver = yield* ConnectionDriver.ConnectionDriver;
225 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
226 const initialIntent: SupervisorIntent = {
227 desired: options?.initiallyDesired ?? false,
228 network: yield* connectivity.status,
229 };
230 const intent = yield* Ref.make(initialIntent);
231 const signals = yield* Queue.unbounded<SupervisorSignal>();
232 const state = yield* SubscriptionRef.make<SupervisorConnectionState>(
233 !initialIntent.desired
234 ? availableState(initialIntent, 0)
235 : initialIntent.network === "offline"
236 ? offlineState(initialIntent, 0, 0, null)
237 : connectingState(initialIntent, 0, 1, null),
238 );
239 const session = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(Option.none());
240 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none());
241
242 const clearLease = Effect.all(
243 [SubscriptionRef.set(session, Option.none()), SubscriptionRef.set(prepared, Option.none())],
244 { discard: true },
245 );
246
247 const setState = Effect.fn("EnvironmentSupervisor.setState")(function* (
248 next: SupervisorConnectionState,
249 ) {
250 yield* SubscriptionRef.set(state, next);
251 });
252
253 const signal = Effect.fn("EnvironmentSupervisor.signal")(function* (next: SupervisorSignal) {
254 yield* Queue.offer(signals, next);
255 });
256
257 const logManagedRelayAccountChange = Effect.logInfo(
258 "Managed relay account changed; restarting the environment connection.",
259 ).pipe(
260 Effect.annotateLogs({
261 "environment.id": target.environmentId,
262 "environment.label": target.label,
263 }),
264 );
265
266 const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* (
267 attempt: number,
268 generation: number,
269 lastFailure: ConnectionAttemptError | null,
270 progress: ConnectionDriver.ConnectionDriverProgress,
271 ) {
272 if ("prepared" in progress) {
273 yield* SubscriptionRef.set(prepared, Option.some(progress.prepared));
274 }
275 yield* setState(
276 connectingState(yield* Ref.get(intent), generation, attempt, lastFailure, progress.stage),
277 );
278 });
279
280 const establishConnection = Effect.fnUntraced(function* (
281 attempt: number,
282 generation: number,
283 lastFailure: ConnectionAttemptError | null,
284 ) {
285 return yield* driver.connect(entry, (progress) =>
286 reportProgress(attempt, generation, lastFailure, progress),
287 );
288 });
289
290 const traceRelayEstablishment = (
291 effect: Effect.Effect<
292 ConnectionDriver.EnvironmentConnectionLease,
293 ConnectionAttemptError,
294 Scope.Scope
295 >,
296 attempt: number,
297 generation: number,
298 pendingRetry: Option.Option<PendingRetryTrace>,
299 ) => {
300 const traced = Effect.gen(function* () {
301 const attemptSpan = yield* Effect.currentSpan.pipe(Effect.orDie);
302 yield* annotateTarget(target);
303 yield* Effect.annotateCurrentSpan({
304 "connection.attempt": attempt,
305 "connection.generation": generation,
306 "connection.retry.failure_count": Option.match(pendingRetry, {
307 onNone: () => 0,
308 onSome: (retry) => retry.failureCount,
309 }),
310 });
311 const lease = yield* effect.pipe(
312 Effect.mapError(
313 (error): TracedAttemptFailure => ({
314 error,
315 attemptSpan: Option.some(attemptSpan),
316 }),
317 ),
318 );
319 return { attemptSpan: Option.some(attemptSpan), lease };
320 }).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));
321
322 return Option.match(pendingRetry, {
323 onNone: () => traced,
324 onSome: (retry) =>
325 traced.pipe(
326 Effect.linkSpans(retry.previousAttempt, {
327 "connection.retry.delay_ms": retry.delayMs,
328 "connection.retry.reason": retry.reason,
329 }),
330 ),
331 }).pipe(withRelayClientTracing);
332 };
333
334 const establishTracedConnection = Effect.fnUntraced(function* (
335 attempt: number,
336 generation: number,
337 lastFailure: ConnectionAttemptError | null,
338 pendingRetry: Option.Option<PendingRetryTrace>,
339 ) {
340 if (target._tag === "RelayConnectionTarget") {
341 return yield* traceRelayEstablishment(
342 establishConnection(attempt, generation, lastFailure),
343 attempt,
344 generation,
345 pendingRetry,
346 );
347 }
348 return yield* establishConnection(attempt, generation, lastFailure).pipe(
349 Effect.map((lease) => ({
350 attemptSpan: Option.none<Tracer.Span>(),
351 lease,
352 })),
353 Effect.mapError(
354 (error): TracedAttemptFailure => ({
355 error,
356 attemptSpan: Option.none(),
357 }),
358 ),
359 );
360 });
361
362 const waitForEstablishmentInterrupt = Effect.fnUntraced(function* () {
363 for (;;) {
364 const next = yield* Queue.take(signals);
365 switch (next._tag) {
366 case "DisconnectRequested":
367 case "RetryRequested":
368 return;
369 case "NetworkChanged":
370 if (next.network === "offline") {
371 return;
372 }
373 break;
374 case "ConnectRequested":
375 break;
376 case "Wakeup":
377 if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
378 yield* logManagedRelayAccountChange;
379 return;
380 }
381 break;
382 }
383 }
384 });
385
386 const monitorConnectedLease = Effect.fnUntraced(function* (
387 lease: ConnectionDriver.EnvironmentConnectionLease,
388 ) {
389 for (;;) {
390 const next = yield* Queue.take(signals);
391 switch (next._tag) {
392 case "DisconnectRequested":
393 case "RetryRequested":
394 return;
395 case "NetworkChanged":
396 if (next.network === "offline") {
397 return;
398 }
399 break;
400 case "Wakeup":
401 if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
402 yield* logManagedRelayAccountChange;
403 return;
404 }
405 if (next.reason === "application-active") {
406 const probe = yield* lease.session.probe.pipe(
407 Effect.timeoutOrElse({
408 duration: CONNECTION_PROBE_TIMEOUT,
409 orElse: () =>
410 Effect.fail(
411 new ConnectionTransientError({
412 reason: "timeout",
413 detail: `${target.label} did not respond to a connection health check.`,
414 }),
415 ),
416 }),
417 Effect.forkChild,
418 );
419 for (;;) {
420 const probeEvent = yield* Effect.raceFirst(
421 Fiber.await(probe).pipe(
422 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
423 ),
424 Queue.take(signals).pipe(
425 Effect.map((signal) => ({ _tag: "Signal" as const, signal })),
426 ),
427 );
428 if (probeEvent._tag === "ProbeCompleted") {
429 yield* probeEvent.exit;
430 break;
431 }
432 switch (probeEvent.signal._tag) {
433 case "DisconnectRequested":
434 case "RetryRequested":
435 yield* Fiber.interrupt(probe);
436 return;
437 case "NetworkChanged":
438 if (probeEvent.signal.network === "offline") {
439 yield* Fiber.interrupt(probe);
440 return;
441 }
442 break;
443 case "ConnectRequested":
444 case "Wakeup":
445 break;
446 }
447 }
448 }
449 break;
450 case "ConnectRequested":
451 break;
452 }
453 }
454 });
455
456 const runAttempt = Effect.fnUntraced(function* (
457 attempt: number,
458 generation: number,
459 lastFailure: ConnectionAttemptError | null,
460 pendingRetry: Option.Option<PendingRetryTrace>,
461 ) {
462 yield* SubscriptionRef.set(prepared, Option.none());
463 const establishment = yield* Effect.raceAllFirst([
464 exitUnlessInterrupted(
465 establishTracedConnection(attempt, generation, lastFailure, pendingRetry),
466 ).pipe(
467 Effect.map(
468 (exit): EstablishmentEvent => ({
469 _tag: "Completed",
470 exit,
471 }),
472 ),
473 ),
474 waitForEstablishmentInterrupt().pipe(Effect.as<EstablishmentEvent>({ _tag: "Interrupted" })),
475 Effect.sleep(CONNECTION_ESTABLISHMENT_TIMEOUT).pipe(
476 Effect.as<EstablishmentEvent>({ _tag: "TimedOut" }),
477 ),
478 ]);
479
480 if (establishment._tag === "Interrupted") {
481 return {
482 _tag: "Interrupted",
483 established: false,
484 stable: false,
485 } satisfies AttemptOutcome;
486 }
487 if (establishment._tag === "TimedOut") {
488 return {
489 _tag: "Failure",
490 established: false,
491 stable: false,
492 failure: {
493 error: new ConnectionTransientError({
494 reason: "timeout",
495 detail: `${target.label} did not respond during connection setup.`,
496 }),
497 attemptSpan: Option.none(),
498 },
499 } satisfies AttemptOutcome;
500 }
501 if (Exit.isFailure(establishment.exit)) {
502 const isUnexpectedDefect =
503 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
504 !establishment.exit.cause.reasons.some(Cause.isFailReason);
505 const outcome = failureFromExit(target, establishment.exit, false, false);
506 if (isUnexpectedDefect) {
507 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
508 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
509 Effect.annotateLogs({
510 "environment.id": target.environmentId,
511 "environment.label": target.label,
512 "cause.reason_count": establishment.exit.cause.reasons.length,
513 ...safeErrorLogAttributes(defect),
514 }),
515 );
516 }
517 return outcome;
518 }
519
520 const active = establishment.exit.value;
521 const currentIntent = yield* Ref.get(intent);
522 if (!currentIntent.desired || currentIntent.network === "offline") {
523 return {
524 _tag: "Interrupted",
525 established: false,
526 stable: false,
527 } satisfies AttemptOutcome;
528 }
529
530 const connectedAt = yield* Clock.currentTimeMillis;
531 yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
532 yield* SubscriptionRef.set(session, Option.some(active.lease.session));
533 yield* setState({
534 desired: true,
535 network: currentIntent.network,
536 phase: "connected",
537 stage: null,
538 attempt,
539 generation,
540 lastFailure: null,
541 retryAt: null,
542 });
543
544 const connectedExit = yield* Effect.raceFirst(
545 active.lease.session.closed.pipe(
546 Effect.mapError(
547 (error): TracedAttemptFailure => ({
548 error,
549 attemptSpan: active.attemptSpan,
550 }),
551 ),
552 ),
553 monitorConnectedLease(active.lease).pipe(
554 Effect.mapError(
555 (error): TracedAttemptFailure => ({
556 error,
557 attemptSpan: active.attemptSpan,
558 }),
559 ),
560 ),
561 ).pipe(exitUnlessInterrupted);
562 const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
563 return failureFromExit(target, connectedExit, true, connectedForMs >= BACKOFF_RESET_AFTER_MS);
564 }, Effect.ensuring(clearLease));
565
566 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
567 return yield* Effect.raceFirst(
568 Effect.sleep(delayMs),
569 Effect.gen(function* () {
570 for (;;) {
571 const next = yield* Queue.take(signals);
572 switch (next._tag) {
573 case "ConnectRequested":
574 case "DisconnectRequested":
575 case "RetryRequested":
576 case "NetworkChanged":
577 case "Wakeup":
578 return;
579 }
580 }
581 }),
582 );
583 });
584
585 const waitForSignal = Queue.take(signals);
586
587 const run = Effect.fnUntraced(function* () {
588 let failureCount = 0;
589 let generation = 0;
590 let latestFailure: ConnectionAttemptError | null = null;
591 let pendingRetry = Option.none<PendingRetryTrace>();
592
593 for (;;) {
594 const currentIntent = yield* Ref.get(intent);
595 if (!currentIntent.desired) {
596 failureCount = 0;
597 latestFailure = null;
598 pendingRetry = Option.none();
599 yield* clearLease;
600 yield* setState(availableState(currentIntent, generation));
601 yield* waitForSignal;
602 continue;
603 }
604 if (currentIntent.network === "offline") {
605 yield* clearLease;
606 yield* setState(offlineState(currentIntent, generation, failureCount + 1, latestFailure));
607 yield* waitForSignal;
608 continue;
609 }
610
611 const attempt = failureCount + 1;
612 const nextGeneration = generation + 1;
613 const outcome: AttemptOutcome = yield* Effect.scoped(
614 runAttempt(attempt, nextGeneration, latestFailure, pendingRetry),
615 );
616 if (outcome.established) {
617 generation = nextGeneration;
618 if (outcome.stable) {
619 failureCount = 0;
620 latestFailure = null;
621 pendingRetry = Option.none();
622 }
623 }
624 if (outcome._tag === "Interrupted") {
625 continue;
626 }
627
628 const attemptSpan: Option.Option<Tracer.Span> = outcome.failure.attemptSpan;
629 const error: ConnectionAttemptError = outcome.failure.error;
630 latestFailure = error;
631 if (error._tag === "ConnectionBlockedError") {
632 const blockedIntent = yield* Ref.get(intent);
633 yield* setState({
634 desired: blockedIntent.desired,
635 network: blockedIntent.network,
636 phase: "blocked",
637 stage: null,
638 attempt,
639 generation,
640 lastFailure: error,
641 retryAt: null,
642 });
643 yield* waitForSignal;
644 continue;
645 }
646
647 failureCount += 1;
648 const delayMs = retryDelayMs(failureCount - 1);
649 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
650 previousAttempt,
651 failureCount,
652 delayMs,
653 reason: error.reason,
654 }));
655 const failedIntent = yield* Ref.get(intent);
656 yield* setState({
657 desired: failedIntent.desired,
658 network: failedIntent.network,
659 phase: "backoff",
660 stage: null,
661 attempt,
662 generation,
663 lastFailure: error,
664 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
665 });
666 yield* waitForRetrySignal(delayMs);
667 }
668 });
669
670 yield* connectivity.changes.pipe(
671 Stream.runForEach((network) =>
672 Ref.modify(intent, (current) =>
673 current.network === network ? [false, current] : ([true, { ...current, network }] as const),
674 ).pipe(
675 Effect.flatMap((changed) =>
676 changed ? signal({ _tag: "NetworkChanged", network }) : Effect.void,
677 ),
678 ),
679 ),
680 Effect.forkScoped,
681 );
682 yield* wakeups.changes.pipe(
683 Stream.runForEach((reason) => signal({ _tag: "Wakeup", reason })),
684 Effect.forkScoped,
685 );
686 yield* run().pipe(Effect.forkScoped);
687
688 const connect = Ref.update(intent, (current) => ({
689 ...current,
690 desired: true,
691 })).pipe(
692 Effect.andThen(signal({ _tag: "ConnectRequested" })),
693 Effect.withSpan("EnvironmentSupervisor.connect"),
694 );
695
696 const disconnect = Ref.update(intent, (current) => ({
697 ...current,
698 desired: false,
699 })).pipe(
700 Effect.andThen(signal({ _tag: "DisconnectRequested" })),
701 Effect.withSpan("EnvironmentSupervisor.disconnect"),
702 );
703
704 const retryNow = signal({ _tag: "RetryRequested" }).pipe(
705 Effect.withSpan("EnvironmentSupervisor.retryNow"),
706 );
707
708 yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease)));
709
710 return EnvironmentSupervisor.of({
711 target,
712 state,
713 session,
714 prepared,
715 connect,
716 disconnect,
717 retryNow,
718 });
719});
720
721export const layer = (
722 entry: ConnectionCatalogEntry,
723 options?: EnvironmentSupervisorOptions,
724): Layer.Layer<
725 EnvironmentSupervisor,
726 never,
727 | Connectivity.Connectivity
728 | ConnectionDriver.ConnectionDriver
729 | ConnectionWakeups.ConnectionWakeups
730> => Layer.effect(EnvironmentSupervisor, make(entry, options));