diff --git a/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/migration.sql b/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/migration.sql new file mode 100644 index 0000000000..7b8f004160 --- /dev/null +++ b/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/migration.sql @@ -0,0 +1,15 @@ +CREATE TABLE "relay_managed_endpoint_allocations" ( + "user_id" varchar(191), + "environment_id" varchar(191), + "hostname" text NOT NULL, + "tunnel_id" varchar(191), + "tunnel_name" text NOT NULL, + "dns_record_id" varchar(191), + "ready_at" varchar(64), + "created_at" varchar(64) NOT NULL, + "updated_at" varchar(64) NOT NULL, + CONSTRAINT "relay_managed_endpoint_allocations_pkey" PRIMARY KEY("user_id","environment_id") +); +--> statement-breakpoint +CREATE UNIQUE INDEX "idx_relay_managed_endpoint_allocations_hostname" ON "relay_managed_endpoint_allocations" ("hostname");--> statement-breakpoint +CREATE UNIQUE INDEX "idx_relay_managed_endpoint_allocations_tunnel_name" ON "relay_managed_endpoint_allocations" ("tunnel_name"); \ No newline at end of file diff --git a/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/snapshot.json b/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/snapshot.json new file mode 100644 index 0000000000..ead6f60968 --- /dev/null +++ b/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/snapshot.json @@ -0,0 +1,1453 @@ +{ + "version": "8", + "dialect": "postgres", + "id": "385d476b-d4f6-48a3-99e6-0a95af4ee4e4", + "prevIds": ["e189638b-4700-4656-b86e-d8baa63f5fe4"], + "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_mobile_devices", + "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(191)", + "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(191)", + "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": "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": 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(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": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ios_major_version", + "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": "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" + }, + { + "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": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_live_activities_user", + "entityType": "indexes", + "schema": "public", + "table": "relay_live_activities" + }, + { + "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": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_user", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "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" + } + ], + "renames": [] +} diff --git a/infra/relay/src/deploymentConfig.test.ts b/infra/relay/src/deploymentConfig.test.ts index 0ae4f6054a..c7dc7b3506 100644 --- a/infra/relay/src/deploymentConfig.test.ts +++ b/infra/relay/src/deploymentConfig.test.ts @@ -50,7 +50,9 @@ describe("managed endpoint names", () => { it("uses the stage slug and a stable stage-scoped digest suffix", () => { const hash = "ABCDEF0123456789ABCDEF0123456789"; - expect(managedEndpointDigestInput("dev_julius", "env_123")).toBe("dev_julius:env_123"); + expect(managedEndpointDigestInput("dev_julius", "user_123", "env_123")).toBe( + "dev_julius:user_123:env_123", + ); expect(managedEndpointHostname("dev_julius", ".example.com.", hash)).toBe( "tunnels-dev-julius-abcdef0123456789.example.com", ); diff --git a/infra/relay/src/deploymentConfig.ts b/infra/relay/src/deploymentConfig.ts index 2ff61f4519..413201f277 100644 --- a/infra/relay/src/deploymentConfig.ts +++ b/infra/relay/src/deploymentConfig.ts @@ -51,8 +51,12 @@ export function relayPublicDomainForStage(stage: string, zoneName: string): stri return `${relayLabel}.${normalizeZoneName(zoneName)}`; } -export function managedEndpointDigestInput(stage: string, environmentId: string): string { - return `${stage}:${environmentId}`; +export function managedEndpointDigestInput( + stage: string, + userId: string, + environmentId: string, +): string { + return `${stage}:${userId}:${environmentId}`; } export function managedEndpointHostname(stage: string, baseDomain: string, hash: string): string { diff --git a/infra/relay/src/environments/EnvironmentLinker.ts b/infra/relay/src/environments/EnvironmentLinker.ts index 59c83477dc..853ea41cbd 100644 --- a/infra/relay/src/environments/EnvironmentLinker.ts +++ b/infra/relay/src/environments/EnvironmentLinker.ts @@ -234,6 +234,7 @@ const make = Effect.gen(function* () { } const provisioned = input.request.managedTunnelsEnabled ? yield* managedEndpointProvider.provision({ + userId: input.userId, environmentId: verified.environmentId, origin: verified.origin, }) diff --git a/infra/relay/src/environments/ManagedEndpointAllocations.ts b/infra/relay/src/environments/ManagedEndpointAllocations.ts new file mode 100644 index 0000000000..13521c6b15 --- /dev/null +++ b/infra/relay/src/environments/ManagedEndpointAllocations.ts @@ -0,0 +1,158 @@ +import { and, eq } from "drizzle-orm"; +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { RelayDb } from "../db.ts"; +import { relayManagedEndpointAllocations } from "../persistence/schema.ts"; + +export interface ManagedEndpointAllocation { + readonly userId: string; + readonly environmentId: string; + readonly hostname: string; + readonly tunnelId: string | null; + readonly tunnelName: string; + readonly dnsRecordId: string | null; + readonly readyAt: string | null; +} + +export class ManagedEndpointAllocationPersistenceError extends Data.TaggedError( + "ManagedEndpointAllocationPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +interface ManagedEndpointAllocationKey { + readonly userId: string; + readonly environmentId: string; +} + +interface ReserveManagedEndpointAllocationInput extends ManagedEndpointAllocationKey { + readonly hostname: string; + readonly tunnelName: string; +} + +interface RecordManagedEndpointTunnelInput extends ManagedEndpointAllocationKey { + readonly tunnelId: string; +} + +interface RecordManagedEndpointDnsInput extends ManagedEndpointAllocationKey { + readonly dnsRecordId: string; +} + +export interface ManagedEndpointAllocationsShape { + readonly reserve: ( + input: ReserveManagedEndpointAllocationInput, + ) => Effect.Effect; + readonly recordTunnel: ( + input: RecordManagedEndpointTunnelInput, + ) => Effect.Effect; + readonly recordDns: ( + input: RecordManagedEndpointDnsInput, + ) => Effect.Effect; + readonly markReady: ( + input: ManagedEndpointAllocationKey, + ) => Effect.Effect; +} + +const allocationSelection = { + userId: relayManagedEndpointAllocations.userId, + environmentId: relayManagedEndpointAllocations.environmentId, + hostname: relayManagedEndpointAllocations.hostname, + tunnelId: relayManagedEndpointAllocations.tunnelId, + tunnelName: relayManagedEndpointAllocations.tunnelName, + dnsRecordId: relayManagedEndpointAllocations.dnsRecordId, + readyAt: relayManagedEndpointAllocations.readyAt, +}; + +const whereAllocation = (input: ManagedEndpointAllocationKey) => + and( + eq(relayManagedEndpointAllocations.userId, input.userId), + eq(relayManagedEndpointAllocations.environmentId, input.environmentId), + ); + +const persistenceError = (cause: unknown) => + cause instanceof ManagedEndpointAllocationPersistenceError + ? cause + : new ManagedEndpointAllocationPersistenceError({ cause }); + +const make = Effect.gen(function* () { + const db = yield* RelayDb; + + return ManagedEndpointAllocations.of({ + reserve: Effect.fn("relay.managed_endpoint_allocations.reserve")(function* ( + input: ReserveManagedEndpointAllocationInput, + ) { + const now = DateTime.formatIso(yield* DateTime.now); + const inserted = yield* db + .insert(relayManagedEndpointAllocations) + .values({ + ...input, + createdAt: now, + updatedAt: now, + }) + .onConflictDoNothing() + .returning(allocationSelection); + + const allocation = + inserted[0] ?? + (yield* db + .select(allocationSelection) + .from(relayManagedEndpointAllocations) + .where(whereAllocation(input)) + .limit(1) + .pipe(Effect.map((rows) => rows[0]))); + + if (allocation === undefined) { + return yield* new ManagedEndpointAllocationPersistenceError({ + cause: new Error("Managed endpoint allocation was not persisted."), + }); + } + + return allocation; + }, Effect.mapError(persistenceError)), + recordTunnel: Effect.fn("relay.managed_endpoint_allocations.record_tunnel")(function* ( + input: RecordManagedEndpointTunnelInput, + ) { + yield* db + .update(relayManagedEndpointAllocations) + .set({ + tunnelId: input.tunnelId, + updatedAt: DateTime.formatIso(yield* DateTime.now), + }) + .where(whereAllocation(input)); + }, Effect.mapError(persistenceError)), + recordDns: Effect.fn("relay.managed_endpoint_allocations.record_dns")(function* ( + input: RecordManagedEndpointDnsInput, + ) { + yield* db + .update(relayManagedEndpointAllocations) + .set({ + dnsRecordId: input.dnsRecordId, + updatedAt: DateTime.formatIso(yield* DateTime.now), + }) + .where(whereAllocation(input)); + }, Effect.mapError(persistenceError)), + markReady: Effect.fn("relay.managed_endpoint_allocations.mark_ready")(function* ( + input: ManagedEndpointAllocationKey, + ) { + const now = DateTime.formatIso(yield* DateTime.now); + yield* db + .update(relayManagedEndpointAllocations) + .set({ + readyAt: now, + updatedAt: now, + }) + .where(whereAllocation(input)); + }, Effect.mapError(persistenceError)), + }); +}); + +export class ManagedEndpointAllocations extends Context.Service< + ManagedEndpointAllocations, + ManagedEndpointAllocationsShape +>()("t3code-relay/environments/ManagedEndpointAllocations") { + static readonly layer = Layer.effect(this, make); +} diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index 8466c9b919..b6a3f2f3fe 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -7,6 +7,7 @@ import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; import * as RelayConfiguration from "../Config.ts"; +import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts"; import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts"; const config = RelayConfiguration.RelayConfiguration.of({ @@ -34,10 +35,19 @@ interface TunnelCall { } interface DnsCall { - readonly operation: "listCnameRecords" | "createCnameRecord" | "updateCnameRecord"; + readonly operation: "listRecords" | "createRecord" | "updateRecord" | "deleteRecord"; readonly input: unknown; } +interface AllocationCall { + readonly operation: "reserve" | "recordTunnel" | "recordDns" | "markReady"; + readonly input: unknown; +} + +function allocationKey(input: { readonly userId: string; readonly environmentId: string }) { + return `${input.userId}:${input.environmentId}`; +} + function makeTunnelClient(calls: TunnelCall[] = []) { return ManagedEndpointProvider.ManagedEndpointTunnelClient.of({ list: (request) => @@ -62,47 +72,134 @@ function makeTunnelClient(calls: TunnelCall[] = []) { }); } -function makeDnsClient( - calls: DnsCall[] = [], - records: ReadonlyArray<{ readonly id: string }> = [], -) { - return ManagedEndpointProvider.ManagedEndpointDnsClient.of({ - listCnameRecords: (hostname) => +function makePersistentTunnelClient(calls: TunnelCall[] = []) { + let tunnel: { readonly id: string; readonly name: string } | null = null; + return ManagedEndpointProvider.ManagedEndpointTunnelClient.of({ + list: (request) => Effect.sync(() => { - calls.push({ operation: "listCnameRecords", input: hostname }); - return records; + calls.push({ operation: "list", input: request }); + return { result: tunnel === null ? [] : [tunnel] }; }), - createCnameRecord: (request) => + create: (request) => Effect.sync(() => { - calls.push({ operation: "createCnameRecord", input: request }); + calls.push({ operation: "create", input: request }); + tunnel = { id: "tunnel-id", name: request.name }; + return tunnel; }), - updateCnameRecord: (dnsRecordId, request) => + putConfiguration: (tunnelId, tunnelConfig) => Effect.sync(() => { - calls.push({ operation: "updateCnameRecord", input: { dnsRecordId, request } }); + calls.push({ operation: "putConfiguration", input: { tunnelId, tunnelConfig } }); + }), + getToken: (tunnelId) => + Effect.sync(() => { + calls.push({ operation: "getToken", input: tunnelId }); + return "connector-token"; }), }); } -function providerLayer(tunnelClient = makeTunnelClient(), dnsClient = makeDnsClient()) { +function makeDnsClient( + calls: DnsCall[] = [], + records: ReadonlyArray<{ readonly id: string }> = [], +) { + let currentRecords = [...records]; + return ManagedEndpointProvider.ManagedEndpointDnsClient.of({ + listRecords: (hostname) => + Effect.sync(() => { + calls.push({ operation: "listRecords", input: hostname }); + return currentRecords; + }), + createRecord: (request) => + Effect.sync(() => { + calls.push({ operation: "createRecord", input: request }); + const record = { id: "created-record-id" }; + currentRecords = [record]; + return record; + }), + updateRecord: (dnsRecordId, request) => + Effect.sync(() => { + calls.push({ operation: "updateRecord", input: { dnsRecordId, request } }); + }), + deleteRecord: (dnsRecordId) => + Effect.sync(() => { + calls.push({ operation: "deleteRecord", input: dnsRecordId }); + currentRecords = currentRecords.filter((record) => record.id !== dnsRecordId); + }), + }); +} + +function makeAllocations(calls: AllocationCall[] = []) { + const allocations = new Map(); + return ManagedEndpointAllocations.ManagedEndpointAllocations.of({ + reserve: (input) => + Effect.sync(() => { + calls.push({ operation: "reserve", input }); + const allocation = allocations.get(allocationKey(input)) ?? { + ...input, + tunnelId: null, + dnsRecordId: null, + readyAt: null, + }; + allocations.set(allocationKey(input), allocation); + return allocation; + }), + recordTunnel: (input) => + Effect.sync(() => { + calls.push({ operation: "recordTunnel", input }); + const allocation = allocations.get(allocationKey(input)); + if (allocation !== undefined) { + allocations.set(allocationKey(input), { ...allocation, tunnelId: input.tunnelId }); + } + }), + recordDns: (input) => + Effect.sync(() => { + calls.push({ operation: "recordDns", input }); + const allocation = allocations.get(allocationKey(input)); + if (allocation !== undefined) { + allocations.set(allocationKey(input), { ...allocation, dnsRecordId: input.dnsRecordId }); + } + }), + markReady: (input) => + Effect.sync(() => { + calls.push({ operation: "markReady", input }); + const allocation = allocations.get(allocationKey(input)); + if (allocation !== undefined) { + allocations.set(allocationKey(input), { + ...allocation, + readyAt: "2026-06-02T00:00:00.000Z", + }); + } + }), + }); +} + +function providerLayer( + tunnelClient = makeTunnelClient(), + dnsClient = makeDnsClient(), + allocations = makeAllocations(), +) { return ManagedEndpointProvider.layer.pipe( Layer.provideMerge(NodeServices.layer), Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, config)), Layer.provide(Layer.succeed(ManagedEndpointProvider.ManagedEndpointTunnelClient, tunnelClient)), Layer.provide(Layer.succeed(ManagedEndpointProvider.ManagedEndpointDnsClient, dnsClient)), + Layer.provide( + Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, allocations), + ), ); } -function expectedManagedHostname(environmentId: string): string { +function expectedManagedHostname(environmentId: string, userId = "user_ABC"): string { const hash = NodeCrypto.createHash("sha256") - .update(`dev_julius:${environmentId}`) + .update(`dev_julius:${userId}:${environmentId}`) .digest("hex") .slice(0, 16); return `tunnels-dev-julius-${hash}.t3code.test`; } -function expectedManagedTunnelName(environmentId: string): string { +function expectedManagedTunnelName(environmentId: string, userId = "user_ABC"): string { const hash = NodeCrypto.createHash("sha256") - .update(`dev_julius:${environmentId}`) + .update(`dev_julius:${userId}:${environmentId}`) .digest("hex") .slice(0, 16); return `t3coderelay-managedendpoint-dev-julius-${hash}`; @@ -112,11 +209,13 @@ describe("ManagedEndpointProvider", () => { it.effect("provisions a Cloudflare tunnel endpoint and connector token", () => { const tunnelCalls: TunnelCall[] = []; const dnsCalls: DnsCall[] = []; + const allocationCalls: AllocationCall[] = []; return Effect.gen(function* () { const hostname = expectedManagedHostname("env_ABC"); const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; const result = yield* provider.provision({ + userId: "user_ABC", environmentId: "env_ABC", origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, }); @@ -135,9 +234,9 @@ describe("ManagedEndpointProvider", () => { }, }); expect(dnsCalls).toEqual([ - { operation: "listCnameRecords", input: hostname }, + { operation: "listRecords", input: hostname }, { - operation: "createCnameRecord", + operation: "createRecord", input: { type: "CNAME", name: hostname, @@ -168,7 +267,21 @@ describe("ManagedEndpointProvider", () => { name: expectedManagedTunnelName("env_ABC"), isDeleted: false, }); - }).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls), makeDnsClient(dnsCalls)))); + expect(allocationCalls.map((call) => call.operation)).toEqual([ + "reserve", + "recordTunnel", + "recordDns", + "markReady", + ]); + }).pipe( + Effect.provide( + providerLayer( + makeTunnelClient(tunnelCalls), + makeDnsClient(dnsCalls), + makeAllocations(allocationCalls), + ), + ), + ); }); it.effect("uses stage-scoped stable names without leaking unusual environment ids", () => { @@ -178,6 +291,7 @@ describe("ManagedEndpointProvider", () => { const environmentId = "ENV With Spaces/../Symbols!" + "x".repeat(80); const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; yield* provider.provision({ + userId: "user_ABC", environmentId, origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, }); @@ -224,6 +338,7 @@ describe("ManagedEndpointProvider", () => { return Effect.gen(function* () { const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; yield* provider.provision({ + userId: "user_ABC", environmentId: "env-ipv6", origin: { localHttpHost: "::1", localHttpPort: 3773 }, }); @@ -250,6 +365,7 @@ describe("ManagedEndpointProvider", () => { const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; const result = yield* Effect.result( provider.provision({ + userId: "user_ABC", environmentId: "env_ABC", origin: { localHttpHost: "192.168.1.10", localHttpPort: 3773 }, }), @@ -270,6 +386,7 @@ describe("ManagedEndpointProvider", () => { const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; const result = yield* Effect.result( provider.provision({ + userId: "user_ABC", environmentId: "env_ABC", origin: { localHttpHost: "127.0.0.1", localHttpPort: 65_536 }, }), @@ -283,19 +400,17 @@ describe("ManagedEndpointProvider", () => { }).pipe(Effect.provide(providerLayer(makeTunnelClient(), makeDnsClient(dnsCalls)))); }); - it.effect("updates an existing CNAME record through the DNS client", () => { + it.effect("reconciles an existing same-host DNS record through the DNS client", () => { const dnsCalls: DnsCall[] = []; return Effect.gen(function* () { const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; yield* provider.provision({ + userId: "user_ABC", environmentId: "env_ABC", origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, }); - expect(dnsCalls.map((call) => call.operation)).toEqual([ - "listCnameRecords", - "updateCnameRecord", - ]); + expect(dnsCalls.map((call) => call.operation)).toEqual(["listRecords", "updateRecord"]); expect(dnsCalls[1]?.input).toMatchObject({ dnsRecordId: "existing-record-id" }); }).pipe( Effect.provide( @@ -304,20 +419,140 @@ describe("ManagedEndpointProvider", () => { ); }); + it.effect("reuses checkpointed resources when provisioning is retried", () => { + const tunnelCalls: TunnelCall[] = []; + const dnsCalls: DnsCall[] = []; + const allocationCalls: AllocationCall[] = []; + const layer = providerLayer( + 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; + yield* provider.provision(request); + yield* provider.provision(request); + + expect(tunnelCalls.map((call) => call.operation)).toEqual([ + "list", + "create", + "putConfiguration", + "getToken", + "list", + "putConfiguration", + "getToken", + ]); + expect(dnsCalls.map((call) => call.operation)).toEqual([ + "listRecords", + "createRecord", + "listRecords", + "updateRecord", + ]); + expect(allocationCalls.map((call) => call.operation)).toEqual([ + "reserve", + "recordTunnel", + "recordDns", + "markReady", + "reserve", + "recordTunnel", + "recordDns", + "markReady", + ]); + }).pipe(Effect.provide(layer)); + }); + + it.effect("scopes managed endpoint resources by user", () => { + const tunnelCalls: TunnelCall[] = []; + + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + yield* provider.provision({ + userId: "user_ABC", + environmentId: "env_shared", + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }); + yield* provider.provision({ + userId: "user_DEF", + environmentId: "env_shared", + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }); + + expect( + tunnelCalls.filter((call) => call.operation === "list").map((call) => call.input), + ).toEqual([ + { name: expectedManagedTunnelName("env_shared", "user_ABC"), isDeleted: false }, + { name: expectedManagedTunnelName("env_shared", "user_DEF"), isDeleted: false }, + ]); + }).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls)))); + }); + + it.effect("recovers when DNS creation reports failure after the record became visible", () => { + const dnsCalls: DnsCall[] = []; + const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({ + cause: "ambiguous Cloudflare DNS response", + }); + let records: ReadonlyArray<{ readonly id: string }> = []; + const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({ + listRecords: (hostname) => + Effect.sync(() => { + dnsCalls.push({ operation: "listRecords", input: hostname }); + return records; + }), + createRecord: (request) => + Effect.gen(function* () { + dnsCalls.push({ operation: "createRecord", input: request }); + records = [{ id: "created-record-id" }]; + return yield* failure; + }), + updateRecord: (dnsRecordId, request) => + Effect.sync(() => { + dnsCalls.push({ operation: "updateRecord", input: { dnsRecordId, request } }); + }), + deleteRecord: (dnsRecordId) => + Effect.sync(() => { + dnsCalls.push({ operation: "deleteRecord", input: dnsRecordId }); + }), + }); + + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + yield* provider.provision({ + userId: "user_ABC", + environmentId: "env_ABC", + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }); + + expect(dnsCalls.map((call) => call.operation)).toEqual([ + "listRecords", + "createRecord", + "listRecords", + "updateRecord", + ]); + }).pipe(Effect.provide(providerLayer(makeTunnelClient(), dnsClient))); + }); + it.effect("fails provisioning when the DNS client fails", () => { const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({ cause: "Cloudflare DNS failure", }); const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({ - listCnameRecords: () => Effect.fail(failure), - createCnameRecord: () => Effect.die("unused"), - updateCnameRecord: () => Effect.die("unused"), + listRecords: () => Effect.fail(failure), + createRecord: () => Effect.die("unused"), + updateRecord: () => Effect.die("unused"), + deleteRecord: () => Effect.die("unused"), }); return Effect.gen(function* () { const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; const error = yield* Effect.flip( provider.provision({ + userId: "user_ABC", environmentId: "env_ABC", origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, }), diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 78ce919dc9..2106d89f47 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -22,6 +22,7 @@ import { managedEndpointHostname, managedEndpointTunnelName, } from "../deploymentConfig.ts"; +import { ManagedEndpointAllocations } from "./ManagedEndpointAllocations.ts"; export class ManagedEndpointProvisioningNotConfigured extends Data.TaggedError( "ManagedEndpointProvisioningNotConfigured", @@ -52,6 +53,7 @@ export interface ManagedEndpointProvisioningResult { export interface ManagedEndpointProviderShape { readonly provision: (input: { + readonly userId: string; readonly environmentId: string; readonly origin: RelayManagedEndpointOrigin; }) => Effect.Effect; @@ -117,16 +119,19 @@ export class ManagedEndpointDnsClientError extends Data.TaggedError( }> {} export interface ManagedEndpointDnsClientShape { - readonly listCnameRecords: ( + readonly listRecords: ( hostname: string, ) => Effect.Effect, ManagedEndpointDnsClientError>; - readonly createCnameRecord: ( + readonly createRecord: ( request: ManagedEndpointCnameRecordInput, - ) => Effect.Effect; - readonly updateCnameRecord: ( + ) => Effect.Effect<{ readonly id: string }, ManagedEndpointDnsClientError>; + readonly updateRecord: ( dnsRecordId: string, request: ManagedEndpointCnameRecordInput, ) => Effect.Effect; + readonly deleteRecord: ( + dnsRecordId: string, + ) => Effect.Effect; } export class ManagedEndpointDnsClient extends Context.Service< @@ -175,10 +180,61 @@ const make = Effect.gen(function* () { const crypto = yield* Crypto.Crypto; const tunnels = yield* ManagedEndpointTunnelClient; const dns = yield* ManagedEndpointDnsClient; + const allocations = yield* ManagedEndpointAllocations; + + const updateExistingDnsRecords = Effect.fnUntraced(function* ( + records: ReadonlyArray<{ readonly id: string }>, + preferredDnsRecordId: string | null, + dnsRecord: ManagedEndpointCnameRecordInput, + ) { + const keptRecord = records.find((record) => record.id === preferredDnsRecordId) ?? records[0]; + if (keptRecord === undefined) { + return null; + } + yield* Effect.forEach( + records, + (record) => (record.id === keptRecord.id ? Effect.void : dns.deleteRecord(record.id)), + { discard: true }, + ); + yield* dns.updateRecord(keptRecord.id, dnsRecord); + return keptRecord.id; + }); + + const ensureDnsRecord = Effect.fnUntraced(function* ( + hostname: string, + preferredDnsRecordId: string | null, + dnsRecord: ManagedEndpointCnameRecordInput, + ) { + const existingDnsRecords = yield* dns.listRecords(hostname); + const existingDnsRecordId = yield* updateExistingDnsRecords( + existingDnsRecords, + preferredDnsRecordId, + dnsRecord, + ); + if (existingDnsRecordId !== null) { + return existingDnsRecordId; + } + return yield* dns.createRecord(dnsRecord).pipe( + Effect.map((record) => record.id), + Effect.catch((createError) => + dns.listRecords(hostname).pipe( + Effect.flatMap((records) => + records.length > 0 + ? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord) + : Effect.fail(createError), + ), + Effect.flatMap((dnsRecordId) => + dnsRecordId === null ? Effect.fail(createError) : Effect.succeed(dnsRecordId), + ), + ), + ), + ); + }); return ManagedEndpointProvider.of({ provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) { yield* Effect.annotateCurrentSpan({ + "relay.user_id": input.userId, "relay.environment_id": input.environmentId, "relay.managed_endpoint.origin_host": input.origin.localHttpHost, "relay.managed_endpoint.origin_port": input.origin.localHttpPort, @@ -193,14 +249,23 @@ const make = Effect.gen(function* () { const environmentHash = yield* crypto .digest( "SHA-256", - new TextEncoder().encode(managedEndpointDigestInput(cf.namespace, input.environmentId)), + new TextEncoder().encode( + managedEndpointDigestInput(cf.namespace, input.userId, input.environmentId), + ), ) .pipe( Effect.map(Encoding.encodeHex), Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })), ); - const hostname = managedEndpointHostname(cf.namespace, cf.baseDomain, environmentHash); - const tunnelName = managedEndpointTunnelName(cf.namespace, environmentHash); + const allocation = yield* allocations + .reserve({ + userId: input.userId, + environmentId: input.environmentId, + hostname: managedEndpointHostname(cf.namespace, cf.baseDomain, environmentHash), + tunnelName: managedEndpointTunnelName(cf.namespace, environmentHash), + }) + .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause }))); + const { hostname, tunnelName } = allocation; const tunnel = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe( Effect.map((tunnels) => tunnels.result), @@ -218,6 +283,13 @@ const make = Effect.gen(function* () { ), Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })), ); + yield* allocations + .recordTunnel({ + userId: input.userId, + environmentId: input.environmentId, + tunnelId: tunnel.id, + }) + .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause }))); yield* tunnels .putConfiguration(tunnel.id, { @@ -231,12 +303,6 @@ const make = Effect.gen(function* () { }) .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause }))); - const existingDnsRecordId = yield* dns.listCnameRecords(hostname).pipe( - Effect.map(Arr.head), - Effect.map(Option.map((record) => record.id)), - Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })), - ); - const dnsRecord = { type: "CNAME", name: hostname, @@ -245,14 +311,26 @@ const make = Effect.gen(function* () { proxied: true, } as const; - yield* Option.match(existingDnsRecordId, { - onSome: (id) => dns.updateCnameRecord(id, dnsRecord), - onNone: () => dns.createCnameRecord(dnsRecord), - }).pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause }))); + const dnsRecordId = yield* ensureDnsRecord(hostname, allocation.dnsRecordId, dnsRecord).pipe( + Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })), + ); + yield* allocations + .recordDns({ + userId: input.userId, + environmentId: input.environmentId, + dnsRecordId, + }) + .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause }))); const connectorToken = yield* tunnels .getToken(tunnel.id) .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause }))); + yield* allocations + .markReady({ + userId: input.userId, + environmentId: input.environmentId, + }) + .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause }))); return { endpoint: { @@ -309,22 +387,33 @@ export const layerCloudflareBindings = ( Layer.succeed( ManagedEndpointDnsClient, ManagedEndpointDnsClient.of({ - listCnameRecords: (hostname) => - dnsClient.listDnsRecords({ type: "CNAME", name: { exact: hostname } }).pipe( - Effect.map((response) => response.result), + listRecords: (hostname) => + dnsClient.listDnsRecords({ name: { exact: hostname } }).pipe( + Effect.map((response) => + response.result.filter( + (record): record is typeof record & { readonly id: string } => + typeof record.id === "string", + ), + ), Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })), Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), - createCnameRecord: (request) => + createRecord: (request) => dnsClient.createDnsRecord(request).pipe( + Effect.map((response) => ({ id: response.id })), Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })), Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), - updateCnameRecord: (dnsRecordId, request) => + updateRecord: (dnsRecordId, request) => dnsClient.updateDnsRecord(dnsRecordId, request).pipe( Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })), Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), ), + deleteRecord: (dnsRecordId) => + dnsClient.deleteDnsRecord(dnsRecordId).pipe( + Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })), + Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext), + ), }), ), ), diff --git a/infra/relay/src/persistence/schema.ts b/infra/relay/src/persistence/schema.ts index cc77895bdc..ab3d2dfd97 100644 --- a/infra/relay/src/persistence/schema.ts +++ b/infra/relay/src/persistence/schema.ts @@ -83,6 +83,26 @@ export const relayEnvironmentLinks = pgTable( ], ); +export const relayManagedEndpointAllocations = pgTable( + "relay_managed_endpoint_allocations", + { + userId: varchar("user_id", { length: 191 }).notNull(), + environmentId: varchar("environment_id", { length: 191 }).notNull(), + hostname: text("hostname").notNull(), + tunnelId: varchar("tunnel_id", { length: 191 }), + tunnelName: text("tunnel_name").notNull(), + dnsRecordId: varchar("dns_record_id", { length: 191 }), + readyAt: varchar("ready_at", { length: 64 }), + createdAt: varchar("created_at", { length: 64 }).notNull(), + updatedAt: varchar("updated_at", { length: 64 }).notNull(), + }, + (table) => [ + primaryKey({ columns: [table.userId, table.environmentId] }), + uniqueIndex("idx_relay_managed_endpoint_allocations_hostname").on(table.hostname), + uniqueIndex("idx_relay_managed_endpoint_allocations_tunnel_name").on(table.tunnelName), + ], +); + export const relayEnvironmentCredentials = pgTable( "relay_environment_credentials", { diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts index 9e2ac934c3..43aa0ab457 100644 --- a/infra/relay/src/worker.ts +++ b/infra/relay/src/worker.ts @@ -38,6 +38,7 @@ import * as DpopProofs from "./auth/DpopProofs.ts"; import * as RelayTokens from "./auth/RelayTokens.ts"; import * as EnvironmentCredentials from "./environments/EnvironmentCredentials.ts"; import * as EnvironmentLinks from "./environments/EnvironmentLinks.ts"; +import * as ManagedEndpointAllocations from "./environments/ManagedEndpointAllocations.ts"; import * as LiveActivities from "./agentActivity/LiveActivities.ts"; import { RelayDb, RelayHyperdrive } from "./db.ts"; import { RelayApnsDeliveryDeadLetterQueue, RelayApnsDeliveryQueue } from "./queues.ts"; @@ -197,7 +198,12 @@ export default class Api extends Cloudflare.Worker()( Layer.provideMerge(AgentActivityRows.layer), Layer.provideMerge(Devices.layer), Layer.provideMerge(EnvironmentCredentials.layer), - Layer.provideMerge(EnvironmentLinks.layer), + Layer.provideMerge( + Layer.mergeAll( + EnvironmentLinks.layer, + ManagedEndpointAllocations.ManagedEndpointAllocations.layer, + ), + ), Layer.provideMerge(LiveActivities.layer), Layer.provideMerge(DeliveryAttempts.layer), Layer.provideMerge(RelayTokens.layer),