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

managedTunnelStartup.ts

214 lines8.1 KB

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