Skip to content
TypeScript

fix(server): T3 Connect backs off from a failing relay instead of hammering it (#22108)

Julius Marmingecd8a98657b99
diff --git a/apps/server/src/cloud/managedTunnelStartup.test.ts b/apps/server/src/cloud/managedTunnelStartup.test.ts
index e87f3e8e363..03d379a513f 100644
--- a/apps/server/src/cloud/managedTunnelStartup.test.ts
+++ b/apps/server/src/cloud/managedTunnelStartup.test.ts
@@ -1,13 +1,21 @@
import { describe, expect, it } from "@effect/vitest";
+import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as TestClock from "effect/testing/TestClock";
import {
+ MANAGED_TUNNEL_RECOVERY_COOLDOWN,
+ makeManagedTunnelRecovery,
managedTunnelStartupAction,
+ nextManagedTunnelRecoveryCooldown,
+ relayRetrySchedule,
+ retryDesiredLinkReconcile,
retryManagedTunnelRegistration,
} from "./managedTunnelStartup.ts";
+import { RelayRequestError } from "./relayResponse.ts";
describe("managedTunnelStartupAction", () => {
const config = {
@@ -129,3 +137,201 @@ describe("retryManagedTunnelRegistration", () => {
}),
);
});
+
+describe("nextManagedTunnelRecoveryCooldown", () => {
+ const minutes = (value: number) => Duration.minutes(value);
+
+ it("backs off while recoveries keep failing to fix the tunnel, up to 30 minutes", () => {
+ let cooldown = MANAGED_TUNNEL_RECOVERY_COOLDOWN;
+ const seen: Array<number> = [];
+ for (let attempt = 0; attempt < 6; attempt++) {
+ cooldown = nextManagedTunnelRecoveryCooldown({
+ current: cooldown,
+ sinceLastRecovery: minutes(3),
+ });
+ seen.push(Duration.toMinutes(cooldown));
+ }
+ expect(seen).toEqual([4, 8, 16, 30, 30, 30]);
+ });
+
+ it("starts over once the previous recovery held", () => {
+ expect(
+ Duration.toMinutes(
+ nextManagedTunnelRecoveryCooldown({ current: minutes(16), sinceLastRecovery: minutes(26) }),
+ ),
+ ).toBe(2);
+ expect(
+ Duration.toMinutes(
+ nextManagedTunnelRecoveryCooldown({ current: minutes(16), sinceLastRecovery: minutes(20) }),
+ ),
+ ).toBe(30);
+ });
+});
+
+describe("relayRetrySchedule", () => {
+ it.effect("waits at least as long as the relay's Retry-After", () =>
+ Effect.gen(function* () {
+ let attempts = 0;
+ const request = Effect.suspend(() => {
+ attempts += 1;
+ return attempts === 1
+ ? Effect.fail(
+ new RelayRequestError({
+ rejection: "unavailable",
+ description: "paused",
+ retryAfterMillis: 120_000,
+ }),
+ )
+ : Effect.succeed("done");
+ });
+ const fiber = yield* Effect.forkChild(
+ Effect.retry(request, { schedule: relayRetrySchedule }),
+ {
+ startImmediately: true,
+ },
+ );
+ yield* TestClock.adjust("90 seconds");
+ expect(attempts).toBe(1);
+ yield* TestClock.adjust("31 seconds");
+ expect(yield* Fiber.join(fiber)).toBe("done");
+ expect(attempts).toBe(2);
+ }),
+ );
+});
+
+describe("makeManagedTunnelRecovery", () => {
+ const config = {
+ providerKind: "cloudflare_tunnel" as const,
+ connectorToken: "connector-token",
+ tunnelId: "tunnel-1",
+ };
+
+ it.effect("retries an unavailable relay every cooldown, and cools down from when it ends", () =>
+ Effect.gen(function* () {
+ const attemptMinutes: Array<number> = [];
+ const recover = makeManagedTunnelRecovery({
+ recover: () =>
+ Effect.gen(function* () {
+ attemptMinutes.push((yield* Clock.currentTimeMillis) / 60_000);
+ return attemptMinutes.length < 4
+ ? yield* Effect.fail("relay unavailable" as const)
+ : true;
+ }),
+ isRetryable: () => true,
+ });
+ const run = yield* recover;
+ const fiber = yield* Effect.forkChild(run(config), { startImmediately: true });
+ yield* TestClock.adjust("6 minutes");
+ expect(yield* Fiber.join(fiber)).toBe(true);
+ expect(attemptMinutes.map(Math.round)).toEqual([0, 2, 4, 6]);
+
+ yield* TestClock.adjust("1 minute");
+ const next = yield* Effect.forkChild(run(config), { startImmediately: true });
+ yield* TestClock.adjust("10 minutes");
+ yield* Fiber.join(next);
+ expect(attemptMinutes.map(Math.round)).toEqual([0, 2, 4, 6, 10]);
+ }),
+ );
+});
+
+describe("retryManagedTunnelRegistration fallback", () => {
+ it.effect("falls back by the end of the window and keeps honoring Retry-After", () =>
+ Effect.gen(function* () {
+ let fallbackAtMillis: number | undefined;
+ const attemptMillis: Array<number> = [];
+ const registration = Clock.currentTimeMillis.pipe(
+ Effect.tap((now) => Effect.sync(() => attemptMillis.push(now))),
+ Effect.andThen(
+ Effect.fail(
+ new RelayRequestError({
+ rejection: "unavailable",
+ description: "paused",
+ retryAfterMillis: 900_000,
+ }),
+ ),
+ ),
+ );
+ yield* Effect.forkChild(
+ retryManagedTunnelRegistration(
+ registration,
+ () => true,
+ Clock.currentTimeMillis.pipe(
+ Effect.tap((now) =>
+ Effect.sync(() => {
+ fallbackAtMillis ??= now;
+ }),
+ ),
+ Effect.asVoid,
+ ),
+ ),
+ { startImmediately: true },
+ );
+ yield* TestClock.adjust("1 hour");
+ expect(fallbackAtMillis).toBeDefined();
+ expect(fallbackAtMillis).toBeLessThanOrEqual(10 * 60_000);
+ expect(attemptMillis.length).toBeGreaterThan(2);
+ for (let index = 1; index < attemptMillis.length; index++) {
+ expect(attemptMillis[index]! - attemptMillis[index - 1]!).toBeGreaterThanOrEqual(900_000);
+ }
+ }),
+ );
+});
+
+describe("retryDesiredLinkReconcile", () => {
+ const relayUnavailable = new RelayRequestError({
+ rejection: "unavailable",
+ description: "relay unavailable",
+ });
+
+ it.effect("gives up on a local failure once the retry window ends", () =>
+ Effect.gen(function* () {
+ let attempts = 0;
+ let windowLogs = 0;
+ const fiber = yield* Effect.forkChild(
+ Effect.flip(
+ retryDesiredLinkReconcile(
+ Effect.suspend(() => {
+ attempts += 1;
+ return Effect.fail("cloudflared cannot run" as const);
+ }),
+ () => true,
+ () =>
+ Effect.sync(() => {
+ windowLogs += 1;
+ }),
+ ),
+ ),
+ { startImmediately: true },
+ );
+ yield* TestClock.adjust("2 hours");
+ expect(yield* Fiber.join(fiber)).toBe("cloudflared cannot run");
+ expect(attempts).toBeLessThan(20);
+ expect(windowLogs).toBe(0);
+ }),
+ );
+
+ it.effect("keeps relinking while the relay is down and succeeds when it returns", () =>
+ Effect.gen(function* () {
+ let windowLogs = 0;
+ const reconcile = Effect.gen(function* () {
+ return (yield* Clock.currentTimeMillis) < 30 * 60_000
+ ? yield* Effect.fail(relayUnavailable)
+ : "managed";
+ });
+ const fiber = yield* Effect.forkChild(
+ retryDesiredLinkReconcile(
+ reconcile,
+ () => true,
+ () =>
+ Effect.sync(() => {
+ windowLogs += 1;
+ }),
+ ),
+ { startImmediately: true },
+ );
+ yield* TestClock.adjust("45 minutes");
+ expect(yield* Fiber.join(fiber)).toBe("managed");
+ expect(windowLogs).toBe(1);
+ }),
+ );
+});
diff --git a/apps/server/src/cloud/managedTunnelStartup.ts b/apps/server/src/cloud/managedTunnelStartup.ts
index bf442e848ad..7101a19b19f 100644
--- a/apps/server/src/cloud/managedTunnelStartup.ts
+++ b/apps/server/src/cloud/managedTunnelStartup.ts
@@ -1,7 +1,11 @@
import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
+import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
+import * as Semaphore from "effect/Semaphore";
+
+import { isRelayUnavailable, relayRetryAfterMillis } from "./relayResponse.ts";
// "revoked" leads to no action: relinking a deregistered environment is the
// user's call, so startup neither retries nor relinks it.
@@ -38,40 +42,177 @@ export function managedTunnelStartupAction(input: {
const MANAGED_TUNNEL_REGISTRATION_RETRY_WINDOW = Duration.minutes(10);
+// Every host retries against the same relay, so while it is failing the
+// retries themselves are load. Backing off to minutes, and never sooner than
+// the relay's Retry-After, lets it recover instead of absorbing the storm.
+// Not HttpClient.retryTransient: it resends the identical request, and these
+// carry proofs that expire after 60 s or single-use link challenges, so each
+// retry has to re-run the whole operation.
+const RELAY_RETRY_MAX_DELAY = Duration.minutes(5);
+
+export const relayRetrySchedule = Schedule.exponential("1 second").pipe(
+ Schedule.jittered,
+ Schedule.modifyDelay(({ duration }) =>
+ Effect.succeed(Duration.min(duration, RELAY_RETRY_MAX_DELAY)),
+ ),
+ Schedule.modifyDelay(({ duration, input }) => {
+ const retryAfterMillis = relayRetryAfterMillis(input);
+ return Effect.succeed(
+ retryAfterMillis === undefined
+ ? duration
+ : Duration.max(duration, Duration.millis(retryAfterMillis)),
+ );
+ }),
+);
+
+const windowMillis = Duration.toMillis(MANAGED_TUNNEL_REGISTRATION_RETRY_WINDOW);
+
+/**
+ * Retries on the relay schedule. The window closes at the first sleep that
+ * would end past it: then `onWindowExhausted` runs, and retrying continues
+ * only while `whilePastWindow` holds. One schedule covers both sides, so the
+ * relay's Retry-After still holds across the handoff.
+ */
+const retryAcrossWindow = <A, E, R>(
+ effect: Effect.Effect<A, E, R>,
+ options: {
+ readonly while: (error: E) => boolean;
+ readonly whilePastWindow: (error: E) => boolean;
+ readonly onWindowExhausted: (error: E) => Effect.Effect<void, never, R>;
+ },
+) =>
+ Effect.suspend(() => {
+ let pastWindow = false;
+ return effect.pipe(
+ Effect.retry({
+ while: (error) => (pastWindow ? options.whilePastWindow(error) : options.while(error)),
+ schedule: relayRetrySchedule.pipe(
+ Schedule.setInputType<E>(),
+ Schedule.modifyDelay(({ duration, elapsed, input }) => {
+ if (pastWindow || elapsed + Duration.toMillis(duration) < windowMillis) {
+ return Effect.succeed(duration);
+ }
+ pastWindow = true;
+ return options.whilePastWindow(input)
+ ? options.onWindowExhausted(input).pipe(Effect.as(duration))
+ : Effect.fail(input);
+ }),
+ ),
+ }),
+ );
+ });
+
export const retryManagedTunnelRegistration = <A, E, R>(
registration: Effect.Effect<A, E, R>,
isRetryable: (error: E) => boolean,
onRetryWindowExhausted?: Effect.Effect<void, never, R>,
-) => {
- const schedule = Schedule.exponential("1 second").pipe(
- Schedule.modifyDelay(({ duration }) =>
- Effect.succeed(Duration.min(duration, Duration.seconds(30))),
- ),
- Schedule.jittered,
- );
- const withinWindow = registration.pipe(
- Effect.retry({
- while: isRetryable,
- schedule: schedule.pipe(
- Schedule.upTo({ duration: MANAGED_TUNNEL_REGISTRATION_RETRY_WINDOW }),
- ),
- }),
- );
- if (onRetryWindowExhausted === undefined) return withinWindow;
- return withinWindow.pipe(
- Effect.catchIf(isRetryable, () =>
- onRetryWindowExhausted.pipe(
- Effect.andThen(registration.pipe(Effect.retry({ while: isRetryable, schedule }))),
- ),
- ),
- );
-};
+) =>
+ retryAcrossWindow(registration, {
+ while: isRetryable,
+ whilePastWindow: onRetryWindowExhausted === undefined ? () => false : isRetryable,
+ onWindowExhausted: () => onRetryWindowExhausted ?? Effect.void,
+ });
+
+/**
+ * Relinks a desired link at startup. Past the retry window it keeps going only
+ * while the relay itself is unavailable: a headless host has nobody to restart
+ * it once the relay recovers, but a local failure (cloudflared that cannot run)
+ * would otherwise relink, and provision a tunnel, forever.
+ */
+export const retryDesiredLinkReconcile = <A, E, R>(
+ reconcile: Effect.Effect<A, E, R>,
+ isRetryable: (error: E) => boolean,
+ onRetryWindowExhausted: (error: E) => Effect.Effect<void, never, R>,
+) =>
+ retryAcrossWindow(reconcile, {
+ while: isRetryable,
+ whilePastWindow: isRelayUnavailable,
+ onWindowExhausted: onRetryWindowExhausted,
+ });
// Every managed host shares one relay, so a host stuck in a bad loop must not
// turn into a fleet-wide request storm.
export const MANAGED_TUNNEL_RECOVERY_COOLDOWN = Duration.minutes(2);
+// Retries inside one recovery, while the relay keeps failing, stay at least a
+// cooldown apart. They do not grow the cooldown: only a new request does.
+const managedTunnelRecoveryRetrySchedule = relayRetrySchedule.pipe(
+ Schedule.modifyDelay(({ duration }) =>
+ Effect.succeed(Duration.max(duration, MANAGED_TUNNEL_RECOVERY_COOLDOWN)),
+ ),
+);
+const MANAGED_TUNNEL_RECOVERY_MAX_COOLDOWN = Duration.minutes(30);
+// A recovery that fixed the tunnel stops the runtime asking for another, so a
+// request this long after the cooldown means the previous one worked.
+const MANAGED_TUNNEL_RECOVERY_SETTLED_AFTER = Duration.minutes(10);
+
+/**
+ * Recovery can only replace the relay-side tunnel. When the connector keeps
+ * failing for local reasons (no network, a firewall), the runtime keeps asking
+ * and recovery cannot help, so each request that follows right after a
+ * recovery doubles the wait, up to 30 minutes.
+ */
+export function nextManagedTunnelRecoveryCooldown(input: {
+ readonly current: Duration.Duration;
+ readonly sinceLastRecovery: Duration.Duration;
+}): Duration.Duration {
+ const settled = Duration.sum(input.current, MANAGED_TUNNEL_RECOVERY_SETTLED_AFTER);
+ if (Duration.isGreaterThanOrEqualTo(input.sinceLastRecovery, settled)) {
+ return MANAGED_TUNNEL_RECOVERY_COOLDOWN;
+ }
+ return Duration.min(Duration.times(input.current, 2), MANAGED_TUNNEL_RECOVERY_MAX_COOLDOWN);
+}
+
// Existing hosts register on their first boot after an upgrade, and desktop
// auto-update delivers that boot to many hosts at once. Spread the first
// registration so the relay and Cloudflare see a ramp instead of a spike.
export const MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER = Duration.seconds(30);
+
+/**
+ * Runs one recovery per request, one at a time: waits out the current
+ * cooldown, then calls the relay, retrying it while it stays unavailable.
+ */
+export const makeManagedTunnelRecovery = Effect.fn("ManagedTunnelRecovery.make")(function* <
+ A,
+ E,
+ R,
+>(options: {
+ readonly recover: (config: RelayManagedEndpointRuntimeConfig) => Effect.Effect<A, E, R>;
+ readonly isRetryable: (error: E) => boolean;
+}) {
+ const lock = yield* Semaphore.make(1);
+ let lastRecoveryAtMillis = Number.NEGATIVE_INFINITY;
+ let cooldown = MANAGED_TUNNEL_RECOVERY_COOLDOWN;
+ const waitForCooldown = Effect.gen(function* () {
+ const elapsed = (yield* Clock.currentTimeMillis) - lastRecoveryAtMillis;
+ cooldown = nextManagedTunnelRecoveryCooldown({
+ current: cooldown,
+ sinceLastRecovery: Duration.millis(elapsed),
+ });
+ const wait = Duration.toMillis(cooldown) - elapsed;
+ if (wait > 0) yield* Effect.sleep(Duration.millis(wait));
+ });
+ // Measured from the end: a recovery that retried through a long relay
+ // outage must not look settled the moment it finishes.
+ const recordRecovery = Clock.currentTimeMillis.pipe(
+ Effect.tap((now) =>
+ Effect.sync(() => {
+ lastRecoveryAtMillis = now;
+ }),
+ ),
+ );
+ return (config: RelayManagedEndpointRuntimeConfig) =>
+ lock.withPermits(1)(
+ waitForCooldown.pipe(
+ Effect.andThen(
+ options.recover(config).pipe(
+ Effect.retry({
+ while: options.isRetryable,
+ schedule: managedTunnelRecoveryRetrySchedule,
+ }),
+ Effect.ensuring(recordRecovery),
+ ),
+ ),
+ ),
+ );
+});
diff --git a/apps/server/src/cloud/relayResponse.test.ts b/apps/server/src/cloud/relayResponse.test.ts
index 59f341aa3c4..88170942ee1 100644
--- a/apps/server/src/cloud/relayResponse.test.ts
+++ b/apps/server/src/cloud/relayResponse.test.ts
@@ -6,6 +6,7 @@ import * as HttpClientError from "effect/http/HttpClientError";
import {
filterRelayResponse,
relayRequestError,
+ relayRetryAfterMillis,
shouldRetryRelayRequest,
} from "./relayResponse.ts";
@@ -121,6 +122,27 @@ it.effect("reports an unrecognized access denial without printing its response b
}),
);
+it.effect("keeps the relay's Retry-After on a retryable failure", () =>
+ Effect.gen(function* () {
+ const seconds = yield* filterRelayResponse(
+ response(503, "paused", { "retry-after": "30" }),
+ ).pipe(Effect.flip);
+ expect(seconds).toMatchObject({ rejection: "unavailable", retryAfterMillis: 30_000 });
+ expect(relayRetryAfterMillis({ cause: { cause: seconds } })).toBe(30_000);
+
+ // The test clock starts at the epoch, so the date is 90 seconds after it.
+ const date = yield* filterRelayResponse(
+ response(429, "slow down", { "retry-after": "Thu, 01 Jan 1970 00:01:30 GMT" }),
+ ).pipe(Effect.flip);
+ expect(date.retryAfterMillis).toBe(90_000);
+
+ const malformed = yield* filterRelayResponse(
+ response(503, "paused", { "retry-after": "soon" }),
+ ).pipe(Effect.flip);
+ expect(malformed.retryAfterMillis).toBeUndefined();
+ }),
+);
+
it.effect.each([408, 429, 500, 502, 503, 504])(
"keeps transient HTTP %s failures retryable",
(status) =>
diff --git a/apps/server/src/cloud/relayResponse.ts b/apps/server/src/cloud/relayResponse.ts
index f86cc571940..33cefa88707 100644
--- a/apps/server/src/cloud/relayResponse.ts
+++ b/apps/server/src/cloud/relayResponse.ts
@@ -1,4 +1,5 @@
import { RelayProtectedError } from "@t3tools/contracts/relay";
+import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -15,6 +16,8 @@ export class RelayRequestError extends Schema.TaggedError<RelayRequestError>()(
{
rejection: Schema.Literals(["unauthorized", "forbidden", "rejected", "unavailable"]),
description: Schema.String,
+ /** How long the relay asked callers to wait (`Retry-After`) before retrying. */
+ retryAfterMillis: Schema.optionalKey(Schema.Number),
},
) {
override get message(): string {
@@ -36,6 +39,30 @@ export function relayRequestError(cause: unknown): RelayRequestError {
export const shouldRetryRelayRequest = (error: unknown): boolean =>
!isRelayRequestError(error) || error.rejection === "unavailable";
+/** The relay answered and asked to be retried later; nothing local is wrong. */
+export const isRelayUnavailable = (error: unknown): boolean =>
+ isRelayRequestError(error) && error.rejection === "unavailable";
+
+// Retry-After is either delay-seconds or an HTTP date (RFC 9110 §10.2.3).
+const MAX_RELAY_RETRY_AFTER_MILLIS = 15 * 60 * 1000;
+function parseRetryAfterMillis(value: string | undefined, nowMillis: number): number | undefined {
+ if (value === undefined) return undefined;
+ const trimmed = value.trim();
+ const millis = /^\d+$/.test(trimmed) ? Number(trimmed) * 1000 : Date.parse(trimmed) - nowMillis;
+ if (!Number.isFinite(millis) || millis <= 0) return undefined;
+ return Math.min(millis, MAX_RELAY_RETRY_AFTER_MILLIS);
+}
+
+/** The relay's requested wait, found anywhere in a failure's cause chain. */
+export function relayRetryAfterMillis(error: unknown): number | undefined {
+ for (let current = error, depth = 0; depth < 8; depth++) {
+ if (isRelayRequestError(current)) return current.retryAfterMillis;
+ if (typeof current !== "object" || current === null || !("cause" in current)) return undefined;
+ current = current.cause;
+ }
+ return undefined;
+}
+
function recoveryHint(error: RelayProtectedError): string {
switch (error._tag) {
case "RelayEnvironmentLinkLimitExceededError":
@@ -88,5 +115,13 @@ export const filterRelayResponse = Effect.fn("cloud.filter_relay_response")(func
) {
return yield* new RelayRequestError({ rejection: "rejected", description });
}
- return yield* new RelayRequestError({ rejection: "unavailable", description });
+ const retryAfterMillis = parseRetryAfterMillis(
+ response.headers["retry-after"],
+ yield* Clock.currentTimeMillis,
+ );
+ return yield* new RelayRequestError({
+ rejection: "unavailable",
+ description,
+ ...(retryAfterMillis === undefined ? {} : { retryAfterMillis }),
+ });
});
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index ed424a726a7..94485a4aa09 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -1,8 +1,6 @@
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
-import * as Clock from "effect/Clock";
import * as Random from "effect/Random";
-import * as Semaphore from "effect/Semaphore";
import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";
import * as StorageCleanup from "./storageCleanup.ts";
import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts";
@@ -22,7 +20,6 @@ import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
-import * as Schedule from "effect/Schedule";
import { FetchHttpClient, HttpRouter, HttpServer } from "effect/http";
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
@@ -148,8 +145,9 @@ import * as RelayTracing from "./cloud/relayTracing.ts";
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
import {
MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER,
- MANAGED_TUNNEL_RECOVERY_COOLDOWN,
+ makeManagedTunnelRecovery,
managedTunnelStartupAction,
+ retryDesiredLinkReconcile,
retryManagedTunnelRegistration,
} from "./cloud/managedTunnelStartup.ts";
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
@@ -855,42 +853,26 @@ const layerMakeServer = Layer.unwrap(
if (typeof address === "string" || !("port" in address)) return;
const localOrigin = `http://127.0.0.1:${address.port}`;
const endpointRuntime = yield* CloudManagedEndpointRuntime.CloudManagedEndpointRuntime;
- const recoveryLock = yield* Semaphore.make(1);
- let lastRecoveryAtMillis = 0;
+ const runManagedTunnelRecovery = yield* makeManagedTunnelRecovery({
+ recover: (config: RelayManagedEndpointRuntimeConfig) =>
+ cloudLink.recoverManagedTunnel(localOrigin, config, {
+ retryRuntimeFailures: true,
+ }),
+ isRetryable: (error) =>
+ CloudLink.shouldRetryCloudLink(error) &&
+ error._tag !== "CloudLinkEndpointUnavailableError",
+ });
const recoverManagedTunnel = (config: RelayManagedEndpointRuntimeConfig) =>
- recoveryLock.withPermits(1)(
- Effect.gen(function* () {
- const elapsed = (yield* Clock.currentTimeMillis) - lastRecoveryAtMillis;
- const wait = Duration.toMillis(MANAGED_TUNNEL_RECOVERY_COOLDOWN) - elapsed;
- if (wait > 0) yield* Effect.sleep(Duration.millis(wait));
- lastRecoveryAtMillis = yield* Clock.currentTimeMillis;
- }).pipe(
- Effect.andThen(
- cloudLink.recoverManagedTunnel(localOrigin, config, {
- retryRuntimeFailures: true,
- }),
- ),
- Effect.retry({
- while: (error) =>
- CloudLink.shouldRetryCloudLink(error) &&
- error._tag !== "CloudLinkEndpointUnavailableError",
- schedule: Schedule.exponential("1 second").pipe(
- Schedule.modifyDelay(({ duration }) =>
- Effect.succeed(Duration.min(duration, Duration.seconds(30))),
- ),
- Schedule.jittered,
- ),
- }),
- Effect.tap((recovered) =>
- recovered ? Effect.logInfo("T3 Connect managed tunnel recovered") : Effect.void,
- ),
- Effect.catchCause((cause) =>
- Cause.hasInterrupts(cause)
- ? Effect.interrupt
- : Effect.logWarning("Failed to recover the T3 Connect managed tunnel", {
- cause,
- }),
- ),
+ runManagedTunnelRecovery(config).pipe(
+ Effect.tap((recovered) =>
+ recovered ? Effect.logInfo("T3 Connect managed tunnel recovered") : Effect.void,
+ ),
+ Effect.catchCause((cause) =>
+ Cause.hasInterrupts(cause)
+ ? Effect.interrupt
+ : Effect.logWarning("Failed to recover the T3 Connect managed tunnel", {
+ cause,
+ }),
),
);
yield* endpointRuntime.recoveryRequests.pipe(
@@ -992,15 +974,13 @@ const layerMakeServer = Layer.unwrap(
const reconciledMode = yield* cloudLink
.reconcileDesiredLinkIfStillDesired(localOrigin)
.pipe(
- Effect.retry({
- while: CloudLink.shouldRetryCloudLink,
- schedule: Schedule.exponential("1 second").pipe(
- Schedule.modifyDelay(({ duration }) =>
- Effect.succeed(Duration.min(duration, Duration.seconds(30))),
+ (reconcile) =>
+ retryDesiredLinkReconcile(reconcile, CloudLink.shouldRetryCloudLink, (cause) =>
+ Effect.logWarning(
+ "T3 Connect relay is still unavailable; retrying the desired link in the background",
+ { cause },
),
- Schedule.upTo({ duration: "10 minutes" }),
),
- }),
Effect.tap((mode) =>
mode === null
? Effect.void