From c4264fda03f51805fe36a4c3c8c3026c583baad8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 18:09:56 -0700 Subject: [PATCH 1/9] fix(relay): tunnel recovery no longer drives the Cloudflare API into rate limits Host recovery requests re-ran a full tunnel provision (list, ingress, DNS, token) even when the tunnel was ready for the same origin, and the Cloudflare SDK slept through every 429 until the relay's 8 s timeout. On 2026-10-19 that tipped the account into sustained rate limiting: links and recoveries both stalled into 503/504 and their retries kept the limit in place. - Recovery of a ready tunnel for an unchanged origin now only checks the tunnel exists and fetches its token, falling back to a full provision otherwise. Links still fully provision. - Cloudflare rate limits are no longer retried inside the request, and a 429 pauses this isolate's Cloudflare calls for its Retry-After so callers fail fast instead of extending the limit. Refs #16810 Co-Authored-By: Claude Opus 5.5 --- infra/relay/package.json | 1 + .../ManagedEndpointProvider.test.ts | 122 ++++++++++ .../environments/ManagedEndpointProvider.ts | 208 +++++++++++++++--- infra/relay/src/http/Api.ts | 1 + pnpm-lock.yaml | 3 + 5 files changed, 303 insertions(+), 32 deletions(-) diff --git a/infra/relay/package.json b/infra/relay/package.json index 2992bb56a12ad..d1cad6500b461 100644 --- a/infra/relay/package.json +++ b/infra/relay/package.json @@ -13,6 +13,7 @@ }, "dependencies": { "@clerk/backend": "catalog:", + "@distilled.cloud/cloudflare": "1.0.0-rc.13", "@effect/sql-pg": "catalog:", "@effect/sql-sqlite-do": "catalog:", "@noble/curves": "catalog:", diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index 2e8c895d11005..04ba2b48c920c 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -6,6 +6,7 @@ import * as Cloudflare from "alchemy/Cloudflare"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; +import * as TestClock from "effect/testing/TestClock"; import * as RelayConfiguration from "../Config.ts"; import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts"; @@ -754,6 +755,127 @@ describe("ManagedEndpointProvider", () => { }).pipe(Effect.provide(layer)); }); + it.effect("recovers a ready tunnel for the same origin with only reads", () => { + const tunnelCalls: TunnelCall[] = []; + const dnsCalls: DnsCall[] = []; + const allocationCalls: AllocationCall[] = []; + const layer = layerProvider( + makePersistentTunnelClient(tunnelCalls), + makeDnsClient(dnsCalls), + makeAllocations(allocationCalls), + ); + + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + const request = { + userId: "user_ABC", + environmentId: "env_ABC", + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + } as const; + const provisioned = yield* provider.provision(request); + tunnelCalls.length = 0; + dnsCalls.length = 0; + allocationCalls.length = 0; + + const recovered = yield* provider.provision({ ...request, reuseReadyTunnel: true }); + + expect(recovered).toEqual(provisioned); + expect(tunnelCalls.map((call) => call.operation)).toEqual(["get", "getToken"]); + expect(dnsCalls).toEqual([]); + expect(allocationCalls.map((call) => call.operation)).toEqual(["reserve"]); + }).pipe(Effect.provide(layer)); + }); + + it.effect("fully provisions a recovery when the ready tunnel cannot be reused", () => { + const tunnelCalls: TunnelCall[] = []; + const tunnelClient = makePersistentTunnelClient(tunnelCalls); + const layer = layerProvider(tunnelClient); + + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + const request = { + userId: "user_ABC", + environmentId: "env_ABC", + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + reuseReadyTunnel: true, + } as const; + yield* provider.provision(request); + + tunnelCalls.length = 0; + yield* provider.provision({ + ...request, + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3774 }, + }); + expect(tunnelCalls.map((call) => call.operation)).toEqual([ + "list", + "putConfiguration", + "getToken", + ]); + + yield* tunnelClient.delete("tunnel-id"); + tunnelCalls.length = 0; + yield* provider.provision({ + ...request, + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3774 }, + }); + expect(tunnelCalls.map((call) => call.operation)).toEqual([ + "get", + "list", + "create", + "putConfiguration", + "getToken", + ]); + }).pipe(Effect.provide(layer)); + }); + + it.effect("stops calling Cloudflare until a rate limit has passed", () => { + let listCalls = 0; + const tunnelClient = { + list: () => + Effect.suspend(() => { + listCalls += 1; + return Effect.fail({ _tag: "TooManyRequests", message: "Rate limited" }); + }), + } as unknown as Cloudflare.Tunnel.ReadWriteTunnelClient; + const layer = ManagedEndpointProvider.layerCloudflareBindings( + tunnelClient, + {} as Cloudflare.DNS.ReadWriteDnsClient, + {} as Alchemy.BaseRuntimeContext, + ).pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(RelayConfiguration.layer(config)), + Layer.provide( + Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()), + ), + Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())), + ); + + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + const provision = provider + .provision({ + userId: "user_ABC", + environmentId: "env_ABC", + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }) + .pipe(Effect.flip); + + const rateLimited = yield* provision; + const paused = yield* provision; + expect(listCalls).toBe(1); + expect(ManagedEndpointProvider.isCloudflareRateLimited(rateLimited)).toBe(true); + expect(paused).toMatchObject({ + _tag: "ManagedEndpointProvisioningFailed", + stage: "ensure-tunnel", + cause: { cause: { _tag: "CloudflareApiPaused" } }, + }); + + yield* TestClock.adjust("30 seconds"); + yield* provision; + expect(listCalls).toBe(2); + }).pipe(Effect.provide(layer)); + }); + it.effect("recreates a checkpointed DNS record when it was removed externally", () => { const dnsCalls: DnsCall[] = []; const allocationCalls: AllocationCall[] = []; diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index bb906db16a8fa..659050ce469be 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -1,9 +1,13 @@ +import * as CloudflareRetry from "@distilled.cloud/cloudflare/Retry"; import * as Alchemy from "alchemy"; import * as Cloudflare from "alchemy/Cloudflare"; import * as Arr from "effect/Array"; +import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as Layer from "effect/Layer"; @@ -148,6 +152,11 @@ export class ManagedEndpointProvider extends Context.Service< readonly userId: string; readonly environmentId: string; readonly origin: RelayManagedEndpointOrigin; + /** + * Return a ready tunnel that already serves this origin with only a + * liveness check and a fresh token, skipping ingress and DNS repair. + */ + readonly reuseReadyTunnel?: boolean; }) => Effect.Effect; readonly reconcileOrigin: (input: { readonly userId: string; @@ -389,6 +398,93 @@ export function isManagedEndpointNotFound(cause: unknown): boolean { return "cause" in cause && isManagedEndpointNotFound(cause.cause); } +export class CloudflareApiPaused extends Schema.TaggedError()( + "CloudflareApiPaused", + { retryAfterMillis: Schema.Number }, +) { + override get message(): string { + return `Cloudflare API calls are paused for ${this.retryAfterMillis}ms after a rate limit`; + } +} + +export function isCloudflareRateLimited(cause: unknown): boolean { + if (typeof cause !== "object" || cause === null) { + return false; + } + if ( + "_tag" in cause && + (cause._tag === "TooManyRequests" || + cause._tag === "CloudflareRateLimited" || + cause._tag === "CloudflareApiPaused") + ) { + return true; + } + return "cause" in cause && isCloudflareRateLimited(cause.cause); +} + +const CLOUDFLARE_DEFAULT_RATE_LIMIT_PAUSE = Duration.seconds(30); +const CLOUDFLARE_MAX_RATE_LIMIT_PAUSE = Duration.minutes(2); + +function cloudflareRateLimitPauseMillis(cause: unknown): number { + const retryAfter = + typeof cause === "object" && cause !== null && "retryAfter" in cause + ? cause.retryAfter + : undefined; + const pause = Duration.isDuration(retryAfter) ? retryAfter : CLOUDFLARE_DEFAULT_RATE_LIMIT_PAUSE; + return Duration.toMillis(Duration.min(pause, CLOUDFLARE_MAX_RATE_LIMIT_PAUSE)); +} + +// The SDK's default policy sleeps through Retry-After inside the request, which +// held every caller until its timeout and kept the account over its limit. +// Rate limits surface at once instead; other transient failures still retry. +const withoutRateLimitRetries: CloudflareRetry.Factory = (lastError) => { + const defaults = CloudflareRetry.makeDefault(lastError); + return { + ...defaults, + while: (error) => !isCloudflareRateLimited(error) && (defaults.while?.(error) ?? false), + }; +}; + +/** + * The rate limit is account-wide, so once one call is rejected every other + * call in this isolate is too. Failing them without a request leaves the + * account room to recover instead of extending the limit. + */ +const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext) => { + let pausedUntilMillis = 0; + return ( + call: Effect.Effect, + ): Effect.Effect => + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + if (now < pausedUntilMillis) { + return yield* new CloudflareApiPaused({ retryAfterMillis: pausedUntilMillis - now }); + } + return yield* call.pipe( + Effect.provideService(CloudflareRetry.Retry, withoutRateLimitRetries), + Effect.timeout("8 seconds"), + Effect.tapError((cause) => + isCloudflareRateLimited(cause) + ? Clock.currentTimeMillis.pipe( + Effect.tap((failedAt) => + Effect.sync(() => { + pausedUntilMillis = Math.max( + pausedUntilMillis, + failedAt + cloudflareRateLimitPauseMillis(cause), + ); + }), + ), + Effect.andThen( + Effect.annotateCurrentSpan({ "relay.cloudflare.rate_limited": true }), + ), + ) + : Effect.void, + ), + Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), + ); + }); +}; + /** * Cloudflare refuses to delete a tunnel while a connector is still attached, * either one that has not finished draining or another runtime still serving @@ -503,6 +599,65 @@ export const make = Effect.gen(function* () { ); }); + // Hosts ask for recovery whenever their connector cannot register, mostly + // for local reasons a fresh provision cannot fix. Those requests outnumber + // every other Cloudflare caller, so a tunnel that is ready for the same + // origin costs two reads instead of a full provision. + const reuseReadyTunnel = Effect.fnUntraced(function* ( + allocation: ManagedEndpointAllocations.ManagedEndpointAllocation, + origin: RelayManagedEndpointOrigin, + ) { + const { tunnelId } = allocation; + if ( + tunnelId === null || + allocation.readyAt === null || + allocation.dnsRecordId === null || + allocation.tunnelReleasedAt !== null || + allocation.origin?.localHttpHost !== origin.localHttpHost || + allocation.origin.localHttpPort !== origin.localHttpPort + ) { + return Option.none(); + } + const failed = ( + stage: "verify-tunnel" | "get-tunnel-token", + cause: ManagedEndpointTunnelClientError, + ) => + new ManagedEndpointProvisioningFailed({ + userId: allocation.userId, + environmentId: allocation.environmentId, + stage, + hostname: allocation.hostname, + tunnelName: allocation.tunnelName, + tunnelId, + cause, + }); + const recorded = yield* tunnels.get(tunnelId).pipe( + Effect.asSome, + Effect.catchTags({ + ManagedEndpointTunnelClientError: (cause) => + isManagedEndpointNotFound(cause.cause) + ? Effect.succeedNone + : Effect.fail(failed("verify-tunnel", cause)), + }), + ); + if (Option.isNone(recorded) || recorded.value.deletedAt) { + return Option.none(); + } + const connectorToken = yield* tunnels + .getToken(tunnelId) + .pipe(Effect.mapError((cause) => failed("get-tunnel-token", cause))); + yield* Effect.annotateCurrentSpan({ "relay.managed_endpoint.reused_ready_tunnel": true }); + return Option.some({ + endpoint: managedEndpointForHostname(allocation.hostname), + runtime: { + providerKind: "cloudflare_tunnel", + connectorToken, + tunnelId, + tunnelName: allocation.tunnelName, + }, + }); + }); + const prepareDeprovision = Effect.fn("relay.managed_endpoint_provider.prepare_deprovision")( function* (input: { readonly userId: string; readonly environmentId: string }) { return yield* allocations.get(input).pipe( @@ -1039,6 +1194,13 @@ export const make = Effect.gen(function* () { ); const { hostname, tunnelName } = allocation; + if (input.reuseReadyTunnel === true) { + const reused = yield* reuseReadyTunnel(allocation, input.origin); + if (Option.isSome(reused)) { + return reused.value; + } + } + const tunnelResponse = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe( Effect.map((tunnels) => tunnels.result), Effect.map(Arr.findFirst((tunnel) => tunnel.name === tunnelName)), @@ -1344,14 +1506,14 @@ export const layerCloudflareBindings = ( tunnelClient: Cloudflare.Tunnel.ReadWriteTunnelClient, dnsClient: Cloudflare.DNS.ReadWriteDnsClient, alchemyRuntimeContext: Alchemy.BaseRuntimeContext, -) => - layer.pipe( +) => { + const cloudflare = makeCloudflareApiGate(alchemyRuntimeContext); + return layer.pipe( Layer.provideMerge( Layer.mergeAll( layerTunnelClient({ get: (tunnelId) => - tunnelClient.get(tunnelId).pipe( - Effect.timeout("8 seconds"), + cloudflare(tunnelClient.get(tunnelId)).pipe( Effect.mapError( (cause) => new ManagedEndpointTunnelClientError({ @@ -1360,11 +1522,9 @@ export const layerCloudflareBindings = ( cause, }), ), - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), list: (request) => - tunnelClient.list(request).pipe( - Effect.timeout("8 seconds"), + cloudflare(tunnelClient.list(request)).pipe( Effect.mapError( (cause) => new ManagedEndpointTunnelClientError({ @@ -1373,11 +1533,9 @@ export const layerCloudflareBindings = ( cause, }), ), - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), create: (request) => - tunnelClient.create(request).pipe( - Effect.timeout("8 seconds"), + cloudflare(tunnelClient.create(request)).pipe( Effect.mapError( (cause) => new ManagedEndpointTunnelClientError({ @@ -1386,11 +1544,9 @@ export const layerCloudflareBindings = ( cause, }), ), - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), putConfiguration: (tunnelId, config) => - tunnelClient.putConfiguration(tunnelId, config).pipe( - Effect.timeout("8 seconds"), + cloudflare(tunnelClient.putConfiguration(tunnelId, config)).pipe( Effect.mapError( (cause) => new ManagedEndpointTunnelClientError({ @@ -1399,11 +1555,9 @@ export const layerCloudflareBindings = ( cause, }), ), - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), getToken: (tunnelId) => - tunnelClient.getToken(tunnelId).pipe( - Effect.timeout("8 seconds"), + cloudflare(tunnelClient.getToken(tunnelId)).pipe( Effect.mapError( (cause) => new ManagedEndpointTunnelClientError({ @@ -1412,11 +1566,9 @@ export const layerCloudflareBindings = ( cause, }), ), - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), delete: (tunnelId) => - tunnelClient.delete(tunnelId).pipe( - Effect.timeout("8 seconds"), + cloudflare(tunnelClient.delete(tunnelId)).pipe( Effect.mapError( (cause) => new ManagedEndpointTunnelClientError({ @@ -1425,13 +1577,11 @@ export const layerCloudflareBindings = ( cause, }), ), - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), }), layerDnsClient({ listRecords: (hostname) => - dnsClient.listDnsRecords({ search: hostname }).pipe( - Effect.timeout("8 seconds"), + cloudflare(dnsClient.listDnsRecords({ search: hostname })).pipe( Effect.map((response) => response.result.filter( (record): record is typeof record & { readonly id: string } => @@ -1447,11 +1597,9 @@ export const layerCloudflareBindings = ( cause, }), ), - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), createRecord: (request) => - dnsClient.createDnsRecord(request).pipe( - Effect.timeout("8 seconds"), + cloudflare(dnsClient.createDnsRecord(request)).pipe( Effect.map((response) => ({ id: response.id })), Effect.mapError( (cause) => @@ -1461,11 +1609,9 @@ export const layerCloudflareBindings = ( cause, }), ), - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), updateRecord: (dnsRecordId, request) => - dnsClient.updateDnsRecord(dnsRecordId, request).pipe( - Effect.timeout("8 seconds"), + cloudflare(dnsClient.updateDnsRecord(dnsRecordId, request)).pipe( Effect.mapError( (cause) => new ManagedEndpointDnsClientError({ @@ -1475,11 +1621,9 @@ export const layerCloudflareBindings = ( cause, }), ), - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), deleteRecord: (dnsRecordId) => - dnsClient.deleteDnsRecord(dnsRecordId).pipe( - Effect.timeout("8 seconds"), + cloudflare(dnsClient.deleteDnsRecord(dnsRecordId)).pipe( Effect.mapError( (cause) => new ManagedEndpointDnsClientError({ @@ -1488,9 +1632,9 @@ export const layerCloudflareBindings = ( cause, }), ), - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), }), ), ), ); +}; diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index 1db129ab834b8..d885310e58afd 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -676,6 +676,7 @@ export const recoverEnvironmentTunnelRecord = Effect.fn( userId: input.userId, environmentId: input.environmentId, origin: input.origin, + reuseReadyTunnel: true, }); const recoveredTunnelId = recovered.runtime.tunnelId; if ( diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index feb2eca59aac0..74ed76a303116 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1058,6 +1058,9 @@ importers: '@clerk/backend': specifier: 3.25.0 version: 3.25.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@distilled.cloud/cloudflare': + specifier: 1.0.0-rc.13 + version: 1.0.0-rc.13(effect@4.0.5) '@effect/sql-pg': specifier: 4.0.5 version: 4.0.5(effect@4.0.5) From 52dfd4a6b841161c329ee974537c56407cd0fcf4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 18:31:57 -0700 Subject: [PATCH 2/9] fix(relay): share the Cloudflare rate-limit pause across Worker isolates The pause added for #16810 lived in each isolate, so every isolate had to hit a 429 itself before it backed off, and hundreds of them could keep the account at its limit. A 429 now records the pause in Postgres (relay_upstream_api_pauses), and each isolate rereads it at most every 5 s before calling Cloudflare. Reads and writes fail open. Refs #16810 Co-Authored-By: Claude Opus 5.5 --- .../migration.sql | 4 + .../snapshot.json | 1634 +++++++++++++++++ .../src/environments/CloudflareApiPause.ts | 63 + .../ManagedEndpointProvider.test.ts | 69 +- .../environments/ManagedEndpointProvider.ts | 320 ++-- infra/relay/src/persistence/schema.ts | 8 + infra/relay/src/worker.ts | 2 + 7 files changed, 1921 insertions(+), 179 deletions(-) create mode 100644 infra/relay/migrations/postgres/20261020013101_upstream_api_pauses/migration.sql create mode 100644 infra/relay/migrations/postgres/20261020013101_upstream_api_pauses/snapshot.json create mode 100644 infra/relay/src/environments/CloudflareApiPause.ts diff --git a/infra/relay/migrations/postgres/20261020013101_upstream_api_pauses/migration.sql b/infra/relay/migrations/postgres/20261020013101_upstream_api_pauses/migration.sql new file mode 100644 index 0000000000000..175f886bd3c16 --- /dev/null +++ b/infra/relay/migrations/postgres/20261020013101_upstream_api_pauses/migration.sql @@ -0,0 +1,4 @@ +CREATE TABLE "relay_upstream_api_pauses" ( + "api" varchar(64) PRIMARY KEY, + "paused_until_ms" bigint NOT NULL +); diff --git a/infra/relay/migrations/postgres/20261020013101_upstream_api_pauses/snapshot.json b/infra/relay/migrations/postgres/20261020013101_upstream_api_pauses/snapshot.json new file mode 100644 index 0000000000000..84acbfa6fd44e --- /dev/null +++ b/infra/relay/migrations/postgres/20261020013101_upstream_api_pauses/snapshot.json @@ -0,0 +1,1634 @@ +{ + "version": "8", + "dialect": "postgres", + "id": "f8594baa-6f4a-4a0d-a7f0-0aa717dfe785", + "prevIds": ["7b10c420-1566-4dfc-8e9c-c73efa561d3b"], + "ddl": [ + { + "isRlsEnabled": false, + "name": "relay_agent_activity_rows", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_delivery_attempts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_dpop_proofs", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_credentials", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_links", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_live_activities", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_managed_endpoint_allocations", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_managed_tunnel_limits", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_mobile_devices", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_upstream_api_pauses", + "entityType": "tables", + "schema": "public" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(512)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "state_json", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(36)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(512)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "kind", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "source_job_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "token_suffix", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_status", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_reason", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "transport_error", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thumbprint", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "jti", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iat", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_hash", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'T3 Environment'", + "generated": null, + "identity": null, + "name": "environment_label", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_http_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_ws_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(32)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_provider_kind", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "notifications_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "live_activities_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "managed_tunnels_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "hold_webhooks_while_offline", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_by_device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_start_queued_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_started_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ended_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_aggregate_json", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_live_activity_delivery_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "hostname", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "tunnel_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "tunnel_name", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "dns_record_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ready_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "recovery_enabled_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "recovery_environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "tunnel_released_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "origin", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "0", + "generated": null, + "identity": null, + "name": "generation", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_tunnel_limits" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "max_tunnels", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_tunnel_limits" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_tunnel_limits" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_tunnel_limits" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'iOS device'", + "generated": null, + "identity": null, + "name": "label", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "platform", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ios_major_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "android_api_level", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "app_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "bundle_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "aps_environment", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_to_start_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "preferences_json", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "api", + "entityType": "columns", + "schema": "public", + "table": "relay_upstream_api_pauses" + }, + { + "type": "bigint", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "paused_until_ms", + "entityType": "columns", + "schema": "public", + "table": "relay_upstream_api_pauses" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "updated_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_agent_activity_rows_updated", + "entityType": "indexes", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "thread_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "created_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "source_job_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_source_job", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "expires_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_dpop_proofs_expires_at", + "entityType": "indexes", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "credential_hash", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_hash", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "environment_public_key", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_environment_key", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_links_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_links" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "activity_push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_live_activities_activity_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_live_activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "hostname", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_managed_endpoint_allocations_hostname", + "entityType": "indexes", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "tunnel_name", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_managed_endpoint_allocations_tunnel_name", + "entityType": "indexes", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_to_start_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_to_start_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["environment_id", "environment_public_key", "thread_id"], + "nameExplicit": false, + "name": "relay_agent_activity_rows_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "columns": ["thumbprint", "jti"], + "nameExplicit": false, + "name": "relay_dpop_proofs_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "columns": ["user_id", "environment_id"], + "nameExplicit": false, + "name": "relay_environment_links_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_environment_links" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_live_activities_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_live_activities" + }, + { + "columns": ["user_id", "environment_id"], + "nameExplicit": false, + "name": "relay_managed_endpoint_allocations_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_mobile_devices_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "relay_delivery_attempts_pkey", + "schema": "public", + "table": "relay_delivery_attempts", + "entityType": "pks" + }, + { + "columns": ["credential_id"], + "nameExplicit": false, + "name": "relay_environment_credentials_pkey", + "schema": "public", + "table": "relay_environment_credentials", + "entityType": "pks" + }, + { + "columns": ["user_id"], + "nameExplicit": false, + "name": "relay_managed_tunnel_limits_pkey", + "schema": "public", + "table": "relay_managed_tunnel_limits", + "entityType": "pks" + }, + { + "columns": ["api"], + "nameExplicit": false, + "name": "relay_upstream_api_pauses_pkey", + "schema": "public", + "table": "relay_upstream_api_pauses", + "entityType": "pks" + } + ], + "renames": [] +} diff --git a/infra/relay/src/environments/CloudflareApiPause.ts b/infra/relay/src/environments/CloudflareApiPause.ts new file mode 100644 index 0000000000000..6114801353e4e --- /dev/null +++ b/infra/relay/src/environments/CloudflareApiPause.ts @@ -0,0 +1,63 @@ +import { eq, sql } from "drizzle-orm"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as RelayDb from "../db.ts"; +import { relayUpstreamApiPauses } from "../persistence/schema.ts"; + +const CLOUDFLARE_API = "cloudflare"; + +/** + * Cloudflare's API rate limit is per account, so a 429 seen by any isolate + * applies to all of them. Both operations fail open: a pause that cannot be + * read or recorded must not block provisioning. + */ +export class CloudflareApiPause extends Context.Service< + CloudflareApiPause, + { + /** Epoch milliseconds until which calls are paused, or 0. */ + readonly pausedUntilMillis: Effect.Effect; + readonly pauseUntil: (untilMillis: number) => Effect.Effect; + } +>()("t3code-relay/environments/CloudflareApiPause") {} + +export const make = Effect.gen(function* () { + const db = yield* RelayDb.RelayDb; + + return CloudflareApiPause.of({ + pausedUntilMillis: db + .select({ pausedUntilMs: relayUpstreamApiPauses.pausedUntilMs }) + .from(relayUpstreamApiPauses) + .where(eq(relayUpstreamApiPauses.api, CLOUDFLARE_API)) + .limit(1) + .pipe( + Effect.map((rows) => rows[0]?.pausedUntilMs ?? 0), + Effect.catch((cause) => + Effect.logWarning("Could not read the shared Cloudflare API pause", { cause }).pipe( + Effect.as(0), + ), + ), + Effect.withSpan("relay.cloudflare_api_pause.read"), + ), + pauseUntil: (untilMillis) => + db + .insert(relayUpstreamApiPauses) + .values({ api: CLOUDFLARE_API, pausedUntilMs: untilMillis }) + .onConflictDoUpdate({ + target: relayUpstreamApiPauses.api, + set: { + pausedUntilMs: sql`greatest(${relayUpstreamApiPauses.pausedUntilMs}, excluded.paused_until_ms)`, + }, + }) + .pipe( + Effect.asVoid, + Effect.catch((cause) => + Effect.logWarning("Could not record the shared Cloudflare API pause", { cause }), + ), + Effect.withSpan("relay.cloudflare_api_pause.record"), + ), + }); +}); + +export const layer = Layer.effect(CloudflareApiPause, make); diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index 04ba2b48c920c..704a43fbd602b 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -9,6 +9,7 @@ import * as Redacted from "effect/Redacted"; import * as TestClock from "effect/testing/TestClock"; import * as RelayConfiguration from "../Config.ts"; +import * as CloudflareApiPause from "./CloudflareApiPause.ts"; import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts"; import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts"; import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts"; @@ -365,6 +366,17 @@ function layerProvider( ); } +function makeSharedCloudflareApiPause() { + let pausedUntilMillis = 0; + return CloudflareApiPause.CloudflareApiPause.of({ + pausedUntilMillis: Effect.sync(() => pausedUntilMillis), + pauseUntil: (untilMillis) => + Effect.sync(() => { + pausedUntilMillis = Math.max(pausedUntilMillis, untilMillis); + }), + }); +} + const MANAGED_ENDPOINT_HASHES: Record = { "user_ABC:env_ABC": "d101ac68108a423e", "user_ABC:env_shared": "d7e6356aaf8863aa", @@ -414,6 +426,9 @@ describe("ManagedEndpointProvider", () => { Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()), ), Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())), + Layer.provide( + Layer.succeed(CloudflareApiPause.CloudflareApiPause, makeSharedCloudflareApiPause()), + ), ); return Effect.gen(function* () { @@ -828,7 +843,7 @@ describe("ManagedEndpointProvider", () => { }).pipe(Effect.provide(layer)); }); - it.effect("stops calling Cloudflare until a rate limit has passed", () => { + it.effect("pauses Cloudflare calls in every isolate until a rate limit has passed", () => { let listCalls = 0; const tunnelClient = { list: () => @@ -837,43 +852,47 @@ describe("ManagedEndpointProvider", () => { return Effect.fail({ _tag: "TooManyRequests", message: "Rate limited" }); }), } as unknown as Cloudflare.Tunnel.ReadWriteTunnelClient; - const layer = ManagedEndpointProvider.layerCloudflareBindings( - tunnelClient, - {} as Cloudflare.DNS.ReadWriteDnsClient, - {} as Alchemy.BaseRuntimeContext, - ).pipe( - Layer.provideMerge(NodeServices.layer), - Layer.provide(RelayConfiguration.layer(config)), - Layer.provide( - Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()), - ), - Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())), - ); - - return Effect.gen(function* () { - const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; - const provision = provider - .provision({ + const sharedPause = makeSharedCloudflareApiPause(); + const isolate = () => + ManagedEndpointProvider.layerCloudflareBindings( + tunnelClient, + {} as Cloudflare.DNS.ReadWriteDnsClient, + {} as Alchemy.BaseRuntimeContext, + ).pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(RelayConfiguration.layer(config)), + Layer.provide( + Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()), + ), + Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())), + Layer.provide(Layer.succeed(CloudflareApiPause.CloudflareApiPause, sharedPause)), + ); + const provision = ManagedEndpointProvider.ManagedEndpointProvider.pipe( + Effect.flatMap((provider) => + provider.provision({ userId: "user_ABC", environmentId: "env_ABC", origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, - }) - .pipe(Effect.flip); + }), + ), + Effect.flip, + ); - const rateLimited = yield* provision; - const paused = yield* provision; + return Effect.gen(function* () { + const rateLimited = yield* provision.pipe(Effect.provide(isolate())); + const pausedElsewhere = yield* provision.pipe(Effect.provide(isolate())); expect(listCalls).toBe(1); expect(ManagedEndpointProvider.isCloudflareRateLimited(rateLimited)).toBe(true); - expect(paused).toMatchObject({ + expect(pausedElsewhere).toMatchObject({ _tag: "ManagedEndpointProvisioningFailed", stage: "ensure-tunnel", cause: { cause: { _tag: "CloudflareApiPaused" } }, }); yield* TestClock.adjust("30 seconds"); - yield* provision; + yield* provision.pipe(Effect.provide(isolate())); expect(listCalls).toBe(2); - }).pipe(Effect.provide(layer)); + }); }); it.effect("recreates a checkpointed DNS record when it was removed externally", () => { diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 659050ce469be..4f1af5286702b 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -27,6 +27,7 @@ import { managedEndpointHostname, managedEndpointTunnelName, } from "../deploymentConfig.ts"; +import * as CloudflareApiPause from "./CloudflareApiPause.ts"; import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts"; import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts"; @@ -445,44 +446,48 @@ const withoutRateLimitRetries: CloudflareRetry.Factory = (lastError) => { }; }; +// Every isolate rereads the shared pause at most this often, so a quiet +// period costs one query per isolate rather than one per Cloudflare call. +const CLOUDFLARE_PAUSE_REFRESH_MILLIS = 5_000; + /** * The rate limit is account-wide, so once one call is rejected every other - * call in this isolate is too. Failing them without a request leaves the + * call is too, from any isolate. Failing them without a request leaves the * account room to recover instead of extending the limit. */ const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext) => { let pausedUntilMillis = 0; - return ( - call: Effect.Effect, - ): Effect.Effect => - Effect.gen(function* () { - const now = yield* Clock.currentTimeMillis; - if (now < pausedUntilMillis) { - return yield* new CloudflareApiPaused({ retryAfterMillis: pausedUntilMillis - now }); - } - return yield* call.pipe( - Effect.provideService(CloudflareRetry.Retry, withoutRateLimitRetries), - Effect.timeout("8 seconds"), - Effect.tapError((cause) => - isCloudflareRateLimited(cause) - ? Clock.currentTimeMillis.pipe( - Effect.tap((failedAt) => - Effect.sync(() => { - pausedUntilMillis = Math.max( - pausedUntilMillis, - failedAt + cloudflareRateLimitPauseMillis(cause), - ); - }), - ), - Effect.andThen( - Effect.annotateCurrentSpan({ "relay.cloudflare.rate_limited": true }), - ), - ) - : Effect.void, - ), - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), - ); - }); + let checkedAtMillis = Number.NEGATIVE_INFINITY; + return (pause: CloudflareApiPause.CloudflareApiPause["Service"]) => { + const recordRateLimit = (cause: unknown) => + Effect.gen(function* () { + const until = (yield* Clock.currentTimeMillis) + cloudflareRateLimitPauseMillis(cause); + pausedUntilMillis = Math.max(pausedUntilMillis, until); + yield* Effect.annotateCurrentSpan({ "relay.cloudflare.rate_limited": true }); + yield* pause.pauseUntil(until); + }); + return ( + call: Effect.Effect, + ): Effect.Effect => + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + if (now >= pausedUntilMillis && now - checkedAtMillis >= CLOUDFLARE_PAUSE_REFRESH_MILLIS) { + checkedAtMillis = now; + pausedUntilMillis = Math.max(pausedUntilMillis, yield* pause.pausedUntilMillis); + } + if (now < pausedUntilMillis) { + return yield* new CloudflareApiPaused({ retryAfterMillis: pausedUntilMillis - now }); + } + return yield* call.pipe( + Effect.provideService(CloudflareRetry.Retry, withoutRateLimitRetries), + Effect.timeout("8 seconds"), + Effect.tapError((cause) => + isCloudflareRateLimited(cause) ? recordRateLimit(cause) : Effect.void, + ), + Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), + ); + }); + }; }; /** @@ -1507,132 +1512,139 @@ export const layerCloudflareBindings = ( dnsClient: Cloudflare.DNS.ReadWriteDnsClient, alchemyRuntimeContext: Alchemy.BaseRuntimeContext, ) => { + // Created once per isolate so its cached pause survives layer rebuilds. const cloudflare = makeCloudflareApiGate(alchemyRuntimeContext); return layer.pipe( Layer.provideMerge( - Layer.mergeAll( - layerTunnelClient({ - get: (tunnelId) => - cloudflare(tunnelClient.get(tunnelId)).pipe( - Effect.mapError( - (cause) => - new ManagedEndpointTunnelClientError({ - operation: "get", - tunnelId, - cause, - }), - ), - ), - list: (request) => - cloudflare(tunnelClient.list(request)).pipe( - Effect.mapError( - (cause) => - new ManagedEndpointTunnelClientError({ - operation: "list", - ...(request.name === undefined ? {} : { tunnelName: request.name }), - cause, - }), - ), - ), - create: (request) => - cloudflare(tunnelClient.create(request)).pipe( - Effect.mapError( - (cause) => - new ManagedEndpointTunnelClientError({ - operation: "create", - tunnelName: request.name, - cause, - }), - ), - ), - putConfiguration: (tunnelId, config) => - cloudflare(tunnelClient.putConfiguration(tunnelId, config)).pipe( - Effect.mapError( - (cause) => - new ManagedEndpointTunnelClientError({ - operation: "put-configuration", - tunnelId, - cause, - }), - ), - ), - getToken: (tunnelId) => - cloudflare(tunnelClient.getToken(tunnelId)).pipe( - Effect.mapError( - (cause) => - new ManagedEndpointTunnelClientError({ - operation: "get-token", - tunnelId, - cause, - }), - ), - ), - delete: (tunnelId) => - cloudflare(tunnelClient.delete(tunnelId)).pipe( - Effect.mapError( - (cause) => - new ManagedEndpointTunnelClientError({ - operation: "delete", - tunnelId, - cause, - }), - ), - ), - }), - layerDnsClient({ - listRecords: (hostname) => - cloudflare(dnsClient.listDnsRecords({ search: hostname })).pipe( - Effect.map((response) => - response.result.filter( - (record): record is typeof record & { readonly id: string } => - typeof record.id === "string" && - normalizeHostname(record.name) === normalizeHostname(hostname), + Layer.unwrap( + Effect.gen(function* () { + const pause = yield* CloudflareApiPause.CloudflareApiPause; + const gate = cloudflare(pause); + return Layer.mergeAll( + layerTunnelClient({ + get: (tunnelId) => + gate(tunnelClient.get(tunnelId)).pipe( + Effect.mapError( + (cause) => + new ManagedEndpointTunnelClientError({ + operation: "get", + tunnelId, + cause, + }), + ), ), - ), - Effect.mapError( - (cause) => - new ManagedEndpointDnsClientError({ - operation: "list-records", - hostname, - cause, - }), - ), - ), - createRecord: (request) => - cloudflare(dnsClient.createDnsRecord(request)).pipe( - Effect.map((response) => ({ id: response.id })), - Effect.mapError( - (cause) => - new ManagedEndpointDnsClientError({ - operation: "create-record", - hostname: request.name, - cause, - }), - ), - ), - updateRecord: (dnsRecordId, request) => - cloudflare(dnsClient.updateDnsRecord(dnsRecordId, request)).pipe( - Effect.mapError( - (cause) => - new ManagedEndpointDnsClientError({ - operation: "update-record", - hostname: request.name, - dnsRecordId, - cause, - }), - ), - ), - deleteRecord: (dnsRecordId) => - cloudflare(dnsClient.deleteDnsRecord(dnsRecordId)).pipe( - Effect.mapError( - (cause) => - new ManagedEndpointDnsClientError({ - operation: "delete-record", - dnsRecordId, - cause, - }), - ), - ), + list: (request) => + gate(tunnelClient.list(request)).pipe( + Effect.mapError( + (cause) => + new ManagedEndpointTunnelClientError({ + operation: "list", + ...(request.name === undefined ? {} : { tunnelName: request.name }), + cause, + }), + ), + ), + create: (request) => + gate(tunnelClient.create(request)).pipe( + Effect.mapError( + (cause) => + new ManagedEndpointTunnelClientError({ + operation: "create", + tunnelName: request.name, + cause, + }), + ), + ), + putConfiguration: (tunnelId, config) => + gate(tunnelClient.putConfiguration(tunnelId, config)).pipe( + Effect.mapError( + (cause) => + new ManagedEndpointTunnelClientError({ + operation: "put-configuration", + tunnelId, + cause, + }), + ), + ), + getToken: (tunnelId) => + gate(tunnelClient.getToken(tunnelId)).pipe( + Effect.mapError( + (cause) => + new ManagedEndpointTunnelClientError({ + operation: "get-token", + tunnelId, + cause, + }), + ), + ), + delete: (tunnelId) => + gate(tunnelClient.delete(tunnelId)).pipe( + Effect.mapError( + (cause) => + new ManagedEndpointTunnelClientError({ + operation: "delete", + tunnelId, + cause, + }), + ), + ), + }), + layerDnsClient({ + listRecords: (hostname) => + gate(dnsClient.listDnsRecords({ search: hostname })).pipe( + Effect.map((response) => + response.result.filter( + (record): record is typeof record & { readonly id: string } => + typeof record.id === "string" && + normalizeHostname(record.name) === normalizeHostname(hostname), + ), + ), + Effect.mapError( + (cause) => + new ManagedEndpointDnsClientError({ + operation: "list-records", + hostname, + cause, + }), + ), + ), + createRecord: (request) => + gate(dnsClient.createDnsRecord(request)).pipe( + Effect.map((response) => ({ id: response.id })), + Effect.mapError( + (cause) => + new ManagedEndpointDnsClientError({ + operation: "create-record", + hostname: request.name, + cause, + }), + ), + ), + updateRecord: (dnsRecordId, request) => + gate(dnsClient.updateDnsRecord(dnsRecordId, request)).pipe( + Effect.mapError( + (cause) => + new ManagedEndpointDnsClientError({ + operation: "update-record", + hostname: request.name, + dnsRecordId, + cause, + }), + ), + ), + deleteRecord: (dnsRecordId) => + gate(dnsClient.deleteDnsRecord(dnsRecordId)).pipe( + Effect.mapError( + (cause) => + new ManagedEndpointDnsClientError({ + operation: "delete-record", + dnsRecordId, + cause, + }), + ), + ), + }), + ); }), ), ), diff --git a/infra/relay/src/persistence/schema.ts b/infra/relay/src/persistence/schema.ts index 3ed6a75a5f6d6..132ceba16a900 100644 --- a/infra/relay/src/persistence/schema.ts +++ b/infra/relay/src/persistence/schema.ts @@ -5,6 +5,7 @@ import type { RelayManagedEndpointOrigin, } from "@t3tools/contracts/relay"; import { + bigint, boolean, index, integer, @@ -111,6 +112,13 @@ export const relayManagedEndpointAllocations = pgTable( ], ); +// One row per upstream API whose rate limit is shared by every Worker +// isolate, so a 429 seen by one isolate pauses the rest. +export const relayUpstreamApiPauses = pgTable("relay_upstream_api_pauses", { + api: varchar("api", { length: 64 }).primaryKey(), + pausedUntilMs: bigint("paused_until_ms", { mode: "number" }).notNull(), +}); + export const relayManagedTunnelLimits = pgTable("relay_managed_tunnel_limits", { userId: varchar("user_id", { length: 191 }).primaryKey(), maxTunnels: integer("max_tunnels").notNull(), diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts index 29e5359fa3f6e..c64db84b497fa 100644 --- a/infra/relay/src/worker.ts +++ b/infra/relay/src/worker.ts @@ -57,6 +57,7 @@ import * as ApnsClient from "./agentActivity/ApnsClient.ts"; import * as ApnsProviderTokens from "./agentActivity/ApnsProviderTokens.ts"; import * as ApnsDeliveryQueue from "./agentActivity/ApnsDeliveryQueue.ts"; import * as ApnsDeliveries from "./agentActivity/ApnsDeliveries.ts"; +import * as CloudflareApiPause from "./environments/CloudflareApiPause.ts"; import * as EnvironmentConnector from "./environments/EnvironmentConnector.ts"; import * as EnvironmentLinker from "./environments/EnvironmentLinker.ts"; import * as EnvironmentPublishSignatures from "./environments/EnvironmentPublishSignatures.ts"; @@ -291,6 +292,7 @@ export const layer = Api.make( Layer.provideMerge(EnvironmentCredentials.layer), Layer.provideMerge( Layer.mergeAll( + CloudflareApiPause.layer, EnvironmentLinks.layer, ManagedEndpointAllocations.layer, ManagedTunnelLimits.layer, From b77c7040daf2c19d6f86c7f5903492cfc03a9d8b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 19:54:20 -0700 Subject: [PATCH 3/9] fix(relay): the shared Cloudflare pause survives transactions; the reaper honors it Review fixes for the shared pause: - The pause was read and written with the relay's database client, which joins an ambient transaction. Ingress and DNS updates call Cloudflare inside the allocation row-lock transaction, so a 429 there rolled the recorded pause back with the transaction, and a failed pause read aborted the provision's own statements. Both now run outside any transaction. - The reaper only recognized raw 429s, so during a pause it walked every candidate. It now uses the provider's isCloudflareRateLimited, which also covers the pause and a plain 429 status. - @distilled.cloud/cloudflare moves to the workspace catalog. Co-Authored-By: Claude Opus 5.5 --- infra/relay/package.json | 2 +- .../environments/CloudflareApiPause.test.ts | 50 +++++++++++++++++++ .../src/environments/CloudflareApiPause.ts | 9 ++++ .../environments/ManagedEndpointProvider.ts | 3 ++ .../ManagedEndpointReaper.test.ts | 14 ++++-- .../src/environments/ManagedEndpointReaper.ts | 15 +----- pnpm-lock.yaml | 5 +- pnpm-workspace.yaml | 3 ++ 8 files changed, 82 insertions(+), 19 deletions(-) create mode 100644 infra/relay/src/environments/CloudflareApiPause.test.ts diff --git a/infra/relay/package.json b/infra/relay/package.json index d1cad6500b461..dd2265aafb0d5 100644 --- a/infra/relay/package.json +++ b/infra/relay/package.json @@ -13,7 +13,7 @@ }, "dependencies": { "@clerk/backend": "catalog:", - "@distilled.cloud/cloudflare": "1.0.0-rc.13", + "@distilled.cloud/cloudflare": "catalog:", "@effect/sql-pg": "catalog:", "@effect/sql-sqlite-do": "catalog:", "@noble/curves": "catalog:", diff --git a/infra/relay/src/environments/CloudflareApiPause.test.ts b/infra/relay/src/environments/CloudflareApiPause.test.ts new file mode 100644 index 0000000000000..639852f1e6ac2 --- /dev/null +++ b/infra/relay/src/environments/CloudflareApiPause.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as RelayDb from "../db.ts"; +import * as CloudflareApiPause from "./CloudflareApiPause.ts"; + +const TransactionConnection = Context.Service("test/TransactionConnection"); + +// Records whether each statement would have joined the ambient transaction. +function makeFakeDb(joinedTransaction: Array) { + const statement = (result: A) => + Effect.serviceOption(TransactionConnection).pipe( + Effect.tap((connection) => + Effect.sync(() => joinedTransaction.push(Option.isSome(connection))), + ), + Effect.as(result), + ); + return { + $client: { transactionService: TransactionConnection }, + select: () => ({ + from: () => ({ where: () => ({ limit: () => statement([{ pausedUntilMs: 42 }]) }) }), + }), + insert: () => ({ values: () => ({ onConflictDoUpdate: () => statement([]) }) }), + } as unknown as RelayDb.RelayDb["Service"]; +} + +describe("CloudflareApiPause", () => { + it.effect("reads and records the pause outside a surrounding transaction", () => { + const joinedTransaction: Array = []; + return Effect.gen(function* () { + const pause = yield* CloudflareApiPause.CloudflareApiPause; + const inTransaction = (effect: Effect.Effect) => + effect.pipe(Effect.provideService(TransactionConnection, "transaction-connection")); + + expect(yield* inTransaction(pause.pausedUntilMillis)).toBe(42); + yield* inTransaction(pause.pauseUntil(1_000)); + + expect(joinedTransaction).toEqual([false, false]); + }).pipe( + Effect.provide( + CloudflareApiPause.layer.pipe( + Layer.provide(Layer.succeed(RelayDb.RelayDb, makeFakeDb(joinedTransaction))), + ), + ), + ); + }); +}); diff --git a/infra/relay/src/environments/CloudflareApiPause.ts b/infra/relay/src/environments/CloudflareApiPause.ts index 6114801353e4e..47390fbf06ed2 100644 --- a/infra/relay/src/environments/CloudflareApiPause.ts +++ b/infra/relay/src/environments/CloudflareApiPause.ts @@ -12,6 +12,11 @@ const CLOUDFLARE_API = "cloudflare"; * Cloudflare's API rate limit is per account, so a 429 seen by any isolate * applies to all of them. Both operations fail open: a pause that cannot be * read or recorded must not block provisioning. + * + * Both also run outside any ambient transaction. Provisioning calls Cloudflare + * while holding an allocation row lock, and a 429 there rolls that transaction + * back, which would drop the recorded pause; a failed read inside it would + * abort the provision's own statements. */ export class CloudflareApiPause extends Context.Service< CloudflareApiPause, @@ -24,6 +29,8 @@ export class CloudflareApiPause extends Context.Service< export const make = Effect.gen(function* () { const db = yield* RelayDb.RelayDb; + const outsideTransaction = (effect: Effect.Effect) => + Effect.updateContext(effect, Context.omit(db.$client.transactionService)); return CloudflareApiPause.of({ pausedUntilMillis: db @@ -38,6 +45,7 @@ export const make = Effect.gen(function* () { Effect.as(0), ), ), + outsideTransaction, Effect.withSpan("relay.cloudflare_api_pause.read"), ), pauseUntil: (untilMillis) => @@ -55,6 +63,7 @@ export const make = Effect.gen(function* () { Effect.catch((cause) => Effect.logWarning("Could not record the shared Cloudflare API pause", { cause }), ), + outsideTransaction, Effect.withSpan("relay.cloudflare_api_pause.record"), ), }); diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 4f1af5286702b..4a6a91f0221f9 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -420,6 +420,9 @@ export function isCloudflareRateLimited(cause: unknown): boolean { ) { return true; } + if ("status" in cause && cause.status === 429) { + return true; + } return "cause" in cause && isCloudflareRateLimited(cause.cause); } diff --git a/infra/relay/src/environments/ManagedEndpointReaper.test.ts b/infra/relay/src/environments/ManagedEndpointReaper.test.ts index 252b468e7cc79..26ce55a58a738 100644 --- a/infra/relay/src/environments/ManagedEndpointReaper.test.ts +++ b/infra/relay/src/environments/ManagedEndpointReaper.test.ts @@ -66,6 +66,7 @@ function harness(input?: { readonly namespace?: string; readonly failTunnelId?: string; readonly rateLimitedTunnelId?: string; + readonly rateLimitCause?: unknown; readonly failAllDeletes?: boolean; readonly failDeleteWhen?: (tunnelId: string) => boolean; readonly missingOnDeleteTunnelId?: string; @@ -155,13 +156,13 @@ function harness(input?: { tunnelId === input?.missingOnDeleteTunnelId ? { _tag: "NotFound" } : tunnelId === input?.rateLimitedTunnelId - ? { + ? (input.rateLimitCause ?? { cause: { _tag: "TooManyRequests", message: "Cloudflare rate limit exceeded", retryAfter: 60, }, - } + }) : "Cloudflare refused the deletion", }), ) @@ -653,7 +654,13 @@ describe("ManagedEndpointReaper", () => { }).pipe(Effect.provide(state.layer)); }); - it.effect("stops the sweep after a structured Cloudflare rate limit error", () => { + it.effect.each([ + ["a structured Cloudflare rate limit error", undefined], + [ + "a Cloudflare API pause recorded by another isolate", + new ManagedEndpointProvider.CloudflareApiPaused({ retryAfterMillis: 30_000 }), + ], + ] as const)("stops the sweep after %s", ([, rateLimitCause]) => { const state = harness({ tunnels: [ tunnel({ @@ -674,6 +681,7 @@ describe("ManagedEndpointReaper", () => { allocation({ tunnelId: "next", recoveryEnabled: true }), ], rateLimitedTunnelId: "limited", + rateLimitCause, }); return Effect.gen(function* () { diff --git a/infra/relay/src/environments/ManagedEndpointReaper.ts b/infra/relay/src/environments/ManagedEndpointReaper.ts index 27c3574ff47a1..cbaf63577e739 100644 --- a/infra/relay/src/environments/ManagedEndpointReaper.ts +++ b/infra/relay/src/environments/ManagedEndpointReaper.ts @@ -110,19 +110,6 @@ function inactiveDaysAt( return (now.epochMilliseconds - timestamp.value.epochMilliseconds) / 86_400_000; } -function isRateLimited(cause: unknown): boolean { - if (typeof cause !== "object" || cause === null) { - return false; - } - if ("_tag" in cause && cause._tag === "TooManyRequests") { - return true; - } - if ("status" in cause && cause.status === 429) { - return true; - } - return "cause" in cause && isRateLimited(cause.cause); -} - function rotatedPages(input: { readonly totalCount: number | undefined; readonly slot: number; @@ -383,7 +370,7 @@ export const make = Effect.gen(function* () { legacy: candidate.legacy, cause: result.failure, }); - if (isRateLimited(result.failure)) { + if (ManagedEndpointProvider.isCloudflareRateLimited(result.failure)) { stopDeleting = true; truncated = true; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 74ed76a303116..83ef28805b05f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,6 +6,9 @@ settings: catalogs: default: + '@distilled.cloud/cloudflare': + specifier: 1.0.0-rc.13 + version: 1.0.0-rc.13 '@effect/graphql-generator': specifier: 4.0.5 version: 4.0.5 @@ -1059,7 +1062,7 @@ importers: specifier: 3.25.0 version: 3.25.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@distilled.cloud/cloudflare': - specifier: 1.0.0-rc.13 + specifier: 'catalog:' version: 1.0.0-rc.13(effect@4.0.5) '@effect/sql-pg': specifier: 4.0.5 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 5800efc6c6474..2bc8c09efa9b0 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -34,6 +34,9 @@ catalog: "@clerk/expo": 4.13.0 "@clerk/react": 6.17.8 "@clerk/shared": 4.40.0 + # Must match the version alchemy depends on: the relay overrides its + # Cloudflare retry policy through this package's Retry service. + "@distilled.cloud/cloudflare": 1.0.0-rc.13 "@effect/atom-react": 4.0.5 "@effect/graphql-generator": 4.0.5 "@effect/openapi-generator": 4.0.5 From 8a5a1adfb648528ccb6e8af636c6e9b001c7da73 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 20:02:39 -0700 Subject: [PATCH 4/9] fix(relay): the Cloudflare pause really leaves the transaction The previous fix omitted `db.$client.transactionService`, but in the Worker `db` is alchemy's lazy Drizzle proxy: that property is another proxy, not the real context key, so nothing was removed and the pause queries still joined the allocation lock transaction. Drop SqlClient transaction keys by name instead. The test now uses the real SqlClient key and a proxied `$client`, and fails against the previous fix. Co-Authored-By: Claude Opus 5.5 --- .../src/environments/CloudflareApiPause.test.ts | 17 +++++++++++++---- .../src/environments/CloudflareApiPause.ts | 15 ++++++++++++++- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/infra/relay/src/environments/CloudflareApiPause.test.ts b/infra/relay/src/environments/CloudflareApiPause.test.ts index 639852f1e6ac2..c844a679c106a 100644 --- a/infra/relay/src/environments/CloudflareApiPause.test.ts +++ b/infra/relay/src/environments/CloudflareApiPause.test.ts @@ -1,13 +1,17 @@ import { describe, expect, it } from "@effect/vitest"; -import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as SqlClient from "effect/sql/SqlClient"; import * as RelayDb from "../db.ts"; import * as CloudflareApiPause from "./CloudflareApiPause.ts"; -const TransactionConnection = Context.Service("test/TransactionConnection"); +const TransactionConnection = SqlClient.TransactionConnection(7); + +// Like the Worker's alchemy database proxy: every property read returns +// another proxy, never the client's real transaction key. +const lazyProxy = (): unknown => new Proxy(() => {}, { get: () => lazyProxy() }); // Records whether each statement would have joined the ambient transaction. function makeFakeDb(joinedTransaction: Array) { @@ -19,7 +23,7 @@ function makeFakeDb(joinedTransaction: Array) { Effect.as(result), ); return { - $client: { transactionService: TransactionConnection }, + $client: lazyProxy(), select: () => ({ from: () => ({ where: () => ({ limit: () => statement([{ pausedUntilMs: 42 }]) }) }), }), @@ -33,7 +37,12 @@ describe("CloudflareApiPause", () => { return Effect.gen(function* () { const pause = yield* CloudflareApiPause.CloudflareApiPause; const inTransaction = (effect: Effect.Effect) => - effect.pipe(Effect.provideService(TransactionConnection, "transaction-connection")); + effect.pipe( + Effect.provideService(TransactionConnection, [ + {} as never, + 0, + ] as unknown as SqlClient.TransactionConnection.Service), + ); expect(yield* inTransaction(pause.pausedUntilMillis)).toBe(42); yield* inTransaction(pause.pauseUntil(1_000)); diff --git a/infra/relay/src/environments/CloudflareApiPause.ts b/infra/relay/src/environments/CloudflareApiPause.ts index 47390fbf06ed2..00a076e4d6219 100644 --- a/infra/relay/src/environments/CloudflareApiPause.ts +++ b/infra/relay/src/environments/CloudflareApiPause.ts @@ -8,6 +8,19 @@ import { relayUpstreamApiPauses } from "../persistence/schema.ts"; const CLOUDFLARE_API = "cloudflare"; +// Every SqlClient's transaction connection lives under a key with this prefix. +// Matching by key name instead of `db.$client.transactionService` because the +// relay's database is an alchemy proxy, whose properties are proxies too, not +// the real key. +const SQL_TRANSACTION_KEY_PREFIX = "effect/sql/SqlClient/TransactionConnection/"; + +const withoutSqlTransaction = (context: Context.Context): Context.Context => + Context.makeUnsafe( + new Map( + Array.from(context.mapUnsafe).filter(([key]) => !key.startsWith(SQL_TRANSACTION_KEY_PREFIX)), + ), + ); + /** * Cloudflare's API rate limit is per account, so a 429 seen by any isolate * applies to all of them. Both operations fail open: a pause that cannot be @@ -30,7 +43,7 @@ export class CloudflareApiPause extends Context.Service< export const make = Effect.gen(function* () { const db = yield* RelayDb.RelayDb; const outsideTransaction = (effect: Effect.Effect) => - Effect.updateContext(effect, Context.omit(db.$client.transactionService)); + Effect.updateContext(effect, withoutSqlTransaction); return CloudflareApiPause.of({ pausedUntilMillis: db From 4b835201068d0e696462d6f0898391e5a3389bd7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 20:04:16 -0700 Subject: [PATCH 5/9] fix(relay): keep Cloudflare rate-limit storms visible while calls are paused A paused call never reaches Cloudflare, so a storm the pause is holding back produced almost no 429 spans and the rate-limit monitors would go quiet. Paused calls now fail inside a relay.cloudflare_api_pause.rejected span, and both Cloudflare monitors count those alongside 429s. The span that records a pause also carries relay.cloudflare.pause_ms, so the real Retry-After windows can be checked against the 2 minute cap. Co-Authored-By: Claude Opus 5.5 --- .../src/environments/ManagedEndpointProvider.ts | 14 +++++++++++--- infra/relay/src/monitoring.ts | 8 ++++---- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 4a6a91f0221f9..1e912ac790fec 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -464,9 +464,13 @@ const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext return (pause: CloudflareApiPause.CloudflareApiPause["Service"]) => { const recordRateLimit = (cause: unknown) => Effect.gen(function* () { - const until = (yield* Clock.currentTimeMillis) + cloudflareRateLimitPauseMillis(cause); + const pauseMillis = cloudflareRateLimitPauseMillis(cause); + const until = (yield* Clock.currentTimeMillis) + pauseMillis; pausedUntilMillis = Math.max(pausedUntilMillis, until); - yield* Effect.annotateCurrentSpan({ "relay.cloudflare.rate_limited": true }); + yield* Effect.annotateCurrentSpan({ + "relay.cloudflare.rate_limited": true, + "relay.cloudflare.pause_ms": pauseMillis, + }); yield* pause.pauseUntil(until); }); return ( @@ -478,8 +482,12 @@ const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext checkedAtMillis = now; pausedUntilMillis = Math.max(pausedUntilMillis, yield* pause.pausedUntilMillis); } + // A paused call never reaches Cloudflare, so it leaves no 429 behind. + // Its own span keeps a storm visible to the rate-limit monitors. if (now < pausedUntilMillis) { - return yield* new CloudflareApiPaused({ retryAfterMillis: pausedUntilMillis - now }); + return yield* new CloudflareApiPaused({ retryAfterMillis: pausedUntilMillis - now }).pipe( + Effect.withSpan("relay.cloudflare_api_pause.rejected"), + ); } return yield* call.pipe( Effect.provideService(CloudflareRetry.Retry, withoutRateLimitRetries), diff --git a/infra/relay/src/monitoring.ts b/infra/relay/src/monitoring.ts index f791dfc450265..a307f46c2e3a1 100644 --- a/infra/relay/src/monitoring.ts +++ b/infra/relay/src/monitoring.ts @@ -114,9 +114,9 @@ const relayMonitors: ReadonlyArray = [ severity: "page", name: "T3 Connect relay: Cloudflare API rate limited", description: - "Cloudflare API 429s per 10 min from tunnel and DNS provisioning. Sustained at this level, links and recoveries stall. Peak before #16810: 1,286; during it: ~11k.", + "Cloudflare API 429s, plus calls the relay refused while paused after one, per 10 min. Sustained at this level, links and recoveries stall. Peak 429s before #16810: 1,286; during it: ~11k.", query: (dataset) => - `['${dataset}']\n| where ${CLOUDFLARE_API} and ${STATUS} == 429\n| summarize rate_limited = count()`, + `['${dataset}']\n| where (${CLOUDFLARE_API} and ${STATUS} == 429) or name == "relay.cloudflare_api_pause.rejected"\n| summarize rate_limited = count()`, operator: "AboveOrEqual", threshold: 500, rangeMinutes: 10, @@ -140,9 +140,9 @@ const relayMonitors: ReadonlyArray = [ severity: "warn", name: "T3 Connect relay: Cloudflare API near its limit", description: - "Any sustained Cloudflare API 429s. These bursts ran for days before #16810; raise the account limit or cut call volume before they grow.", + "Any sustained Cloudflare API 429s or paused calls. 429 bursts ran for days before #16810; raise the account limit or cut call volume before they grow.", query: (dataset) => - `['${dataset}']\n| where ${CLOUDFLARE_API} and ${STATUS} == 429\n| summarize rate_limited = count()`, + `['${dataset}']\n| where (${CLOUDFLARE_API} and ${STATUS} == 429) or name == "relay.cloudflare_api_pause.rejected"\n| summarize rate_limited = count()`, operator: "AboveOrEqual", threshold: 20, rangeMinutes: 10, From 24e4ea9eb3bdf4af2c1e38b3259e102d4985660a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 20:05:01 -0700 Subject: [PATCH 6/9] refactor(relay): record each Cloudflare rate limit in its own span The new prefer-effect-fn lint rule flagged the inline Effect.gen. The relay.cloudflare_api_pause.rate_limited span now carries the pause length. Co-Authored-By: Claude Opus 5.5 --- .../environments/ManagedEndpointProvider.ts | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 1e912ac790fec..f7d9ae93af516 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -462,17 +462,15 @@ const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext let pausedUntilMillis = 0; let checkedAtMillis = Number.NEGATIVE_INFINITY; return (pause: CloudflareApiPause.CloudflareApiPause["Service"]) => { - const recordRateLimit = (cause: unknown) => - Effect.gen(function* () { - const pauseMillis = cloudflareRateLimitPauseMillis(cause); - const until = (yield* Clock.currentTimeMillis) + pauseMillis; - pausedUntilMillis = Math.max(pausedUntilMillis, until); - yield* Effect.annotateCurrentSpan({ - "relay.cloudflare.rate_limited": true, - "relay.cloudflare.pause_ms": pauseMillis, - }); - yield* pause.pauseUntil(until); - }); + const recordRateLimit = Effect.fn("relay.cloudflare_api_pause.rate_limited")(function* ( + cause: unknown, + ) { + const pauseMillis = cloudflareRateLimitPauseMillis(cause); + const until = (yield* Clock.currentTimeMillis) + pauseMillis; + pausedUntilMillis = Math.max(pausedUntilMillis, until); + yield* Effect.annotateCurrentSpan({ "relay.cloudflare.pause_ms": pauseMillis }); + yield* pause.pauseUntil(until); + }); return ( call: Effect.Effect, ): Effect.Effect => From becbb5db8ce8df97163f779ea8fd15c01ca6cf8e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 20:30:53 -0700 Subject: [PATCH 7/9] feat(relay): dashboard shows recovery fast-path use and paused Cloudflare calls Two charts to see this change working: provisions split into reused ready tunnels, full provisions and failures; and Cloudflare API calls with paused calls and calls that got no response as their own series, so a held-back storm does not look like a quiet period. Co-Authored-By: Claude Opus 5.5 --- infra/relay/src/monitoring.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/infra/relay/src/monitoring.ts b/infra/relay/src/monitoring.ts index a307f46c2e3a1..e7b06fc3f6512 100644 --- a/infra/relay/src/monitoring.ts +++ b/infra/relay/src/monitoring.ts @@ -218,7 +218,14 @@ const relayDashboardCharts = (dataset: string): ReadonlyArray => { timeSeries( "cloudflare-api", "Cloudflare API calls by status", - `${source}\n| where ${CLOUDFLARE_API}\n| summarize count() by bin_auto(_time), status = ${STATUS}`, + // Calls refused during a rate-limit pause never reach Cloudflare, so + // they are their own series or a storm would look like a quiet period. + `${source}\n| where ${CLOUDFLARE_API} or name == "relay.cloudflare_api_pause.rejected"\n| summarize count() by bin_auto(_time), status = case(name == "relay.cloudflare_api_pause.rejected", "paused", isnull(${STATUS}), "no response", tostring(${STATUS}))`, + ), + timeSeries( + "provision-paths", + "Tunnel provisions by path", + `${source}\n| where name == "relay.managed_endpoint_provider.provision"\n| summarize reused_ready_tunnel = countif(error != true and tobool(['attributes.custom']['relay.managed_endpoint.reused_ready_tunnel']) == true), full_provision = countif(error != true and isnull(['attributes.custom']['relay.managed_endpoint.reused_ready_tunnel'])), failed = countif(error == true) by bin_auto(_time)`, ), timeSeries( "postgres", From af7a32fd80a82711803250e4df69c706958d553f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 20:36:25 -0700 Subject: [PATCH 8/9] fix(relay): a 429 recorded during a shared pause read is no longer erased `Math.max(pausedUntilMillis, yield* read)` captured the local value before the read suspended, so a pause recorded by a concurrent 429 in the same isolate was overwritten when the read returned. Read first, then merge. Found by Macroscope. Co-Authored-By: Claude Opus 5.5 --- .../ManagedEndpointProvider.test.ts | 55 +++++++++++++++++++ .../environments/ManagedEndpointProvider.ts | 4 +- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index 704a43fbd602b..9717382444fb8 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -3,7 +3,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; import * as Alchemy from "alchemy"; import * as Cloudflare from "alchemy/Cloudflare"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; import * as TestClock from "effect/testing/TestClock"; @@ -843,6 +845,59 @@ describe("ManagedEndpointProvider", () => { }).pipe(Effect.provide(layer)); }); + it.effect("keeps a pause recorded while a shared pause read was in flight", () => { + let listCalls = 0; + const tunnelClient = { + list: () => + Effect.suspend(() => { + listCalls += 1; + return Effect.fail({ _tag: "TooManyRequests", message: "Rate limited" }); + }), + } as unknown as Cloudflare.Tunnel.ReadWriteTunnelClient; + + return Effect.gen(function* () { + const readStarted = yield* Deferred.make(); + const releaseRead = yield* Deferred.make(); + const layer = ManagedEndpointProvider.layerCloudflareBindings( + tunnelClient, + {} as Cloudflare.DNS.ReadWriteDnsClient, + {} as Alchemy.BaseRuntimeContext, + ).pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(RelayConfiguration.layer(config)), + Layer.provide( + Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()), + ), + Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())), + Layer.provide( + Layer.succeed( + CloudflareApiPause.CloudflareApiPause, + CloudflareApiPause.CloudflareApiPause.of({ + pausedUntilMillis: Deferred.succeed(readStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseRead)), + Effect.as(0), + ), + pauseUntil: () => Effect.void, + }), + ), + ), + ); + + yield* Effect.gen(function* () { + const tunnels = yield* ManagedEndpointProvider.ManagedEndpointTunnelClient; + const list = tunnels.list({ isDeleted: false }).pipe(Effect.flip); + // The first call starts the shared read; the second hits a 429 meanwhile. + const reading = yield* Effect.forkChild(list); + yield* Deferred.await(readStarted); + yield* list; + yield* Deferred.succeed(releaseRead, undefined); + yield* Fiber.join(reading); + yield* list; + expect(listCalls).toBe(1); + }).pipe(Effect.provide(layer)); + }); + }); + it.effect("pauses Cloudflare calls in every isolate until a rate limit has passed", () => { let listCalls = 0; const tunnelClient = { diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index f7d9ae93af516..162c2f8fa744f 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -478,7 +478,9 @@ const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext const now = yield* Clock.currentTimeMillis; if (now >= pausedUntilMillis && now - checkedAtMillis >= CLOUDFLARE_PAUSE_REFRESH_MILLIS) { checkedAtMillis = now; - pausedUntilMillis = Math.max(pausedUntilMillis, yield* pause.pausedUntilMillis); + // Read first: a 429 recorded while the read is in flight must win. + const shared = yield* pause.pausedUntilMillis; + pausedUntilMillis = Math.max(pausedUntilMillis, shared); } // A paused call never reaches Cloudflare, so it leaves no 429 behind. // Its own span keeps a storm visible to the rate-limit monitors. From f62e0216102c34c511496b577be926c4cf788eaf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 20:46:00 -0700 Subject: [PATCH 9/9] feat(relay): tell hosts when to retry during a Cloudflare rate limit Link, tunnel registration and recovery failures caused by a Cloudflare 429 or the shared pause after one now carry Retry-After with the remaining pause, so hosts that honor it (#22108) wait the pause out instead of retrying into it. Co-Authored-By: Claude Opus 5.5 --- .../environments/ManagedEndpointProvider.ts | 24 +++++ infra/relay/src/http/Api.test.ts | 96 +++++++++++++++++++ infra/relay/src/http/Api.ts | 14 +++ 3 files changed, 134 insertions(+) diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 162c2f8fa744f..6a5d1f8bc3c9a 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -438,6 +438,30 @@ function cloudflareRateLimitPauseMillis(cause: unknown): number { return Duration.toMillis(Duration.min(pause, CLOUDFLARE_MAX_RATE_LIMIT_PAUSE)); } +/** + * How long a caller should wait before retrying, when `cause` is a Cloudflare + * rate limit or a call refused during the pause that follows one. + */ +export function cloudflareRetryAfterMillis(cause: unknown): number | undefined { + for (let current = cause, depth = 0; depth < 8; depth++) { + if (typeof current !== "object" || current === null) return undefined; + if ("_tag" in current && current._tag === "CloudflareApiPaused") { + const retryAfterMillis: unknown = Reflect.get(current, "retryAfterMillis"); + return typeof retryAfterMillis === "number" ? retryAfterMillis : undefined; + } + if ( + ("_tag" in current && + (current._tag === "TooManyRequests" || current._tag === "CloudflareRateLimited")) || + ("status" in current && current.status === 429) + ) { + return cloudflareRateLimitPauseMillis(current); + } + if (!("cause" in current)) return undefined; + current = current.cause; + } + return undefined; +} + // The SDK's default policy sleeps through Retry-After inside the request, which // held every caller until its timeout and kept the account over its limit. // Rate limits surface at once instead; other transient failures still retry. diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.ts index 81574b0392248..9455cf36ca4b4 100644 --- a/infra/relay/src/http/Api.test.ts +++ b/infra/relay/src/http/Api.test.ts @@ -187,6 +187,102 @@ describe("device listing compatibility", () => { }); }); +describe("Cloudflare rate-limit retry hint", () => { + const provisioningFailed = (cause?: unknown) => + new ManagedEndpointProvider.ManagedEndpointProvisioningFailed({ + userId: "user-1", + environmentId: "env-1", + stage: "ensure-tunnel", + ...(cause === undefined + ? {} + : { + cause: new ManagedEndpointProvider.ManagedEndpointTunnelClientError({ + operation: "list", + cause, + }), + }), + }); + + const linkResponse = (failure: ManagedEndpointProvider.ManagedEndpointProvisioningFailed) => { + const layerHandlers = RelayHttpApi.layerClientApi.pipe( + HttpRouter.provideRequest( + Layer.mergeAll( + Layer.mock(EnvironmentCredentials.EnvironmentCredentials, {}), + Layer.mock(EnvironmentLinks.EnvironmentLinks, {}), + Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}), + Layer.mock(RelayDb.RelayTransactions, {}), + Layer.mock(HookInbox.HookInbox, {}), + ), + ), + Layer.provide( + Layer.mergeAll( + Layer.succeed(RelayConfiguration.RelayConfiguration, relaySettings), + NodeCryptoLayer.layer, + Layer.mock(RelayTokens.RelayTokens, { resolveDpopAccessTokenScopes: () => null }), + Layer.mock(EnvironmentLinker.EnvironmentLinker, { link: () => Effect.fail(failure) }), + Layer.mock(EnvironmentLinks.EnvironmentLinks, {}), + Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}), + Layer.mock(Devices.Devices, {}), + ), + ), + Layer.provideMerge( + Layer.succeed(RelayClientAuth, { + clientBearer: (effect) => + Effect.provideService(effect, RelayClientPrincipal, { + userId: "user-1", + token: "test-token", + }), + }), + ), + ); + return Effect.acquireRelease( + Effect.sync(() => + HttpRouter.toWebHandler( + HttpApiBuilder.layer(HttpApi.make("RelayApi").add(RelayApi.groups.client)).pipe( + Layer.provide(layerHandlers), + Layer.provide(HttpServer.layerServices), + ), + { disableLogger: true }, + ), + ), + (app) => Effect.promise(() => app.dispose()), + ).pipe( + Effect.flatMap((app) => + Effect.promise(() => + app.handler( + new Request("https://relay.example.test/v1/client/environment-links", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify({ + proof: "signed-proof", + notificationsEnabled: true, + liveActivitiesEnabled: true, + managedTunnelsEnabled: true, + }), + }), + ), + ), + ), + ); + }; + + it.effect("tells a link refused during a Cloudflare pause when to retry", () => + Effect.gen(function* () { + const paused = yield* linkResponse( + provisioningFailed( + new ManagedEndpointProvider.CloudflareApiPaused({ retryAfterMillis: 24_100 }), + ), + ); + expect(paused.status).toBe(503); + expect(paused.headers.get("retry-after")).toBe("25"); + + const other = yield* linkResponse(provisioningFailed()); + expect(other.status).toBe(503); + expect(other.headers.get("retry-after")).toBeNull(); + }).pipe(Effect.scoped), + ); +}); + describe("relay client authentication", () => { it.effect("preserves the existing Clerk session JWT path", () => Effect.gen(function* () { diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index 6cbf00dc6e9db..69925a3645311 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -102,6 +102,17 @@ const appendRelayCredentialResponseHeaders = HttpEffect.appendPreResponseHandler ), ); +// T3 Code hosts never retry sooner than Retry-After, so during a Cloudflare +// rate limit they wait out the pause instead of retrying into it. +const appendCloudflareRetryAfter = (error: unknown) => { + const retryAfterMillis = ManagedEndpointProvider.cloudflareRetryAfterMillis(error); + if (retryAfterMillis === undefined) return Effect.void; + const seconds = String(Math.max(1, Math.ceil(retryAfterMillis / 1000))); + return HttpEffect.appendPreResponseHandler((_request, response) => + Effect.succeed(HttpServerResponse.setHeader(response, "retry-after", seconds)), + ); +}; + const appendRelayDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) => Effect.succeed( response.status === 401 @@ -874,6 +885,7 @@ export const layerClientApi = HttpApiBuilder.group( cloudMintPublicKey: config.cloudMintPublicKey, }; }, + Effect.tapError(appendCloudflareRetryAfter), mapErrorTags({ EnvironmentLinkProofExpired: (_error, traceId) => new RelayEnvironmentLinkProofExpiredError({ @@ -1335,6 +1347,7 @@ export const layerServerApi = HttpApiBuilder.group( origin: payload.origin, }); }, + Effect.tapError(appendCloudflareRetryAfter), Effect.catchTags({ ManagedEndpointOriginNotAllowed: () => Effect.fail(new HttpApiError.Unauthorized({})), ManagedEndpointProvisioningNotConfigured: () => @@ -1370,6 +1383,7 @@ export const layerServerApi = HttpApiBuilder.group( origin: payload.origin, }); }, + Effect.tapError(appendCloudflareRetryAfter), Effect.catchTags({ ManagedEndpointOriginNotAllowed: () => Effect.fail(new HttpApiError.Unauthorized({})), ManagedEndpointProvisioningNotConfigured: () =>