fix(relay): tunnel recovery no longer drives the Cloudflare API into rate limits #22059
Mergedjuliusmarmingemerged 11 commits into
main fromrefs/pull/22059/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- infra/relay/src/environments/ManagedEndpointProvider.ts lines 646 to 699Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -505,0 +639,21 @@639+ ? Effect.succeedNone640+ : Effect.fail(failed("verify-tunnel", cause)),641+ }),642+ );643+ if (Option.isNone(recorded) || recorded.value.deletedAt) {644+ return Option.none<ManagedEndpointProvisioningResult>();645+ }646+ const connectorToken = yield* tunnels647+ .getToken(tunnelId)648+ .pipe(Effect.mapError((cause) => failed("get-tunnel-token", cause)));649+ yield* Effect.annotateCurrentSpan({ "relay.managed_endpoint.reused_ready_tunnel": true });650+ return Option.some<ManagedEndpointProvisioningResult>({651+ endpoint: managedEndpointForHostname(allocation.hostname),652+ runtime: {653+ providerKind: "cloudflare_tunnel",654+ connectorToken,655+ tunnelId,656+ tunnelName: allocation.tunnelName,657+ },658+ });659+ });
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -391,0 +438,21 @@438+// The SDK's default policy sleeps through Retry-After inside the request, which439+// held every caller until its timeout and kept the account over its limit.440+// Rate limits surface at once instead; other transient failures still retry.441+const withoutRateLimitRetries: CloudflareRetry.Factory = (lastError) => {442+ const defaults = CloudflareRetry.makeDefault(lastError);443+ return {444+ ...defaults,445+ while: (error) => !isCloudflareRateLimited(error) && (defaults.while?.(error) ?? false),446+ };447+};448+449+// Every isolate rereads the shared pause at most this often, so a quiet450+// period costs one query per isolate rather than one per Cloudflare call.451+const CLOUDFLARE_PAUSE_REFRESH_MILLIS = 5_000;452+453+/**454+ * The rate limit is account-wide, so once one call is rejected every other455+ * call is too, from any isolate. Failing them without a request leaves the456+ * account room to recover instead of extending the limit.457+ */458+const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext) => {infra/relay/src/environments/CloudflareApiPause.ts line 43Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +5,21 @@5+6+import * as RelayDb from "../db.ts";7+import { relayUpstreamApiPauses } from "../persistence/schema.ts";8+9+const CLOUDFLARE_API = "cloudflare";10+11+/**12+ * Cloudflare's API rate limit is per account, so a 429 seen by any isolate13+ * applies to all of them. Both operations fail open: a pause that cannot be14+ * read or recorded must not block provisioning.15+ */16+export class CloudflareApiPause extends Context.Service<17+ CloudflareApiPause,18+ {19+ /** Epoch milliseconds until which calls are paused, or 0. */20+ readonly pausedUntilMillis: Effect.Effect<number>;21+ readonly pauseUntil: (untilMillis: number) => Effect.Effect<void>;22+ }23+>()("t3code-relay/environments/CloudflareApiPause") {}24+25+export const make = Effect.gen(function* () {
- infra/relay/src/environments/CloudflareApiPause.ts line 43Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +5,21 @@5+6+import * as RelayDb from "../db.ts";7+import { relayUpstreamApiPauses } from "../persistence/schema.ts";8+9+const CLOUDFLARE_API = "cloudflare";10+11+/**12+ * Cloudflare's API rate limit is per account, so a 429 seen by any isolate13+ * applies to all of them. Both operations fail open: a pause that cannot be14+ * read or recorded must not block provisioning.15+ */16+export class CloudflareApiPause extends Context.Service<17+ CloudflareApiPause,18+ {19+ /** Epoch milliseconds until which calls are paused, or 0. */20+ readonly pausedUntilMillis: Effect.Effect<number>;21+ readonly pauseUntil: (untilMillis: number) => Effect.Effect<void>;22+ }23+>()("t3code-relay/environments/CloudflareApiPause") {}24+25+export const make = Effect.gen(function* () {
- infra/relay/src/environments/ManagedEndpointProvider.ts lines 479 to 479OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -391,0 +459,21 @@459+ * account room to recover instead of extending the limit.460+ */461+const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext) => {462+ let pausedUntilMillis = 0;463+ let checkedAtMillis = Number.NEGATIVE_INFINITY;464+ return (pause: CloudflareApiPause.CloudflareApiPause["Service"]) => {465+ const recordRateLimit = (cause: unknown) =>466+ Effect.gen(function* () {467+ const until = (yield* Clock.currentTimeMillis) + cloudflareRateLimitPauseMillis(cause);468+ pausedUntilMillis = Math.max(pausedUntilMillis, until);469+ yield* Effect.annotateCurrentSpan({ "relay.cloudflare.rate_limited": true });470+ yield* pause.pauseUntil(until);471+ });472+ return <A, E>(473+ call: Effect.Effect<A, E, Alchemy.RuntimeContext>,474+ ): Effect.Effect<A, E | CloudflareApiPaused | Cause.TimeoutError> =>475+ Effect.gen(function* () {476+ const now = yield* Clock.currentTimeMillis;477+ if (now >= pausedUntilMillis && now - checkedAtMillis >= CLOUDFLARE_PAUSE_REFRESH_MILLIS) {478+ checkedAtMillis = now;479+ pausedUntilMillis = Math.max(pausedUntilMillis, yield* pause.pausedUntilMillis);infra/relay/src/environments/ManagedEndpointProvider.ts line 690Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -505,0 +638,21 @@638+ tunnelName: allocation.tunnelName,639+ tunnelId,640+ cause,641+ });642+ const recorded = yield* tunnels.get(tunnelId).pipe(643+ Effect.asSome,644+ Effect.catchTags({645+ ManagedEndpointTunnelClientError: (cause) =>646+ isManagedEndpointNotFound(cause.cause)647+ ? Effect.succeedNone648+ : Effect.fail(failed("verify-tunnel", cause)),649+ }),650+ );651+ if (Option.isNone(recorded) || recorded.value.deletedAt) {652+ return Option.none<ManagedEndpointProvisioningResult>();653+ }654+ const connectorToken = yield* tunnels655+ .getToken(tunnelId)656+ .pipe(Effect.mapError((cause) => failed("get-tunnel-token", cause)));657+ yield* Effect.annotateCurrentSpan({ "relay.managed_endpoint.reused_ready_tunnel": true });658+ return Option.some<ManagedEndpointProvisioningResult>({
juliusmarminge merged this44a7cb1
juliusmarminge closed this
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
6a049d0· PR result:f62e021· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.