Open History to see the last commit
1import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
2import * as Clock from "effect/Clock";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Schedule from "effect/Schedule";
6import * as Semaphore from "effect/Semaphore";
7
8import { isRelayUnavailable, relayRetryAfterMillis } from "./relayResponse.ts";
9
10// "revoked" leads to no action: relinking a deregistered environment is the
11// user's call, so startup neither retries nor relinks it.
12export type ManagedTunnelRegistrationResult =
13 | { readonly status: "not_linked" | "ready" | "unavailable" | "superseded" | "revoked" }
14 | {
15 readonly status: "recovery_required";
16 readonly config: RelayManagedEndpointRuntimeConfig;
17 };
18
19export type ManagedTunnelStartupAction =
20 | { readonly action: "none" }
21 | { readonly action: "reconcile_link" }
22 | {
23 readonly action: "request_recovery";
24 readonly config: RelayManagedEndpointRuntimeConfig;
25 };
26
27export function managedTunnelStartupAction(input: {
28 readonly wantsCliLink: boolean;
29 readonly registration: ManagedTunnelRegistrationResult;
30}): ManagedTunnelStartupAction {
31 if (input.registration.status === "recovery_required") {
32 return {
33 action: "request_recovery",
34 config: input.registration.config,
35 };
36 }
37 if (input.wantsCliLink && input.registration.status === "not_linked") {
38 return { action: "reconcile_link" };
39 }
40 return { action: "none" };
41}
42
43const MANAGED_TUNNEL_REGISTRATION_RETRY_WINDOW = Duration.minutes(10);
44
45// Every host retries against the same relay, so while it is failing the
46// retries themselves are load. Backing off to minutes, and never sooner than
47// the relay's Retry-After, lets it recover instead of absorbing the storm.
48// Not HttpClient.retryTransient: it resends the identical request, and these
49// carry proofs that expire after 60 s or single-use link challenges, so each
50// retry has to re-run the whole operation.
51const RELAY_RETRY_MAX_DELAY = Duration.minutes(5);
52
53export const relayRetrySchedule = Schedule.exponential("1 second").pipe(
54 Schedule.jittered,
55 Schedule.modifyDelay(({ duration }) =>
56 Effect.succeed(Duration.min(duration, RELAY_RETRY_MAX_DELAY)),
57 ),
58 Schedule.modifyDelay(({ duration, input }) => {
59 const retryAfterMillis = relayRetryAfterMillis(input);
60 return Effect.succeed(
61 retryAfterMillis === undefined
62 ? duration
63 : Duration.max(duration, Duration.millis(retryAfterMillis)),
64 );
65 }),
66);
67
68const windowMillis = Duration.toMillis(MANAGED_TUNNEL_REGISTRATION_RETRY_WINDOW);
69
70/**
71 * Retries on the relay schedule. The window closes at the first sleep that
72 * would end past it: then `onWindowExhausted` runs, and retrying continues
73 * only while `whilePastWindow` holds. One schedule covers both sides, so the
74 * relay's Retry-After still holds across the handoff.
75 */
76const retryAcrossWindow = <A, E, R>(
77 effect: Effect.Effect<A, E, R>,
78 options: {
79 readonly while: (error: E) => boolean;
80 readonly whilePastWindow: (error: E) => boolean;
81 readonly onWindowExhausted: (error: E) => Effect.Effect<void, never, R>;
82 },
83) =>
84 Effect.suspend(() => {
85 let pastWindow = false;
86 return effect.pipe(
87 Effect.retry({
88 while: (error) => (pastWindow ? options.whilePastWindow(error) : options.while(error)),
89 schedule: relayRetrySchedule.pipe(
90 Schedule.setInputType<E>(),
91 Schedule.modifyDelay(({ duration, elapsed, input }) => {
92 if (pastWindow || elapsed + Duration.toMillis(duration) < windowMillis) {
93 return Effect.succeed(duration);
94 }
95 pastWindow = true;
96 return options.whilePastWindow(input)
97 ? options.onWindowExhausted(input).pipe(Effect.as(duration))
98 : Effect.fail(input);
99 }),
100 ),
101 }),
102 );
103 });
104
105export const retryManagedTunnelRegistration = <A, E, R>(
106 registration: Effect.Effect<A, E, R>,
107 isRetryable: (error: E) => boolean,
108 onRetryWindowExhausted?: Effect.Effect<void, never, R>,
109) =>
110 retryAcrossWindow(registration, {
111 while: isRetryable,
112 whilePastWindow: onRetryWindowExhausted === undefined ? () => false : isRetryable,
113 onWindowExhausted: () => onRetryWindowExhausted ?? Effect.void,
114 });
115
116/**
117 * Relinks a desired link at startup. Past the retry window it keeps going only
118 * while the relay itself is unavailable: a headless host has nobody to restart
119 * it once the relay recovers, but a local failure (cloudflared that cannot run)
120 * would otherwise relink, and provision a tunnel, forever.
121 */
122export const retryDesiredLinkReconcile = <A, E, R>(
123 reconcile: Effect.Effect<A, E, R>,
124 isRetryable: (error: E) => boolean,
125 onRetryWindowExhausted: (error: E) => Effect.Effect<void, never, R>,
126) =>
127 retryAcrossWindow(reconcile, {
128 while: isRetryable,
129 whilePastWindow: isRelayUnavailable,
130 onWindowExhausted: onRetryWindowExhausted,
131 });
132
133// Every managed host shares one relay, so a host stuck in a bad loop must not
134// turn into a fleet-wide request storm.
135export const MANAGED_TUNNEL_RECOVERY_COOLDOWN = Duration.minutes(2);
136
137// Retries inside one recovery, while the relay keeps failing, stay at least a
138// cooldown apart. They do not grow the cooldown: only a new request does.
139const managedTunnelRecoveryRetrySchedule = relayRetrySchedule.pipe(
140 Schedule.modifyDelay(({ duration }) =>
141 Effect.succeed(Duration.max(duration, MANAGED_TUNNEL_RECOVERY_COOLDOWN)),
142 ),
143);
144const MANAGED_TUNNEL_RECOVERY_MAX_COOLDOWN = Duration.minutes(30);
145// A recovery that fixed the tunnel stops the runtime asking for another, so a
146// request this long after the cooldown means the previous one worked.
147const MANAGED_TUNNEL_RECOVERY_SETTLED_AFTER = Duration.minutes(10);
148
149/**
150 * Recovery can only replace the relay-side tunnel. When the connector keeps
151 * failing for local reasons (no network, a firewall), the runtime keeps asking
152 * and recovery cannot help, so each request that follows right after a
153 * recovery doubles the wait, up to 30 minutes.
154 */
155export function nextManagedTunnelRecoveryCooldown(input: {
156 readonly current: Duration.Duration;
157 readonly sinceLastRecovery: Duration.Duration;
158}): Duration.Duration {
159 const settled = Duration.sum(input.current, MANAGED_TUNNEL_RECOVERY_SETTLED_AFTER);
160 if (Duration.isGreaterThanOrEqualTo(input.sinceLastRecovery, settled)) {
161 return MANAGED_TUNNEL_RECOVERY_COOLDOWN;
162 }
163 return Duration.min(Duration.times(input.current, 2), MANAGED_TUNNEL_RECOVERY_MAX_COOLDOWN);
164}
165
166// Existing hosts register on their first boot after an upgrade, and desktop
167// auto-update delivers that boot to many hosts at once. Spread the first
168// registration so the relay and Cloudflare see a ramp instead of a spike.
169export const MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER = Duration.seconds(30);
170
171/**
172 * Runs one recovery per request, one at a time: waits out the current
173 * cooldown, then calls the relay, retrying it while it stays unavailable.
174 */
175export const makeManagedTunnelRecovery = Effect.fn("ManagedTunnelRecovery.make")(function* <
176 A,
177 E,
178 R,
179>(options: {
180 readonly recover: (config: RelayManagedEndpointRuntimeConfig) => Effect.Effect<A, E, R>;
181 readonly isRetryable: (error: E) => boolean;
182}) {
183 const lock = yield* Semaphore.make(1);
184 let lastRecoveryAtMillis = Number.NEGATIVE_INFINITY;
185 let cooldown = MANAGED_TUNNEL_RECOVERY_COOLDOWN;
186 const waitForCooldown = Effect.gen(function* () {
187 const elapsed = (yield* Clock.currentTimeMillis) - lastRecoveryAtMillis;
188 cooldown = nextManagedTunnelRecoveryCooldown({
189 current: cooldown,
190 sinceLastRecovery: Duration.millis(elapsed),
191 });
192 const wait = Duration.toMillis(cooldown) - elapsed;
193 if (wait > 0) yield* Effect.sleep(Duration.millis(wait));
194 });
195 // Measured from the end: a recovery that retried through a long relay
196 // outage must not look settled the moment it finishes.
197 const recordRecovery = Clock.currentTimeMillis.pipe(
198 Effect.tap((now) =>
199 Effect.sync(() => {
200 lastRecoveryAtMillis = now;
201 }),
202 ),
203 );
204 return (config: RelayManagedEndpointRuntimeConfig) =>
205 lock.withPermits(1)(
206 waitForCooldown.pipe(
207 Effect.andThen(
208 options.recover(config).pipe(
209 Effect.retry({
210 while: options.isRetryable,
211 schedule: managedTunnelRecoveryRetrySchedule,
212 }),
213 Effect.ensuring(recordRecovery),
214 ),
215 ),
216 ),
217 );
218});