Skip to content
TypeScript

fix(relay): tunnel recovery no longer drives the Cloudflare API into rate limits (#22059)

Julius Marminge44a7cb1057b6
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 00000000000..175f886bd3c
--- /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 00000000000..84acbfa6fd4
--- /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/package.json b/infra/relay/package.json
index 2992bb56a12..dd2265aafb0 100644
--- a/infra/relay/package.json
+++ b/infra/relay/package.json
@@ -13,6 +13,7 @@
},
"dependencies": {
"@clerk/backend": "catalog:",
+ "@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 00000000000..c844a679c10
--- /dev/null
+++ b/infra/relay/src/environments/CloudflareApiPause.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from "@effect/vitest";
+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 = 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<boolean>) {
+ const statement = <A>(result: A) =>
+ Effect.serviceOption(TransactionConnection).pipe(
+ Effect.tap((connection) =>
+ Effect.sync(() => joinedTransaction.push(Option.isSome(connection))),
+ ),
+ Effect.as(result),
+ );
+ return {
+ $client: lazyProxy(),
+ 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<boolean> = [];
+ return Effect.gen(function* () {
+ const pause = yield* CloudflareApiPause.CloudflareApiPause;
+ const inTransaction = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
+ 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));
+
+ 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
new file mode 100644
index 00000000000..00a076e4d62
--- /dev/null
+++ b/infra/relay/src/environments/CloudflareApiPause.ts
@@ -0,0 +1,85 @@
+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";
+
+// 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<never>): Context.Context<never> =>
+ 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
+ * 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,
+ {
+ /** Epoch milliseconds until which calls are paused, or 0. */
+ readonly pausedUntilMillis: Effect.Effect<number>;
+ readonly pauseUntil: (untilMillis: number) => Effect.Effect<void>;
+ }
+>()("t3code-relay/environments/CloudflareApiPause") {}
+
+export const make = Effect.gen(function* () {
+ const db = yield* RelayDb.RelayDb;
+ const outsideTransaction = <A, E>(effect: Effect.Effect<A, E>) =>
+ Effect.updateContext(effect, withoutSqlTransaction);
+
+ 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),
+ ),
+ ),
+ outsideTransaction,
+ 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 }),
+ ),
+ outsideTransaction,
+ 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 2e8c895d110..9717382444f 100644
--- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts
+++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts
@@ -3,11 +3,15 @@ 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";
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";
@@ -364,6 +368,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<string, string> = {
"user_ABC:env_ABC": "d101ac68108a423e",
"user_ABC:env_shared": "d7e6356aaf8863aa",
@@ -413,6 +428,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* () {
@@ -754,6 +772,184 @@ 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("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<void>();
+ const releaseRead = yield* Deferred.make<void>();
+ 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 = {
+ list: () =>
+ Effect.suspend(() => {
+ listCalls += 1;
+ return Effect.fail({ _tag: "TooManyRequests", message: "Rate limited" });
+ }),
+ } as unknown as Cloudflare.Tunnel.ReadWriteTunnelClient;
+ 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 },
+ }),
+ ),
+ Effect.flip,
+ );
+
+ 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(pausedElsewhere).toMatchObject({
+ _tag: "ManagedEndpointProvisioningFailed",
+ stage: "ensure-tunnel",
+ cause: { cause: { _tag: "CloudflareApiPaused" } },
+ });
+
+ yield* TestClock.adjust("30 seconds");
+ yield* provision.pipe(Effect.provide(isolate()));
+ expect(listCalls).toBe(2);
+ });
+ });
+
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 bb906db16a8..6a5d1f8bc3c 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";
@@ -23,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";
@@ -148,6 +153,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<ManagedEndpointProvisioningResult, ManagedEndpointProviderError>;
readonly reconcileOrigin: (input: {
readonly userId: string;
@@ -389,6 +399,132 @@ export function isManagedEndpointNotFound(cause: unknown): boolean {
return "cause" in cause && isManagedEndpointNotFound(cause.cause);
}
+export class CloudflareApiPaused extends Schema.TaggedError<CloudflareApiPaused>()(
+ "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;
+ }
+ if ("status" in cause && cause.status === 429) {
+ 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));
+}
+
+/**
+ * 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.
+const withoutRateLimitRetries: CloudflareRetry.Factory = (lastError) => {
+ const defaults = CloudflareRetry.makeDefault(lastError);
+ return {
+ ...defaults,
+ while: (error) => !isCloudflareRateLimited(error) && (defaults.while?.(error) ?? false),
+ };
+};
+
+// 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 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;
+ let checkedAtMillis = Number.NEGATIVE_INFINITY;
+ return (pause: CloudflareApiPause.CloudflareApiPause["Service"]) => {
+ 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 <A, E>(
+ call: Effect.Effect<A, E, Alchemy.RuntimeContext>,
+ ): Effect.Effect<A, E | CloudflareApiPaused | Cause.TimeoutError> =>
+ Effect.gen(function* () {
+ const now = yield* Clock.currentTimeMillis;
+ if (now >= pausedUntilMillis && now - checkedAtMillis >= CLOUDFLARE_PAUSE_REFRESH_MILLIS) {
+ checkedAtMillis = now;
+ // 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.
+ if (now < pausedUntilMillis) {
+ return yield* new CloudflareApiPaused({ retryAfterMillis: pausedUntilMillis - now }).pipe(
+ Effect.withSpan("relay.cloudflare_api_pause.rejected"),
+ );
+ }
+ 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),
+ );
+ });
+ };
+};
+
/**
* 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 +639,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<ManagedEndpointProvisioningResult>();
+ }
+ 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<ManagedEndpointProvisioningResult>();
+ }
+ 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<ManagedEndpointProvisioningResult>({
+ 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 +1234,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,153 +1546,142 @@ export const layerCloudflareBindings = (
tunnelClient: Cloudflare.Tunnel.ReadWriteTunnelClient,
dnsClient: Cloudflare.DNS.ReadWriteDnsClient,
alchemyRuntimeContext: Alchemy.BaseRuntimeContext,
-) =>
- layer.pipe(
+) => {
+ // 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) =>
- tunnelClient.get(tunnelId).pipe(
- Effect.timeout("8 seconds"),
- Effect.mapError(
- (cause) =>
- new ManagedEndpointTunnelClientError({
- operation: "get",
- tunnelId,
- cause,
- }),
- ),
- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
- ),
- list: (request) =>
- tunnelClient.list(request).pipe(
- Effect.timeout("8 seconds"),
- Effect.mapError(
- (cause) =>
- new ManagedEndpointTunnelClientError({
- operation: "list",
- ...(request.name === undefined ? {} : { tunnelName: request.name }),
- cause,
- }),
- ),
- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
- ),
- create: (request) =>
- tunnelClient.create(request).pipe(
- Effect.timeout("8 seconds"),
- Effect.mapError(
- (cause) =>
- new ManagedEndpointTunnelClientError({
- operation: "create",
- tunnelName: request.name,
- cause,
- }),
- ),
- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
- ),
- putConfiguration: (tunnelId, config) =>
- tunnelClient.putConfiguration(tunnelId, config).pipe(
- Effect.timeout("8 seconds"),
- Effect.mapError(
- (cause) =>
- new ManagedEndpointTunnelClientError({
- operation: "put-configuration",
- tunnelId,
- cause,
- }),
- ),
- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
- ),
- getToken: (tunnelId) =>
- tunnelClient.getToken(tunnelId).pipe(
- Effect.timeout("8 seconds"),
- Effect.mapError(
- (cause) =>
- new ManagedEndpointTunnelClientError({
- operation: "get-token",
- tunnelId,
- cause,
- }),
- ),
- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
- ),
- delete: (tunnelId) =>
- tunnelClient.delete(tunnelId).pipe(
- Effect.timeout("8 seconds"),
- Effect.mapError(
- (cause) =>
- new ManagedEndpointTunnelClientError({
- operation: "delete",
- tunnelId,
- cause,
- }),
- ),
- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
- ),
- }),
- layerDnsClient({
- listRecords: (hostname) =>
- dnsClient.listDnsRecords({ search: hostname }).pipe(
- Effect.timeout("8 seconds"),
- 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,
- }),
- ),
- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
- ),
- createRecord: (request) =>
- dnsClient.createDnsRecord(request).pipe(
- Effect.timeout("8 seconds"),
- Effect.map((response) => ({ id: response.id })),
- Effect.mapError(
- (cause) =>
- new ManagedEndpointDnsClientError({
- operation: "create-record",
- hostname: request.name,
- cause,
- }),
- ),
- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
- ),
- updateRecord: (dnsRecordId, request) =>
- dnsClient.updateDnsRecord(dnsRecordId, request).pipe(
- Effect.timeout("8 seconds"),
- Effect.mapError(
- (cause) =>
- new ManagedEndpointDnsClientError({
- operation: "update-record",
- hostname: request.name,
- dnsRecordId,
- cause,
- }),
- ),
- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
- ),
- deleteRecord: (dnsRecordId) =>
- dnsClient.deleteDnsRecord(dnsRecordId).pipe(
- Effect.timeout("8 seconds"),
- Effect.mapError(
- (cause) =>
- new ManagedEndpointDnsClientError({
- operation: "delete-record",
- dnsRecordId,
- cause,
- }),
- ),
- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
- ),
+ 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/environments/ManagedEndpointReaper.test.ts b/infra/relay/src/environments/ManagedEndpointReaper.test.ts
index 252b468e7cc..26ce55a58a7 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 27c3574ff47..cbaf63577e7 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/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.ts
index 81574b03922..9455cf36ca4 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 8db3a4054d6..69925a36453 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
@@ -693,6 +704,7 @@ export const recoverEnvironmentTunnelRecord = Effect.fn(
userId: input.userId,
environmentId: input.environmentId,
origin: input.origin,
+ reuseReadyTunnel: true,
});
const recoveredTunnelId = recovered.runtime.tunnelId;
if (
@@ -873,6 +885,7 @@ export const layerClientApi = HttpApiBuilder.group(
cloudMintPublicKey: config.cloudMintPublicKey,
};
},
+ Effect.tapError(appendCloudflareRetryAfter),
mapErrorTags({
EnvironmentLinkProofExpired: (_error, traceId) =>
new RelayEnvironmentLinkProofExpiredError({
@@ -1334,6 +1347,7 @@ export const layerServerApi = HttpApiBuilder.group(
origin: payload.origin,
});
},
+ Effect.tapError(appendCloudflareRetryAfter),
Effect.catchTags({
ManagedEndpointOriginNotAllowed: () => Effect.fail(new HttpApiError.Unauthorized({})),
ManagedEndpointProvisioningNotConfigured: () =>
@@ -1369,6 +1383,7 @@ export const layerServerApi = HttpApiBuilder.group(
origin: payload.origin,
});
},
+ Effect.tapError(appendCloudflareRetryAfter),
Effect.catchTags({
ManagedEndpointOriginNotAllowed: () => Effect.fail(new HttpApiError.Unauthorized({})),
ManagedEndpointProvisioningNotConfigured: () =>
diff --git a/infra/relay/src/monitoring.ts b/infra/relay/src/monitoring.ts
index 6577dab61cf..3ed521de7e2 100644
--- a/infra/relay/src/monitoring.ts
+++ b/infra/relay/src/monitoring.ts
@@ -119,9 +119,9 @@ const relayMonitors: ReadonlyArray<RelayMonitor> = [
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,
@@ -145,9 +145,9 @@ const relayMonitors: ReadonlyArray<RelayMonitor> = [
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,
@@ -250,7 +250,14 @@ const relayDashboardCharts = (dataset: string): ReadonlyArray<QueryChart> => {
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",
diff --git a/infra/relay/src/persistence/schema.ts b/infra/relay/src/persistence/schema.ts
index 3ed6a75a5f6..132ceba16a9 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 7e381b23f7d..2d3e388ceb1 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,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ed2566a4e22..3744c9e1e38 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
@@ -1064,6 +1067,9 @@ importers:
'@clerk/backend':
specifier: 3.25.0
+ '@distilled.cloud/cloudflare':
+ specifier: 'catalog:'
+ version: 1.0.0-rc.13([email protected])
'@effect/sql-pg':
specifier: 4.0.5
version: 4.0.5([email protected])
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index ac0a089fb95..12ec4bc1b6e 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