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

managedTunnelStartup.ts

77 lines2.7 KB

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​
6// "revoked" leads to no action: relinking a deregistered environment is the
7// user's call, so startup neither retries nor relinks it.
8export type ManagedTunnelRegistrationResult =
9 | { readonly status: "not_linked" | "ready" | "unavailable" | "superseded" | "revoked" }
10 | {
11 readonly status: "recovery_required";
12 readonly config: RelayManagedEndpointRuntimeConfig;
13 };
14​
15export type ManagedTunnelStartupAction =
16 | { readonly action: "none" }
17 | { readonly action: "reconcile_link" }
18 | {
19 readonly action: "request_recovery";
20 readonly config: RelayManagedEndpointRuntimeConfig;
21 };
22​
23export function managedTunnelStartupAction(input: {
24 readonly wantsCliLink: boolean;
25 readonly registration: ManagedTunnelRegistrationResult;
26}): ManagedTunnelStartupAction {
27 if (input.registration.status === "recovery_required") {
28 return {
29 action: "request_recovery",
30 config: input.registration.config,
31 };
32 }
33 if (input.wantsCliLink && input.registration.status === "not_linked") {
34 return { action: "reconcile_link" };
35 }
36 return { action: "none" };
38​
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// Every managed host shares one relay, so a host stuck in a bad loop must not
71// turn into a fleet-wide request storm.
72export const MANAGED_TUNNEL_RECOVERY_COOLDOWN = Duration.minutes(2);
73​
74// Existing hosts register on their first boot after an upgrade, and desktop
75// auto-update delivers that boot to many hosts at once. Spread the first
76// registration so the relay and Cloudflare see a ramp instead of a spike.
77export const MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER = Duration.seconds(30);