Open History to see the last commit
1import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Schedule from "effect/Schedule";
5
6export type ManagedTunnelRegistrationResult =
7 | { readonly status: "not_linked" | "ready" | "unavailable" | "superseded" }
8 | {
9 readonly status: "recovery_required";
10 readonly config: RelayManagedEndpointRuntimeConfig;
11 };
12
13export type ManagedTunnelStartupAction =
14 | { readonly action: "none" }
15 | { readonly action: "reconcile_link" }
16 | {
17 readonly action: "request_recovery";
18 readonly config: RelayManagedEndpointRuntimeConfig;
19 };
20
21export function managedTunnelStartupAction(input: {
22 readonly wantsCliLink: boolean;
23 readonly registration: ManagedTunnelRegistrationResult;
24}): ManagedTunnelStartupAction {
25 if (input.registration.status === "recovery_required") {
26 return {
27 action: "request_recovery",
28 config: input.registration.config,
29 };
30 }
31 if (input.wantsCliLink && input.registration.status === "not_linked") {
32 return { action: "reconcile_link" };
33 }
34 return { action: "none" };
35}
36
37// After this window the host can start its stored connector config while
38// registration keeps retrying to reconcile the origin when the relay returns.
39const MANAGED_TUNNEL_REGISTRATION_RETRY_WINDOW = Duration.minutes(10);
40
41export const retryManagedTunnelRegistration = <A, E, R>(
42 registration: Effect.Effect<A, E, R>,
43 isRetryable: (error: E) => boolean,
44 onRetryWindowExhausted?: Effect.Effect<void, never, R>,
45) => {
46 const schedule = Schedule.exponential("1 second").pipe(
47 Schedule.modifyDelay(({ duration }) =>
48 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
49 ),
50 Schedule.jittered,
51 );
52 const withinWindow = registration.pipe(
53 Effect.retry({
54 while: isRetryable,
55 schedule: schedule.pipe(
56 Schedule.upTo({ duration: MANAGED_TUNNEL_REGISTRATION_RETRY_WINDOW }),
57 ),
58 }),
59 );
60 if (onRetryWindowExhausted === undefined) return withinWindow;
61 return withinWindow.pipe(
62 Effect.catchIf(isRetryable, () =>
63 onRetryWindowExhausted.pipe(
64 Effect.andThen(registration.pipe(Effect.retry({ while: isRetryable, schedule }))),
65 ),
66 ),
67 );
68};
69
70// A host asks the relay for a replacement tunnel at most this often. Every
71// managed host shares one relay, so a host stuck in a bad loop must not turn
72// into a fleet-wide request storm.
73export const MANAGED_TUNNEL_RECOVERY_COOLDOWN = Duration.minutes(2);
74
75// Existing hosts register on their first boot after an upgrade, and desktop
76// auto-update delivers that boot to many hosts at once. Spread the first
77// registration so the relay and Cloudflare see a ramp instead of a spike.
78export const MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER = Duration.seconds(30);