diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5b606c2a6..682c4d09a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,7 +15,7 @@ concurrency: env: # The forge release whose generator wrote apps/dashboard/src/client/forge. # Move it with the forge module, and regenerate if the check fails. - FORGE_CLI: github.com/xraph/forge/cmd/forge@v1.14.1 + FORGE_CLI: github.com/xraph/forge/cmd/forge@v1.14.3 jobs: go: diff --git a/apps/dashboard/specs/loomplane.asyncapi.json b/apps/dashboard/specs/loomplane.asyncapi.json index c15a8ec7a..6abcef7fb 100644 --- a/apps/dashboard/specs/loomplane.asyncapi.json +++ b/apps/dashboard/specs/loomplane.asyncapi.json @@ -293,15 +293,6 @@ "title": "environment.updated event", "summary": "SSE event: environment.updated" }, - "environment_cloud.updated": { - "payload": { - "$ref": "#/components/schemas/EnvironmentCloudEvent" - }, - "contentType": "text/event-stream", - "name": "environment_cloud.updated", - "title": "environment_cloud.updated event", - "summary": "SSE event: environment_cloud.updated" - }, "forge.gap": { "payload": { "$ref": "#/components/schemas/RealtimeForgeGap" @@ -392,6 +383,15 @@ "title": "project.updated event", "summary": "SSE event: project.updated" }, + "project_cloud.updated": { + "payload": { + "$ref": "#/components/schemas/ProjectCloudEvent" + }, + "contentType": "text/event-stream", + "name": "project_cloud.updated", + "title": "project_cloud.updated event", + "summary": "SSE event: project_cloud.updated" + }, "realtime.snapshot": { "payload": { "$ref": "#/components/schemas/RealtimeRealtimeSnapshot" @@ -639,7 +639,7 @@ "entityType": "CanaryVerdict", "intent": "upsert", "invalidates": [ - "CanaryReport" + "CanaryVerdict[]" ], "message": "canary_verdict.updated", "type": "github.com/xraph/loomplane/internal/deployments.CanaryVerdict" @@ -648,7 +648,7 @@ "entityType": "CanaryVerdict", "intent": "evict", "invalidates": [ - "CanaryReport" + "CanaryVerdict[]" ], "message": "canary_verdict.deleted", "type": "github.com/xraph/loomplane/internal/deployments.CanaryVerdict" @@ -708,21 +708,21 @@ "type": "github.com/xraph/loomplane/internal/cloudprofiles.Target" }, { - "entityType": "EnvironmentCloudEvent", + "entityType": "ProjectCloudEvent", "intent": "patch", "invalidates": [ - "EnvironmentCloud" + "DefaultCloud:{projectId}" ], - "message": "environment_cloud.updated", - "type": "github.com/xraph/loomplane/internal/cloudprofiles.EnvironmentCloudEvent" + "message": "project_cloud.updated", + "type": "github.com/xraph/loomplane/internal/cloudprofiles.ProjectCloudEvent" }, { "entityType": "CloudSyncEvent", "intent": "patch", "invalidates": [ - "Sync", + "Sync:{id}", "Sync[]", - "EnvironmentCloud" + "DefaultCloud:{projectId}" ], "message": "cloud_sync.updated", "type": "github.com/xraph/loomplane/internal/cloudprofiles.CloudSyncEvent" @@ -731,16 +731,13 @@ "entityType": "ClusterChange", "intent": "patch", "invalidates": [ - "CloudCluster", - "CloudClusterPage", - "CloudClusterOperation", - "CloudClusterOperationPage", - "Target", - "Target[]", - "Connection", + "CloudCluster:{resourceId}", + "CloudCluster[]", + "CloudClusterOperation:{operationId}", + "CloudClusterOperation[]", + "CloudprofilesTarget[]", "Connection[]", - "Profile", - "Profile[]" + "Profile:{cloudId}" ], "message": "cloud_cluster.updated", "type": "github.com/xraph/loomplane/internal/cloudinfra.ClusterChange" @@ -749,8 +746,8 @@ "entityType": "CapacityChange", "intent": "patch", "invalidates": [ - "CapacityPolicyView:{cloud_id}", - "CapacityUsage:{cloud_id}", + "CapacityPolicyView:{cloudId}", + "CapacityUsage:{cloudId}", "Expansion[]" ], "message": "cloud_capacity.updated", @@ -760,7 +757,7 @@ "entityType": "NotificationCreated", "intent": "upsert", "invalidates": [ - "NotificationList" + "Notification[]" ], "message": "notification.created", "type": "github.com/xraph/loomplane/internal/notifications.NotificationCreated" @@ -776,19 +773,18 @@ }, { "entityType": "TaskEvent", - "intent": "upsert", + "intent": "patch", "invalidates": [ - "AgentTask", - "AgentTask[]" + "Task:{id}" ], "message": "agent_task.updated", "type": "github.com/xraph/loomplane/internal/agentruns.TaskEvent" }, { "entityType": "TaskEvent", - "intent": "evict", + "intent": "patch", "invalidates": [ - "TaskEvent[]" + "Task:{id}" ], "message": "agent_task.deleted", "type": "github.com/xraph/loomplane/internal/agentruns.TaskEvent" @@ -797,8 +793,7 @@ "entityType": "Report", "intent": "upsert", "invalidates": [ - "AgentReport", - "AgentReport[]" + "Report[]" ], "message": "agent_report.updated", "type": "github.com/xraph/loomplane/internal/agentreports.Report" @@ -814,28 +809,29 @@ }, { "entityType": "RequestEvent", - "intent": "upsert", + "intent": "patch", "invalidates": [ - "AgentRequest", - "AgentRequest[]" + "Request:{id}", + "Request[]" ], "message": "agent_request.updated", "type": "github.com/xraph/loomplane/internal/agentrequests.RequestEvent" }, { "entityType": "RequestEvent", - "intent": "evict", + "intent": "patch", "invalidates": [ - "RequestEvent[]" + "Request:{id}", + "Request[]" ], "message": "agent_request.deleted", "type": "github.com/xraph/loomplane/internal/agentrequests.RequestEvent" }, { "entityType": "ReleaseReportEvent", - "intent": "upsert", + "intent": "patch", "invalidates": [ - "ReleaseReport", + "ReleaseReport:{id}", "ReleaseReport[]" ], "message": "release_report.updated", @@ -843,9 +839,9 @@ }, { "entityType": "ReleaseReportEvent", - "intent": "evict", + "intent": "patch", "invalidates": [ - "ReleaseReport", + "ReleaseReport:{id}", "ReleaseReport[]" ], "message": "release_report.deleted", @@ -1073,7 +1069,7 @@ "entityType": "CanaryVerdict", "intent": "upsert", "invalidates": [ - "CanaryReport" + "CanaryVerdict[]" ], "message": "canary_verdict.updated", "type": "github.com/xraph/loomplane/internal/deployments.CanaryVerdict" @@ -1082,7 +1078,7 @@ "entityType": "CanaryVerdict", "intent": "evict", "invalidates": [ - "CanaryReport" + "CanaryVerdict[]" ], "message": "canary_verdict.deleted", "type": "github.com/xraph/loomplane/internal/deployments.CanaryVerdict" @@ -1142,21 +1138,21 @@ "type": "github.com/xraph/loomplane/internal/cloudprofiles.Target" }, { - "entityType": "EnvironmentCloudEvent", + "entityType": "ProjectCloudEvent", "intent": "patch", "invalidates": [ - "EnvironmentCloud" + "DefaultCloud:{projectId}" ], - "message": "environment_cloud.updated", - "type": "github.com/xraph/loomplane/internal/cloudprofiles.EnvironmentCloudEvent" + "message": "project_cloud.updated", + "type": "github.com/xraph/loomplane/internal/cloudprofiles.ProjectCloudEvent" }, { "entityType": "CloudSyncEvent", "intent": "patch", "invalidates": [ - "Sync", + "Sync:{id}", "Sync[]", - "EnvironmentCloud" + "DefaultCloud:{projectId}" ], "message": "cloud_sync.updated", "type": "github.com/xraph/loomplane/internal/cloudprofiles.CloudSyncEvent" @@ -1165,16 +1161,13 @@ "entityType": "ClusterChange", "intent": "patch", "invalidates": [ - "CloudCluster", - "CloudClusterPage", - "CloudClusterOperation", - "CloudClusterOperationPage", - "Target", - "Target[]", - "Connection", + "CloudCluster:{resourceId}", + "CloudCluster[]", + "CloudClusterOperation:{operationId}", + "CloudClusterOperation[]", + "CloudprofilesTarget[]", "Connection[]", - "Profile", - "Profile[]" + "Profile:{cloudId}" ], "message": "cloud_cluster.updated", "type": "github.com/xraph/loomplane/internal/cloudinfra.ClusterChange" @@ -1183,8 +1176,8 @@ "entityType": "CapacityChange", "intent": "patch", "invalidates": [ - "CapacityPolicyView:{cloud_id}", - "CapacityUsage:{cloud_id}", + "CapacityPolicyView:{cloudId}", + "CapacityUsage:{cloudId}", "Expansion[]" ], "message": "cloud_capacity.updated", @@ -1194,7 +1187,7 @@ "entityType": "NotificationCreated", "intent": "upsert", "invalidates": [ - "NotificationList" + "Notification[]" ], "message": "notification.created", "type": "github.com/xraph/loomplane/internal/notifications.NotificationCreated" @@ -1210,19 +1203,18 @@ }, { "entityType": "TaskEvent", - "intent": "upsert", + "intent": "patch", "invalidates": [ - "AgentTask", - "AgentTask[]" + "Task:{id}" ], "message": "agent_task.updated", "type": "github.com/xraph/loomplane/internal/agentruns.TaskEvent" }, { "entityType": "TaskEvent", - "intent": "evict", + "intent": "patch", "invalidates": [ - "TaskEvent[]" + "Task:{id}" ], "message": "agent_task.deleted", "type": "github.com/xraph/loomplane/internal/agentruns.TaskEvent" @@ -1231,8 +1223,7 @@ "entityType": "Report", "intent": "upsert", "invalidates": [ - "AgentReport", - "AgentReport[]" + "Report[]" ], "message": "agent_report.updated", "type": "github.com/xraph/loomplane/internal/agentreports.Report" @@ -1248,28 +1239,29 @@ }, { "entityType": "RequestEvent", - "intent": "upsert", + "intent": "patch", "invalidates": [ - "AgentRequest", - "AgentRequest[]" + "Request:{id}", + "Request[]" ], "message": "agent_request.updated", "type": "github.com/xraph/loomplane/internal/agentrequests.RequestEvent" }, { "entityType": "RequestEvent", - "intent": "evict", + "intent": "patch", "invalidates": [ - "RequestEvent[]" + "Request:{id}", + "Request[]" ], "message": "agent_request.deleted", "type": "github.com/xraph/loomplane/internal/agentrequests.RequestEvent" }, { "entityType": "ReleaseReportEvent", - "intent": "upsert", + "intent": "patch", "invalidates": [ - "ReleaseReport", + "ReleaseReport:{id}", "ReleaseReport[]" ], "message": "release_report.updated", @@ -1277,9 +1269,9 @@ }, { "entityType": "ReleaseReportEvent", - "intent": "evict", + "intent": "patch", "invalidates": [ - "ReleaseReport", + "ReleaseReport:{id}", "ReleaseReport[]" ], "message": "release_report.deleted", @@ -1423,9 +1415,6 @@ { "$ref": "#/channels/api-v1-realtime-events/messages/environment.updated" }, - { - "$ref": "#/channels/api-v1-realtime-events/messages/environment_cloud.updated" - }, { "$ref": "#/channels/api-v1-realtime-events/messages/forge.gap" }, @@ -1456,6 +1445,9 @@ { "$ref": "#/channels/api-v1-realtime-events/messages/project.updated" }, + { + "$ref": "#/channels/api-v1-realtime-events/messages/project_cloud.updated" + }, { "$ref": "#/channels/api-v1-realtime-events/messages/realtime.snapshot" }, @@ -1903,16 +1895,12 @@ "template", "template_hash", "commit_sha", - "assignment_revision", "cloud_revision", "target_revision", "grant_revision", "target_name" ], "properties": { - "assignment_revision": { - "type": "integer" - }, "cloud_revision": { "type": "integer" }, @@ -2104,7 +2092,6 @@ "account_identity", "cloud_id", "cloud_revision", - "assignment_revision", "target_id", "target_revision", "target_name", @@ -2118,9 +2105,6 @@ "allocation": { "type": "string" }, - "assignment_revision": { - "type": "integer" - }, "cloud_id": { "type": "string" }, @@ -5996,34 +5980,6 @@ } } }, - "EnvironmentCloudEvent": { - "type": "object", - "required": [ - "org_id", - "project_id", - "environment_id", - "cloud_id", - "revision" - ], - "properties": { - "cloud_id": { - "type": "string", - "nullable": true - }, - "environment_id": { - "type": "string" - }, - "org_id": { - "type": "string" - }, - "project_id": { - "type": "string" - }, - "revision": { - "type": "integer" - } - } - }, "RealtimeForgeGap": { "type": "object", "required": [ @@ -6478,6 +6434,26 @@ } } }, + "ProjectCloudEvent": { + "type": "object", + "required": [ + "org_id", + "project_id", + "cloud_id" + ], + "properties": { + "cloud_id": { + "type": "string", + "nullable": true + }, + "org_id": { + "type": "string" + }, + "project_id": { + "type": "string" + } + } + }, "RealtimeRealtimeSnapshot": { "type": "object", "required": [ @@ -9019,40 +8995,6 @@ "title": "environment.updated event", "summary": "SSE event: environment.updated" }, - "api-v1-realtime-eventsenvironment_cloud.updated": { - "payload": { - "type": "object", - "required": [ - "org_id", - "project_id", - "environment_id", - "cloud_id", - "revision" - ], - "properties": { - "cloud_id": { - "type": "string", - "nullable": true - }, - "environment_id": { - "type": "string" - }, - "org_id": { - "type": "string" - }, - "project_id": { - "type": "string" - }, - "revision": { - "type": "integer" - } - } - }, - "contentType": "text/event-stream", - "name": "environment_cloud.updated", - "title": "environment_cloud.updated event", - "summary": "SSE event: environment_cloud.updated" - }, "api-v1-realtime-eventsforge.gap": { "payload": { "type": "object", @@ -9869,6 +9811,32 @@ "title": "project.updated event", "summary": "SSE event: project.updated" }, + "api-v1-realtime-eventsproject_cloud.updated": { + "payload": { + "type": "object", + "required": [ + "org_id", + "project_id", + "cloud_id" + ], + "properties": { + "cloud_id": { + "type": "string", + "nullable": true + }, + "org_id": { + "type": "string" + }, + "project_id": { + "type": "string" + } + } + }, + "contentType": "text/event-stream", + "name": "project_cloud.updated", + "title": "project_cloud.updated event", + "summary": "SSE event: project_cloud.updated" + }, "api-v1-realtime-eventsrealtime.snapshot": { "payload": { "type": "object", diff --git a/apps/dashboard/specs/loomplane.openapi.json b/apps/dashboard/specs/loomplane.openapi.json index aa1dec28a..e17cf99cb 100644 --- a/apps/dashboard/specs/loomplane.openapi.json +++ b/apps/dashboard/specs/loomplane.openapi.json @@ -820,10 +820,6 @@ }, "/api/v1/agent/tasks/{id}/stream": { "get": { - "tags": [ - "Agent" - ], - "summary": "Follow a task's events as they happen", "description": "Each agent.event carries one event, with its seq as the SSE id. Reconnect with Last-Event-ID (or after) set to the last seq you have, and the stream picks up at the next one. agent.end is the last frame: the task's final status.", "operationId": "agentTasks.stream", "parameters": [ @@ -846,9 +842,21 @@ ], "responses": { "200": { - "description": "Success" + "description": "Event stream", + "content": { + "text/event-stream": { + "schema": { + "type": "string" + } + } + } } - } + }, + "summary": "Follow a task's events as they happen", + "tags": [ + "Agent" + ], + "x-forge-protocol": "sse" } }, "/api/v1/agent/watcher": { @@ -1638,7 +1646,7 @@ ], "x-forge-entity": { "idField": "id", - "type": "BitbucketWorkspace" + "type": "BitbucketWorkspaceView" } } }, @@ -2648,11 +2656,10 @@ "Cloud clusters" ], "x-forge-invalidates": [ - "CloudCluster", - "CloudClusterOperation", - "CloudClusterPage", - "CloudClusterOperationPage", - "RuntimeAttachmentPage" + "CloudCluster[]", + "CloudClusterOperation[]", + "CloudCluster:{res.resourceId}", + "RuntimeAttachmentPage:{res.resourceId}" ] } }, @@ -2716,11 +2723,10 @@ "Cloud clusters" ], "x-forge-invalidates": [ - "CloudCluster", - "CloudClusterOperation", - "CloudClusterPage", - "CloudClusterOperationPage", - "RuntimeAttachmentPage" + "CloudCluster[]", + "CloudClusterOperation[]", + "CloudCluster:{res.resourceId}", + "RuntimeAttachmentPage:{res.resourceId}" ] } }, @@ -2784,11 +2790,10 @@ "Cloud clusters" ], "x-forge-invalidates": [ - "CloudCluster", - "CloudClusterOperation", - "CloudClusterPage", - "CloudClusterOperationPage", - "RuntimeAttachmentPage" + "CloudCluster[]", + "CloudClusterOperation[]", + "CloudCluster:{res.resourceId}", + "RuntimeAttachmentPage:{res.resourceId}" ] } }, @@ -3009,11 +3014,8 @@ "Cloud clusters" ], "x-forge-invalidates": [ - "CloudCluster", - "CloudClusterOperation", - "CloudClusterPage", - "CloudClusterOperationPage", - "RuntimeAttachmentPage" + "CloudCluster[]", + "CloudClusterOperation[]" ] } }, @@ -3327,11 +3329,10 @@ "Cloud clusters" ], "x-forge-invalidates": [ - "CloudCluster", - "CloudClusterOperation", - "CloudClusterPage", - "CloudClusterOperationPage", - "RuntimeAttachmentPage" + "CloudCluster[]", + "CloudClusterOperation[]", + "CloudCluster:{res.resourceId}", + "RuntimeAttachmentPage:{res.resourceId}" ] } }, @@ -3406,11 +3407,10 @@ "Cloud clusters" ], "x-forge-invalidates": [ - "CloudCluster", - "CloudClusterOperation", - "CloudClusterPage", - "CloudClusterOperationPage", - "RuntimeAttachmentPage" + "CloudCluster[]", + "CloudClusterOperation[]", + "CloudCluster:{res.resourceId}", + "RuntimeAttachmentPage:{res.resourceId}" ] } }, @@ -11304,6 +11304,81 @@ } } }, + "/api/v1/projects/{id}/default-cloud": { + "get": { + "tags": [ + "Clouds" + ], + "summary": "defaultCloud.get", + "operationId": "defaultCloud.get", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Path parameter: id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Result", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DefaultCloud" + } + } + } + } + } + } + }, + "/api/v1/projects/{id}/default-cloud/preview": { + "post": { + "tags": [ + "Clouds" + ], + "summary": "defaultCloud.preview", + "operationId": "defaultCloud.preview", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Path parameter: id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "Request body", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DefaultCloudInputBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Result", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Preview" + } + } + } + } + } + } + }, "/api/v1/projects/{id}/deletion": { "get": { "tags": [ @@ -11503,99 +11578,6 @@ } } }, - "/api/v1/projects/{id}/environments/{environmentId}/cloud": { - "get": { - "tags": [ - "Clouds" - ], - "summary": "environmentClouds.get", - "operationId": "environmentClouds.get", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "Path parameter: id", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "environmentId", - "in": "path", - "description": "Path parameter: environmentId", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Result", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EnvironmentCloud" - } - } - } - } - } - } - }, - "/api/v1/projects/{id}/environments/{environmentId}/cloud/preview": { - "post": { - "tags": [ - "Clouds" - ], - "summary": "environmentClouds.preview", - "operationId": "environmentClouds.preview", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "Path parameter: id", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "environmentId", - "in": "path", - "description": "Path parameter: environmentId", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "description": "Request body", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EnvironmentCloudInputBody" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Result", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Preview" - } - } - } - } - } - } - }, "/api/v1/projects/{id}/environments/{environmentId}/provider-environments/retry": { "post": { "tags": [ @@ -13051,7 +13033,7 @@ ], "x-forge-entity": { "idField": "id", - "type": "Source" + "type": "DiscoverySource" } }, "patch": { @@ -18178,9 +18160,6 @@ }, "/api/v1/realtime/events": { "get": { - "tags": [ - "Realtime" - ], "operationId": "realtime.events", "parameters": [ { @@ -18214,9 +18193,20 @@ ], "responses": { "200": { - "description": "Success" + "description": "Event stream", + "content": { + "text/event-stream": { + "schema": { + "type": "string" + } + } + } } - } + }, + "tags": [ + "Realtime" + ], + "x-forge-protocol": "sse" } }, "/api/v1/realtime/snapshot": { @@ -18272,9 +18262,6 @@ }, "/api/v1/realtime/ws": { "get": { - "tags": [ - "Realtime" - ], "operationId": "realtime.ws", "parameters": [ { @@ -18307,10 +18294,14 @@ } ], "responses": { - "200": { - "description": "Success" + "101": { + "description": "Switching Protocols" } - } + }, + "tags": [ + "Realtime" + ], + "x-forge-protocol": "websocket" } }, "/api/v1/release-reports/{id}": { @@ -20430,51 +20421,6 @@ } } }, - "Assignment": { - "type": "object", - "required": [ - "grant_revision", - "cloud_revision", - "org_id", - "project_id", - "environment_id", - "cloud_id", - "revision", - "targets" - ], - "properties": { - "cloud_id": { - "type": "string" - }, - "cloud_revision": { - "type": "integer" - }, - "default_placement": { - "$ref": "#/components/schemas/DefaultPlacement" - }, - "environment_id": { - "type": "string" - }, - "grant_revision": { - "type": "integer" - }, - "org_id": { - "type": "string" - }, - "project_id": { - "type": "string" - }, - "revision": { - "type": "integer" - }, - "targets": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CloudprofilesTarget" - } - } - } - }, "AttachDefaults": { "type": "object", "required": [ @@ -21630,16 +21576,12 @@ "template", "template_hash", "commit_sha", - "assignment_revision", "cloud_revision", "target_revision", "grant_revision", "target_name" ], "properties": { - "assignment_revision": { - "type": "integer" - }, "cloud_revision": { "type": "integer" }, @@ -22240,12 +22182,12 @@ "default": { "type": "boolean" }, - "environment_id": { - "type": "string" - }, "pool_id": { "type": "string" }, + "project_default": { + "type": "boolean" + }, "provider": { "type": "string" }, @@ -22279,12 +22221,12 @@ "default": { "type": "boolean" }, - "environment_id": { - "type": "string" - }, "pool_id": { "type": "string" }, + "project_default": { + "type": "boolean" + }, "provider": { "type": "string" }, @@ -23071,7 +23013,6 @@ "account_identity", "cloud_id", "cloud_revision", - "assignment_revision", "target_id", "target_revision", "target_name", @@ -23085,9 +23026,6 @@ "allocation": { "type": "string" }, - "assignment_revision": { - "type": "integer" - }, "cloud_id": { "type": "string" }, @@ -25914,6 +25852,52 @@ } } }, + "DefaultCloud": { + "type": "object", + "required": [ + "project_id", + "cloud", + "revision" + ], + "properties": { + "cloud": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProjectCloud" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + }, + "project_id": { + "type": "string", + "x-forge-id": true + }, + "revision": { + "type": "integer" + } + } + }, + "DefaultCloudInputBody": { + "type": "object", + "required": [ + "cloud_id", + "revision" + ], + "properties": { + "cloud_id": { + "type": "string" + }, + "revision": { + "type": "integer" + } + } + }, "DefaultPlacement": { "type": "object", "required": [ @@ -27100,6 +27084,12 @@ "source" ], "properties": { + "cloud": { + "type": "string" + }, + "cloud_target": { + "type": "string" + }, "enabled_in": { "type": "string" }, @@ -27182,6 +27172,9 @@ "build": { "$ref": "#/components/schemas/Build" }, + "cloud": { + "type": "string" + }, "cloud_sql_network": { "$ref": "#/components/schemas/CloudSQLApplicationNetwork" }, @@ -27762,47 +27755,6 @@ } } }, - "EnvironmentCloud": { - "type": "object", - "required": [ - "assignment", - "revision" - ], - "properties": { - "assignment": { - "oneOf": [ - { - "$ref": "#/components/schemas/Assignment" - }, - { - "type": "object", - "nullable": true, - "enum": [ - null - ] - } - ] - }, - "revision": { - "type": "integer" - } - } - }, - "EnvironmentCloudInputBody": { - "type": "object", - "required": [ - "cloud_id", - "revision" - ], - "properties": { - "cloud_id": { - "type": "string" - }, - "revision": { - "type": "integer" - } - } - }, "EnvironmentConnections": { "type": "object", "required": [ @@ -27841,11 +27793,11 @@ "project_name", "environment_id", "environment_name", - "assigned", + "default", "placements" ], "properties": { - "assigned": { + "default": { "type": "boolean" }, "environment_id": { @@ -33217,6 +33169,66 @@ } } }, + "NewServiceInput": { + "type": "object", + "required": [ + "name", + "source" + ], + "properties": { + "cloud": { + "type": "string" + }, + "cloud_target": { + "type": "string" + }, + "enabled_in": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "name": { + "type": "string" + }, + "needed_by": { + "type": "array", + "items": { + "type": "string" + } + }, + "needs": { + "type": "array", + "items": { + "type": "string" + } + }, + "only": { + "type": "boolean" + }, + "port": { + "type": "integer" + }, + "provider": { + "type": "string" + }, + "public": { + "type": "boolean" + }, + "region": { + "type": "string" + }, + "repo": { + "type": "string" + }, + "source": { + "type": "string" + }, + "target": { + "type": "string" + } + } + }, "Node": { "type": "object", "required": [ @@ -35627,8 +35639,8 @@ "after": { "$ref": "#/components/schemas/CloudprofilesTarget" }, - "after_assignment": { - "$ref": "#/components/schemas/Assignment" + "after_cloud": { + "$ref": "#/components/schemas/ProjectCloud" }, "after_default": { "$ref": "#/components/schemas/DefaultPlacement" @@ -35636,8 +35648,8 @@ "before": { "$ref": "#/components/schemas/CloudprofilesTarget" }, - "before_assignment": { - "$ref": "#/components/schemas/Assignment" + "before_cloud": { + "$ref": "#/components/schemas/ProjectCloud" }, "before_default": { "$ref": "#/components/schemas/DefaultPlacement" @@ -35843,6 +35855,51 @@ } } }, + "ProjectCloud": { + "type": "object", + "required": [ + "grant_revision", + "cloud_revision", + "org_id", + "project_id", + "cloud_id", + "name", + "default", + "targets" + ], + "properties": { + "cloud_id": { + "type": "string" + }, + "cloud_revision": { + "type": "integer" + }, + "default": { + "type": "boolean" + }, + "default_placement": { + "$ref": "#/components/schemas/DefaultPlacement" + }, + "grant_revision": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "org_id": { + "type": "string" + }, + "project_id": { + "type": "string" + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CloudprofilesTarget" + } + } + } + }, "ProjectDomain": { "type": "object", "required": [ @@ -35902,12 +35959,16 @@ "project_id", "target_ids", "revision", - "revoked" + "revoked", + "default" ], "properties": { "cloud_id": { "type": "string" }, + "default": { + "type": "boolean" + }, "org_id": { "type": "string" }, @@ -41235,6 +41296,71 @@ } } }, + "ServiceSuggestion": { + "type": "object", + "required": [ + "id", + "kind", + "ecosystem", + "path", + "service" + ], + "properties": { + "ecosystem": { + "type": "string" + }, + "env": { + "type": "array", + "items": { + "type": "string" + } + }, + "framework": { + "type": "string" + }, + "id": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "path": { + "type": "string" + }, + "ports": { + "type": "array", + "items": { + "type": "integer" + } + }, + "service": { + "$ref": "#/components/schemas/NewServiceInput" + } + } + }, + "ServiceSuggestions": { + "type": "object", + "required": [ + "project_id", + "analyzed", + "services" + ], + "properties": { + "analyzed": { + "type": "boolean" + }, + "project_id": { + "type": "string", + "x-forge-id": true + }, + "services": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ServiceSuggestion" + } + } + } + }, "ServiceTraffic": { "type": "object", "required": [ @@ -44091,125 +44217,6 @@ "type": "string" } } - }, - "NewServiceInput": { - "type": "object", - "required": [ - "name", - "source" - ], - "properties": { - "enabled_in": { - "type": "string" - }, - "kind": { - "type": "string" - }, - "name": { - "type": "string" - }, - "needed_by": { - "type": "array", - "items": { - "type": "string" - } - }, - "needs": { - "type": "array", - "items": { - "type": "string" - } - }, - "only": { - "type": "boolean" - }, - "port": { - "type": "integer" - }, - "provider": { - "type": "string" - }, - "public": { - "type": "boolean" - }, - "region": { - "type": "string" - }, - "repo": { - "type": "string" - }, - "source": { - "type": "string" - }, - "target": { - "type": "string" - } - } - }, - "ServiceSuggestion": { - "type": "object", - "required": [ - "id", - "kind", - "ecosystem", - "path", - "service" - ], - "properties": { - "ecosystem": { - "type": "string" - }, - "env": { - "type": "array", - "items": { - "type": "string" - } - }, - "framework": { - "type": "string" - }, - "id": { - "type": "string" - }, - "kind": { - "type": "string" - }, - "path": { - "type": "string" - }, - "ports": { - "type": "array", - "items": { - "type": "integer" - } - }, - "service": { - "$ref": "#/components/schemas/NewServiceInput" - } - } - }, - "ServiceSuggestions": { - "type": "object", - "required": [ - "project_id", - "analyzed", - "services" - ], - "properties": { - "analyzed": { - "type": "boolean" - }, - "project_id": { - "type": "string", - "x-forge-id": true - }, - "services": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ServiceSuggestion" - } - } - } } }, "securitySchemes": { diff --git a/apps/dashboard/src/client/cache-contract.test.ts b/apps/dashboard/src/client/cache-contract.test.ts new file mode 100644 index 000000000..7f7c66bae --- /dev/null +++ b/apps/dashboard/src/client/cache-contract.test.ts @@ -0,0 +1,104 @@ +// The generated cache contract only refreshes a screen when a write or a live +// event names a tag some query carries. A tag nothing carries is silent: the +// write lands, and the page stays stale until a reload. This test fails on +// every such tag, so a route declaring one is caught in review rather than by +// someone wondering why the page didn't update. +// +// Matching is exact, as it is in @forge-go/client-core: `Order` reaches only +// a query carrying `Order`, never `Order:7` or `Order[]`. +import { describe, expect, it } from "vitest" + +import { entities } from "@/client/forge/loomplane/entities" +import { ops } from "@/client/forge/loomplane/ops" +import { streams } from "@/client/forge/loomplane/stream-bindings" + +type Op = { + method: string + rootType?: string + provides: readonly string[] + invalidates: readonly string[] +} +type Row = { idField?: string; fields?: Record } + +const all = Object.entries(ops as unknown as Record) +const table = entities as unknown as Record +const reads = all.filter(([, op]) => op.method === "GET") + +/** shape turns a tag template into what it matches: `Order:{id}` → `Order:*`. */ +const shape = (tag: string) => tag.replace(/\{[^}]+\}/g, "*") + +// What a read carries: its declared tags, and an item tag for every entity its +// response can hold, since a settled query also carries the keys it normalized. +const carried = new Set() +const reach = (type: string, seen: Set) => { + if (seen.has(type)) return + seen.add(type) + const row = table[type] + if (!row) return + if (row.idField) carried.add(`${type}:*`) + for (const next of Object.values(row.fields ?? {})) reach(next, seen) +} +for (const [, op] of reads) { + for (const tag of op.provides) carried.add(shape(tag)) + if (op.rootType) reach(op.rootType, new Set()) +} + +// Tags known to reach nothing today, each with why. Shrink this list; never +// grow it without a reason a reviewer would accept. +const known: Record = { + "Watch[]": "release watches are only read one at a time, by deployment", + "Collection[]": + "build output collections are delivered to the log view, not listed", + "Preview[]": "previews are immutable and never listed", + "Task[]": "agent tasks are only read one at a time", + "EntryDetail[]": "model registry entries are only read one at a time", + "CapacityPolicyView[]": "a capacity policy is read per Cloud", + "CapacityUsage[]": "capacity usage is read per Cloud", + "ClusterCapacity[]": "cluster capacity is read per cluster", + ManagedRegistryView: "the managed registry read has no identity", + "ProviderResourceSync[]": "resource syncs are never listed", + "GitLabConnectionView[]": + "GitLab connections are read inside the GitLab status", + "GitLabHostView[]": "GitLab hosts are read inside the GitLab status", + "NativeRetentionPolicy[]": + "carried by the hand-written read in client/native-retention-policies.ts", + "TLSRenewalAuthority[]": "renewal authorities are never listed", + "Host[]": "platform hosts are listed as HostView", + "RouteSummary[]": "gateway routes are read inside the gateway", + "GroupVerificationResult[]": "verification results are never listed", + "MemberPrerequisite[]": "prerequisites are never listed", + "FleetOperation[]": "fleet operations are read one at a time", + "ProviderResource[]": "the provider resource list has no envelope yet", + "PushDevice[]": "push devices are never listed", + "RetentionPolicy[]": + "carried by the hand-written read in client/retention-policies.ts", +} + +function dead(tags: readonly string[]): string[] { + return tags.map(shape).filter((tag) => !carried.has(tag) && !known[tag]) +} + +describe("cache contract", () => { + it("every write invalidates only tags some read carries", () => { + const misses = all + .filter(([, op]) => op.method !== "GET") + .flatMap(([name, op]) => + dead(op.invalidates).map((tag) => `${name}: ${tag}`) + ) + expect(misses).toEqual([]) + }) + + it("every live event invalidates only tags some read carries", () => { + const misses = streams.flatMap((b) => + b.kind === "entity" + ? dead(b.invalidates ?? []).map((tag) => `${b.message}: ${tag}`) + : [] + ) + expect([...new Set(misses)]).toEqual([]) + }) + + it("every known gap is still a gap", () => { + // A fixed gap left on the list would hide its own regression. + expect(Object.keys(known).filter((tag) => carried.has(tag))).toEqual([]) + }) +}) diff --git a/apps/dashboard/src/client/canary.ts b/apps/dashboard/src/client/canary.ts index c108b2fe6..3da26fe53 100644 --- a/apps/dashboard/src/client/canary.ts +++ b/apps/dashboard/src/client/canary.ts @@ -2,13 +2,13 @@ import { query } from "@forge-go/client-core" import { op_deployments_canary } from "@/client/forge/loomplane/ops/deployments.canary" import type { CanaryReport } from "@/client/forge/loomplane/types" +import { deploymentLists } from "@/client/tags" -// The generated route provides only verdict entities, but the stream -// invalidates the CanaryReport tag when a verdict lands, and a status change -// with no new verdict (a rollback that couldn't finish, the next weight, a -// promotion) arrives as deployment.updated. Providing both tags keeps the -// report current on either event. -const provides = ["CanaryReport", "Deployment[]"] +// The generated route provides the verdicts, which a canary_verdict event +// reaches. A status change with no new verdict (a rollback that couldn't +// finish, the next weight, a promotion) arrives as deployment.updated, which +// invalidates the deployment lists, so the report carries that tag too. +const provides = [deploymentLists] export const useDeploymentsCanary = query({ ...op_deployments_canary, provides: [...op_deployments_canary.provides, ...provides], diff --git a/apps/dashboard/src/client/failed-cleanup.ts b/apps/dashboard/src/client/failed-cleanup.ts index 6a17bbde5..8d5833f48 100644 --- a/apps/dashboard/src/client/failed-cleanup.ts +++ b/apps/dashboard/src/client/failed-cleanup.ts @@ -8,12 +8,13 @@ import type { CleanupReview, FailedCleanup, } from "@/client/forge/loomplane/types" +import { deploymentItem, deploymentLists } from "@/client/tags" export type { CleanupReview } from "@/client/forge/loomplane/types" // An absent cleanup still depends on its next acceptance. The operation is // keyed by deployment rather than by a serving resource entity. const provides = ["FailedCleanup:{id}"] -const invalidates = [...provides, "Deployment:{id}", "Deployment[]"] +const invalidates = [...provides, deploymentItem, deploymentLists] export const useFailedCleanup = query({ ...op_deployments_cleanup, provides, diff --git a/apps/dashboard/src/client/forge/authsome/rest.ts b/apps/dashboard/src/client/forge/authsome/rest.ts index d9a25544f..856cf291a 100644 --- a/apps/dashboard/src/client/forge/authsome/rest.ts +++ b/apps/dashboard/src/client/forge/authsome/rest.ts @@ -49,8 +49,8 @@ export class RESTClient extends Client { public readonly checkOrgSlug = async (appId?: string, slug?: string, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/authsome/v1/orgs/check-slug`; const queryParams: Record = {}; - queryParams['app_id'] = appId; - queryParams['slug'] = slug; + queryParams["app_id"] = appId; + queryParams["slug"] = slug; const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { __path += '?' + queryString; @@ -165,10 +165,10 @@ export class RESTClient extends Client { let __path = `/authsome/v1/orgs/${encodeURIComponent(String(orgId))}/invitations`; const queryParams: Record = {}; if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -193,10 +193,10 @@ export class RESTClient extends Client { let __path = `/authsome/v1/orgs/${encodeURIComponent(String(orgId))}/members`; const queryParams: Record = {}; if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -221,10 +221,10 @@ export class RESTClient extends Client { let __path = `/authsome/v1/orgs`; const queryParams: Record = {}; if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { diff --git a/apps/dashboard/src/client/forge/loomplane/README.md b/apps/dashboard/src/client/forge/loomplane/README.md index 53c09fd83..a9dfa05f9 100644 --- a/apps/dashboard/src/client/forge/loomplane/README.md +++ b/apps/dashboard/src/client/forge/loomplane/README.md @@ -53,8 +53,8 @@ This API supports the following authentication methods: ## API Overview -- **Total Endpoints**: 456 -- **REST Endpoints**: 453 +- **Total Endpoints**: 453 +- **REST Endpoints**: 450 - **WebSocket Endpoints**: 1 - **SSE Endpoints**: 2 diff --git a/apps/dashboard/src/client/forge/loomplane/codecs.ts b/apps/dashboard/src/client/forge/loomplane/codecs.ts index 85ec781a3..c19f0f534 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs.ts @@ -64,8 +64,6 @@ export const CODECS: Record = { "ApplyInputBody": {"kind": "object", "fields": {"review": {"ts": "review"}}, "required": ["review"]}, "ApproveExpansionInputBody": {"kind": "object", "fields": {"expected_revision": {"ts": "expectedRevision"}}, "required": ["expected_revision"]}, "ArtifactChoice": {"kind": "object", "fields": {"from": {"ts": "from"}, "reason": {"ts": "reason"}, "reference": {"ts": "reference"}, "reused": {"ts": "reused"}, "revision": {"ts": "revision"}, "service": {"ts": "service"}}, "required": ["reused", "service"]}, - "Assignment": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "cloud_revision": {"ts": "cloudRevision"}, "default_placement": {"ts": "defaultPlacement", "codec": () => CODECS["DefaultPlacement"]}, "environment_id": {"ts": "environmentId"}, "grant_revision": {"ts": "grantRevision"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "revision": {"ts": "revision"}, "targets": {"ts": "targets", "codec": () => CODECS["Assignment.targets"]}}, "required": ["cloud_id", "cloud_revision", "environment_id", "grant_revision", "org_id", "project_id", "revision", "targets"]}, - "Assignment.targets": {"kind": "array", "items": () => CODECS["CloudprofilesTarget"]}, "AttachDefaults": {"kind": "object", "fields": {"blocked_path_prefixes": {"ts": "blockedPathPrefixes", "codec": () => CODECS["AttachDefaults.blocked_path_prefixes"]}, "cloud_id": {"ts": "cloudId"}, "environment_id": {"ts": "environmentId"}, "port": {"ts": "port"}, "service": {"ts": "service"}}, "required": ["blocked_path_prefixes", "environment_id", "port", "service"]}, "AttachDefaults.blocked_path_prefixes": {"kind": "array"}, "AttachmentInput": {"kind": "object", "fields": {"adopt_namespace": {"ts": "adoptNamespace"}, "cloud_revision": {"ts": "cloudRevision"}, "endpoint_fingerprint": {"ts": "endpointFingerprint"}, "grant_revision": {"ts": "grantRevision"}, "namespace": {"ts": "namespace"}, "namespace_uid": {"ts": "namespaceUid"}, "prerequisites": {"ts": "prerequisites", "codec": () => CODECS["AttachmentPrerequisites"]}, "project_id": {"ts": "projectId"}, "resource_revision": {"ts": "resourceRevision"}, "runtime_access": {"ts": "runtimeAccess", "codec": () => CODECS["RuntimeAccessProfile"]}, "service_account_name": {"ts": "serviceAccountName"}, "target_slug": {"ts": "targetSlug"}, "trust_fingerprint": {"ts": "trustFingerprint"}}, "required": ["adopt_namespace", "cloud_revision", "endpoint_fingerprint", "grant_revision", "namespace", "prerequisites", "project_id", "resource_revision", "service_account_name", "target_slug", "trust_fingerprint"]}, @@ -124,7 +122,7 @@ export const CODECS: Record = { "CapacityBudget": {"kind": "object", "fields": {"horizon_seconds": {"ts": "horizonSeconds"}, "max_horizon_micro_usd": {"ts": "maxHorizonMicroUsd"}, "max_hourly_micro_usd": {"ts": "maxHourlyMicroUsd"}}, "required": ["horizon_seconds", "max_horizon_micro_usd", "max_hourly_micro_usd"]}, "CapacityChange": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "entity_id": {"ts": "entityId"}, "kind": {"ts": "kind"}, "org_id": {"ts": "orgId"}, "revision": {"ts": "revision"}, "status": {"ts": "status"}}, "required": ["cloud_id", "entity_id", "kind", "org_id", "revision"]}, "CapacityDemand": {"kind": "object", "fields": {"architecture": {"ts": "architecture"}, "cloud_id": {"ts": "cloudId"}, "environment_id": {"ts": "environmentId"}, "intent_hash": {"ts": "intentHash"}, "local_data": {"ts": "localData"}, "org_id": {"ts": "orgId"}, "plan_id": {"ts": "planId"}, "policy_revision": {"ts": "policyRevision"}, "pool_id": {"ts": "poolId"}, "project_id": {"ts": "projectId"}, "resources": {"ts": "resources", "codec": () => CODECS["ResourceVector"]}, "service": {"ts": "service"}, "sticky_server_id": {"ts": "stickyServerId"}, "target_id": {"ts": "targetId"}}, "required": ["architecture", "cloud_id", "environment_id", "intent_hash", "local_data", "org_id", "plan_id", "policy_revision", "pool_id", "project_id", "resources", "service", "sticky_server_id", "target_id"]}, - "CapacityIntent": {"kind": "object", "fields": {"assignment_revision": {"ts": "assignmentRevision"}, "cloud_revision": {"ts": "cloudRevision"}, "commit_sha": {"ts": "commitSha"}, "demand": {"ts": "demand", "codec": () => CODECS["CapacityDemand"]}, "grant_revision": {"ts": "grantRevision"}, "target_name": {"ts": "targetName"}, "target_revision": {"ts": "targetRevision"}, "template": {"ts": "template", "codec": () => CODECS["PoolExpansionPolicy"]}, "template_hash": {"ts": "templateHash"}}, "required": ["assignment_revision", "cloud_revision", "commit_sha", "demand", "grant_revision", "target_name", "target_revision", "template", "template_hash"]}, + "CapacityIntent": {"kind": "object", "fields": {"cloud_revision": {"ts": "cloudRevision"}, "commit_sha": {"ts": "commitSha"}, "demand": {"ts": "demand", "codec": () => CODECS["CapacityDemand"]}, "grant_revision": {"ts": "grantRevision"}, "target_name": {"ts": "targetName"}, "target_revision": {"ts": "targetRevision"}, "template": {"ts": "template", "codec": () => CODECS["PoolExpansionPolicy"]}, "template_hash": {"ts": "templateHash"}}, "required": ["cloud_revision", "commit_sha", "demand", "grant_revision", "target_name", "target_revision", "template", "template_hash"]}, "CapacityObservation": {"kind": "object", "fields": {"checked_at": {"ts": "checkedAt"}, "cpu_millis": {"ts": "cpuMillis"}, "free_storage_bytes": {"ts": "freeStorageBytes"}, "memory_bytes": {"ts": "memoryBytes"}, "storage_bytes": {"ts": "storageBytes"}}, "required": ["checked_at"]}, "CapacityPolicy": {"kind": "object", "fields": {"budget": {"ts": "budget", "codec": () => CODECS["CapacityBudget"]}, "cloud_id": {"ts": "cloudId"}, "enabled": {"ts": "enabled"}, "frontend_limits": {"ts": "frontendLimits", "codec": () => CODECS["CapacityPolicy.frontend_limits"]}, "gpu_limits": {"ts": "gpuLimits", "codec": () => CODECS["CapacityPolicy.gpu_limits"]}, "limits": {"ts": "limits", "codec": () => CODECS["ResourceVector"]}, "org_id": {"ts": "orgId"}, "pools": {"ts": "pools", "codec": () => CODECS["CapacityPolicy.pools"]}, "require_expansion_approval": {"ts": "requireExpansionApproval"}, "revision": {"ts": "revision"}}, "required": ["cloud_id", "enabled", "frontend_limits", "limits", "org_id", "pools", "require_expansion_approval", "revision"]}, "CapacityPolicy.frontend_limits": {"kind": "array", "items": () => CODECS["FrontendLimit"]}, @@ -157,8 +155,8 @@ export const CODECS: Record = { "CertificateView": {"kind": "object", "fields": {"days_left": {"ts": "daysLeft"}, "expires_at": {"ts": "expiresAt"}, "rotation": {"ts": "rotation"}, "warning": {"ts": "warning"}}, "required": ["rotation", "warning"]}, "ChallengeCredentialInputBody": {"kind": "object", "fields": {"connection_id": {"ts": "connectionId"}, "revision": {"ts": "revision"}}, "required": ["connection_id", "revision"]}, "Change": {"kind": "object", "fields": {"field": {"ts": "field"}, "from": {"ts": "from"}, "to": {"ts": "to"}}, "required": ["field", "from", "to"]}, - "ChangeInput": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "connection_id": {"ts": "connectionId"}, "default": {"ts": "default"}, "environment_id": {"ts": "environmentId"}, "pool_id": {"ts": "poolId"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "revision": {"ts": "revision"}, "runtime": {"ts": "runtime"}, "target_id": {"ts": "targetId"}}, "required": ["cloud_id", "revision"]}, - "ChangeInputBody": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "connection_id": {"ts": "connectionId"}, "default": {"ts": "default"}, "environment_id": {"ts": "environmentId"}, "pool_id": {"ts": "poolId"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "revision": {"ts": "revision"}, "runtime": {"ts": "runtime"}, "target_id": {"ts": "targetId"}}, "required": ["cloud_id", "revision"]}, + "ChangeInput": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "connection_id": {"ts": "connectionId"}, "default": {"ts": "default"}, "pool_id": {"ts": "poolId"}, "project_default": {"ts": "projectDefault"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "revision": {"ts": "revision"}, "runtime": {"ts": "runtime"}, "target_id": {"ts": "targetId"}}, "required": ["cloud_id", "revision"]}, + "ChangeInputBody": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "connection_id": {"ts": "connectionId"}, "default": {"ts": "default"}, "pool_id": {"ts": "poolId"}, "project_default": {"ts": "projectDefault"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "revision": {"ts": "revision"}, "runtime": {"ts": "runtime"}, "target_id": {"ts": "targetId"}}, "required": ["cloud_id", "revision"]}, "ChangedService": {"kind": "object", "fields": {"action_id": {"ts": "actionId"}, "canary": {"ts": "canary"}, "last_canary": {"ts": "lastCanary"}, "name": {"ts": "name"}, "op": {"ts": "op"}, "provider": {"ts": "provider"}}, "required": ["action_id", "canary", "last_canary", "name", "op", "provider"]}, "CheckInputBody": {"kind": "object", "fields": {"dependency": {"ts": "dependency"}, "dsn": {"ts": "dsn"}, "engine": {"ts": "engine"}, "kind": {"ts": "kind"}, "target": {"ts": "target"}}, "required": ["dependency", "dsn", "engine", "kind", "target"]}, "CheckResult": {"kind": "object", "fields": {"missing": {"ts": "missing", "codec": () => CODECS["CheckResult.missing"]}, "notes": {"ts": "notes", "codec": () => CODECS["CheckResult.notes"]}, "ok": {"ts": "ok"}, "problems": {"ts": "problems", "codec": () => CODECS["CheckResult.problems"]}, "version": {"ts": "version"}}, "required": ["ok"]}, @@ -206,7 +204,7 @@ export const CODECS: Record = { "CloudLocationDeleteInputBody": {"kind": "object", "fields": {"cloud_revision": {"ts": "cloudRevision"}, "revision": {"ts": "revision"}}, "required": ["cloud_revision", "revision"]}, "CloudLocationList": {"kind": "object", "fields": {"locations": {"ts": "locations", "codec": () => CODECS["CloudLocationList.locations"]}}, "required": ["locations"]}, "CloudLocationList.locations": {"kind": "array", "items": () => CODECS["CloudLocation"]}, - "CloudPlacement": {"kind": "object", "fields": {"account_identity": {"ts": "accountIdentity"}, "allocation": {"ts": "allocation"}, "assignment_revision": {"ts": "assignmentRevision"}, "cloud_id": {"ts": "cloudId"}, "cloud_revision": {"ts": "cloudRevision"}, "connection_generation": {"ts": "connectionGeneration"}, "connection_id": {"ts": "connectionId"}, "cpu_millis": {"ts": "cpuMillis"}, "default": {"ts": "default"}, "gpu_kind": {"ts": "gpuKind"}, "gpus": {"ts": "gpus"}, "grant_revision": {"ts": "grantRevision"}, "memory_bytes": {"ts": "memoryBytes"}, "pool_id": {"ts": "poolId"}, "pool_revision": {"ts": "poolRevision"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "region_source": {"ts": "regionSource"}, "server_id": {"ts": "serverId"}, "server_revision": {"ts": "serverRevision"}, "target_id": {"ts": "targetId"}, "target_name": {"ts": "targetName"}, "target_revision": {"ts": "targetRevision"}}, "required": ["account_identity", "assignment_revision", "cloud_id", "cloud_revision", "connection_id", "provider", "target_id", "target_name", "target_revision"]}, + "CloudPlacement": {"kind": "object", "fields": {"account_identity": {"ts": "accountIdentity"}, "allocation": {"ts": "allocation"}, "cloud_id": {"ts": "cloudId"}, "cloud_revision": {"ts": "cloudRevision"}, "connection_generation": {"ts": "connectionGeneration"}, "connection_id": {"ts": "connectionId"}, "cpu_millis": {"ts": "cpuMillis"}, "default": {"ts": "default"}, "gpu_kind": {"ts": "gpuKind"}, "gpus": {"ts": "gpus"}, "grant_revision": {"ts": "grantRevision"}, "memory_bytes": {"ts": "memoryBytes"}, "pool_id": {"ts": "poolId"}, "pool_revision": {"ts": "poolRevision"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "region_source": {"ts": "regionSource"}, "server_id": {"ts": "serverId"}, "server_revision": {"ts": "serverRevision"}, "target_id": {"ts": "targetId"}, "target_name": {"ts": "targetName"}, "target_revision": {"ts": "targetRevision"}}, "required": ["account_identity", "cloud_id", "cloud_revision", "connection_id", "provider", "target_id", "target_name", "target_revision"]}, "CloudProjectGrantInputBody": {"kind": "object", "fields": {"target_ids": {"ts": "targetIds", "codec": () => CODECS["CloudProjectGrantInputBody.target_ids"]}}, "required": ["target_ids"]}, "CloudProjectGrantInputBody.target_ids": {"kind": "array"}, "CloudProjectGrantList": {"kind": "object", "fields": {"grants": {"ts": "grants", "codec": () => CODECS["CloudProjectGrantList.grants"]}}, "required": ["grants"]}, @@ -362,6 +360,8 @@ export const CODECS: Record = { "DbgatewayRouteStatus": {"kind": "object", "fields": {"backend_conns": {"ts": "backendConns"}, "id": {"ts": "id"}, "max_connections": {"ts": "maxConnections"}, "pin_rate": {"ts": "pinRate"}, "reachable": {"ts": "reachable"}, "reported": {"ts": "reported"}, "resource": {"ts": "resource"}, "state": {"ts": "state"}}, "required": ["backend_conns", "id", "max_connections", "pin_rate", "reachable", "reported", "resource", "state"]}, "DecideInputBody": {"kind": "object", "fields": {"note": {"ts": "note"}, "revision": {"ts": "revision"}}}, "DeclineInputBody": {"kind": "object", "fields": {"reason": {"ts": "reason"}}}, + "DefaultCloud": {"kind": "object", "fields": {"cloud": {"ts": "cloud", "codec": () => CODECS["ProjectCloud"]}, "project_id": {"ts": "projectId"}, "revision": {"ts": "revision"}}, "required": ["cloud", "project_id", "revision"]}, + "DefaultCloudInputBody": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "revision": {"ts": "revision"}}, "required": ["cloud_id", "revision"]}, "DefaultPlacement": {"kind": "object", "fields": {"connection_id": {"ts": "connectionId"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}}, "required": ["connection_id", "provider", "region"]}, "Defaults": {"kind": "object", "fields": {"cloud_tags": {"ts": "cloudTags", "codec": () => CODECS["Defaults.cloud_tags"]}, "provider": {"ts": "provider"}, "region": {"ts": "region"}}}, "Defaults.cloud_tags": {"kind": "array"}, @@ -435,12 +435,12 @@ export const CODECS: Record = { "EditInputBody.add_resource.needed_by": {"kind": "array"}, "EditInputBody.add_resource.settings": {"kind": "record"}, "EditInputBody.add_resource.uses": {"kind": "record"}, - "EditInputBody.add_service": {"kind": "object", "fields": {"enabled_in": {"ts": "enabledIn"}, "kind": {"ts": "kind"}, "name": {"ts": "name"}, "needed_by": {"ts": "neededBy", "codec": () => CODECS["EditInputBody.add_service.needed_by"]}, "needs": {"ts": "needs", "codec": () => CODECS["EditInputBody.add_service.needs"]}, "only": {"ts": "only"}, "port": {"ts": "port"}, "provider": {"ts": "provider"}, "public": {"ts": "public"}, "region": {"ts": "region"}, "repo": {"ts": "repo"}, "source": {"ts": "source"}, "target": {"ts": "target"}}, "required": ["name", "source"]}, + "EditInputBody.add_service": {"kind": "object", "fields": {"cloud": {"ts": "cloud"}, "cloud_target": {"ts": "cloudTarget"}, "enabled_in": {"ts": "enabledIn"}, "kind": {"ts": "kind"}, "name": {"ts": "name"}, "needed_by": {"ts": "neededBy", "codec": () => CODECS["EditInputBody.add_service.needed_by"]}, "needs": {"ts": "needs", "codec": () => CODECS["EditInputBody.add_service.needs"]}, "only": {"ts": "only"}, "port": {"ts": "port"}, "provider": {"ts": "provider"}, "public": {"ts": "public"}, "region": {"ts": "region"}, "repo": {"ts": "repo"}, "source": {"ts": "source"}, "target": {"ts": "target"}}, "required": ["name", "source"]}, "EditInputBody.add_service.needed_by": {"kind": "array"}, "EditInputBody.add_service.needs": {"kind": "array"}, "EditInputBody.link": {"kind": "object", "fields": {"need": {"ts": "need"}, "options": {"ts": "options", "codec": () => CODECS["EditInputBody.link.options"]}, "service": {"ts": "service"}}, "required": ["need", "service"]}, "EditInputBody.link.options": {"kind": "record"}, - "EditInputBody.placement": {"kind": "object", "fields": {"build": {"ts": "build", "codec": () => CODECS["Build"]}, "cloud_sql_network": {"ts": "cloudSqlNetwork", "codec": () => CODECS["CloudSQLApplicationNetwork"]}, "cloud_tags": {"ts": "cloudTags", "codec": () => CODECS["EditInputBody.placement.cloud_tags"]}, "cloud_target": {"ts": "cloudTarget"}, "commands": {"ts": "commands", "codec": () => CODECS["BuildCommands"]}, "enabled": {"ts": "enabled"}, "endpoint": {"ts": "endpoint", "codec": () => CODECS["ManifestEndpoint"]}, "environment": {"ts": "environment"}, "health_path": {"ts": "healthPath"}, "name": {"ts": "name"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "scale": {"ts": "scale", "codec": () => CODECS["Scale"]}, "section": {"ts": "section"}, "size": {"ts": "size", "codec": () => CODECS["SizeEdit"]}, "target": {"ts": "target"}, "vercel": {"ts": "vercel", "codec": () => CODECS["VercelSettings"]}}, "required": ["name", "section"]}, + "EditInputBody.placement": {"kind": "object", "fields": {"build": {"ts": "build", "codec": () => CODECS["Build"]}, "cloud": {"ts": "cloud"}, "cloud_sql_network": {"ts": "cloudSqlNetwork", "codec": () => CODECS["CloudSQLApplicationNetwork"]}, "cloud_tags": {"ts": "cloudTags", "codec": () => CODECS["EditInputBody.placement.cloud_tags"]}, "cloud_target": {"ts": "cloudTarget"}, "commands": {"ts": "commands", "codec": () => CODECS["BuildCommands"]}, "enabled": {"ts": "enabled"}, "endpoint": {"ts": "endpoint", "codec": () => CODECS["ManifestEndpoint"]}, "environment": {"ts": "environment"}, "health_path": {"ts": "healthPath"}, "name": {"ts": "name"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "scale": {"ts": "scale", "codec": () => CODECS["Scale"]}, "section": {"ts": "section"}, "size": {"ts": "size", "codec": () => CODECS["SizeEdit"]}, "target": {"ts": "target"}, "vercel": {"ts": "vercel", "codec": () => CODECS["VercelSettings"]}}, "required": ["name", "section"]}, "EditInputBody.placement.cloud_tags": {"kind": "array"}, "EditInputBody.set_use": {"kind": "object", "fields": {"dependency": {"ts": "dependency"}, "resource": {"ts": "resource"}, "use": {"ts": "use", "codec": () => CODECS["ManifestUse"]}}, "required": ["dependency", "resource", "use"]}, "EditInputBody.unlink": {"kind": "object", "fields": {"need": {"ts": "need"}, "options": {"ts": "options", "codec": () => CODECS["EditInputBody.unlink.options"]}, "service": {"ts": "service"}}, "required": ["need", "service"]}, @@ -469,14 +469,11 @@ export const CODECS: Record = { "EnvironmentChange": {"kind": "object", "fields": {"compensation_message": {"ts": "compensationMessage"}, "compensation_mode": {"ts": "compensationMode"}, "deployment_id": {"ts": "deploymentId"}, "environment": {"ts": "environment"}, "environment_id": {"ts": "environmentId"}, "error": {"ts": "error"}, "external_routing": {"ts": "externalRouting"}, "plan_id": {"ts": "planId"}, "project_id": {"ts": "projectId"}, "routes": {"ts": "routes", "codec": () => CODECS["EnvironmentChange.routes"]}, "routing_evidence": {"ts": "routingEvidence"}, "routing_status": {"ts": "routingStatus"}, "services": {"ts": "services", "codec": () => CODECS["EnvironmentChange.services"]}, "status": {"ts": "status"}, "summary": {"ts": "summary", "codec": () => CODECS["PlanSummary"]}}, "required": ["environment", "environment_id", "external_routing", "services", "status", "summary"]}, "EnvironmentChange.routes": {"kind": "array", "items": () => CODECS["SyncRoute"]}, "EnvironmentChange.services": {"kind": "array"}, - "EnvironmentCloud": {"kind": "object", "fields": {"assignment": {"ts": "assignment", "codec": () => CODECS["Assignment"]}, "revision": {"ts": "revision"}}, "required": ["assignment", "revision"]}, - "EnvironmentCloudEvent": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "environment_id": {"ts": "environmentId"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "revision": {"ts": "revision"}}, "required": ["cloud_id", "environment_id", "org_id", "project_id", "revision"]}, - "EnvironmentCloudInputBody": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "revision": {"ts": "revision"}}, "required": ["cloud_id", "revision"]}, "EnvironmentConnections": {"kind": "object", "fields": {"connections": {"ts": "connections", "codec": () => CODECS["EnvironmentConnections.connections"]}, "environment": {"ts": "environment"}}, "required": ["connections", "environment"]}, "EnvironmentConnections.connections": {"kind": "record"}, "EnvironmentList": {"kind": "object", "fields": {"environments": {"ts": "environments", "codec": () => CODECS["EnvironmentList.environments"]}}, "required": ["environments"]}, "EnvironmentList.environments": {"kind": "array", "items": () => CODECS["Environment"]}, - "EnvironmentUsage": {"kind": "object", "fields": {"assigned": {"ts": "assigned"}, "environment_id": {"ts": "environmentId"}, "environment_name": {"ts": "environmentName"}, "placements": {"ts": "placements", "codec": () => CODECS["EnvironmentUsage.placements"]}, "project_id": {"ts": "projectId"}, "project_name": {"ts": "projectName"}}, "required": ["assigned", "environment_id", "environment_name", "placements", "project_id", "project_name"]}, + "EnvironmentUsage": {"kind": "object", "fields": {"default": {"ts": "default"}, "environment_id": {"ts": "environmentId"}, "environment_name": {"ts": "environmentName"}, "placements": {"ts": "placements", "codec": () => CODECS["EnvironmentUsage.placements"]}, "project_id": {"ts": "projectId"}, "project_name": {"ts": "projectName"}}, "required": ["default", "environment_id", "environment_name", "placements", "project_id", "project_name"]}, "EnvironmentUsage.placements": {"kind": "array", "items": () => CODECS["PlacementUsage"]}, "Event": {"kind": "object", "fields": {"at": {"ts": "at"}, "data": {"ts": "data"}, "kind": {"ts": "kind"}, "seq": {"ts": "seq"}, "task_id": {"ts": "taskId"}}, "required": ["at", "data", "kind", "seq", "task_id"]}, "EventAcceptance": {"kind": "object", "fields": {"attempts": {"ts": "attempts"}, "error_code": {"ts": "errorCode"}, "event_id": {"ts": "eventId"}, "state": {"ts": "state"}}, "required": ["attempts", "event_id", "state"]}, @@ -762,7 +759,7 @@ export const CODECS: Record = { "NewCertificate": {"kind": "object", "fields": {"client_certificate": {"ts": "clientCertificate"}, "client_fingerprint": {"ts": "clientFingerprint"}, "expires_at": {"ts": "expiresAt"}, "host": {"ts": "host", "codec": () => CODECS["Host"]}}, "required": ["client_certificate", "client_fingerprint", "expires_at", "host"]}, "NewHost": {"kind": "object", "fields": {"client_certificate": {"ts": "clientCertificate"}, "client_fingerprint": {"ts": "clientFingerprint"}, "host": {"ts": "host", "codec": () => CODECS["Host"]}}, "required": ["client_certificate", "client_fingerprint", "host"]}, "NewKeyBody": {"kind": "object", "fields": {"access": {"ts": "access"}, "expires_in_days": {"ts": "expiresInDays"}, "name": {"ts": "name"}}, "required": ["access", "name"]}, - "NewServiceInput": {"kind": "object", "fields": {"enabled_in": {"ts": "enabledIn"}, "kind": {"ts": "kind"}, "name": {"ts": "name"}, "needed_by": {"ts": "neededBy", "codec": () => CODECS["NewServiceInput.needed_by"]}, "needs": {"ts": "needs", "codec": () => CODECS["NewServiceInput.needs"]}, "only": {"ts": "only"}, "port": {"ts": "port"}, "provider": {"ts": "provider"}, "public": {"ts": "public"}, "region": {"ts": "region"}, "repo": {"ts": "repo"}, "source": {"ts": "source"}, "target": {"ts": "target"}}, "required": ["name", "source"]}, + "NewServiceInput": {"kind": "object", "fields": {"cloud": {"ts": "cloud"}, "cloud_target": {"ts": "cloudTarget"}, "enabled_in": {"ts": "enabledIn"}, "kind": {"ts": "kind"}, "name": {"ts": "name"}, "needed_by": {"ts": "neededBy", "codec": () => CODECS["NewServiceInput.needed_by"]}, "needs": {"ts": "needs", "codec": () => CODECS["NewServiceInput.needs"]}, "only": {"ts": "only"}, "port": {"ts": "port"}, "provider": {"ts": "provider"}, "public": {"ts": "public"}, "region": {"ts": "region"}, "repo": {"ts": "repo"}, "source": {"ts": "source"}, "target": {"ts": "target"}}, "required": ["name", "source"]}, "NewServiceInput.needed_by": {"kind": "array"}, "NewServiceInput.needs": {"kind": "array"}, "Node": {"kind": "object", "fields": {"created_at": {"ts": "createdAt"}, "edge_scope": {"ts": "edgeScope"}, "endpoints": {"ts": "endpoints", "codec": () => CODECS["Node.endpoints"]}, "id": {"ts": "id"}, "identity_generation": {"ts": "identityGeneration"}, "ingress_applied": {"ts": "ingressApplied"}, "ingress_detail": {"ts": "ingressDetail"}, "ingress_mode": {"ts": "ingressMode"}, "inventory": {"ts": "inventory", "codec": () => CODECS["Inventory"]}, "joined_by": {"ts": "joinedBy"}, "joined_by_key_id": {"ts": "joinedByKeyId"}, "key_fingerprint": {"ts": "keyFingerprint"}, "labels": {"ts": "labels", "codec": () => CODECS["Node.labels"]}, "last_seen_at": {"ts": "lastSeenAt"}, "name": {"ts": "name"}, "org_id": {"ts": "orgId"}, "protocol_version": {"ts": "protocolVersion"}, "public_address": {"ts": "publicAddress"}, "public_address_confirmed_at": {"ts": "publicAddressConfirmedAt"}, "revoked_at": {"ts": "revokedAt"}, "revoked_by": {"ts": "revokedBy"}, "role": {"ts": "role"}, "status": {"ts": "status"}, "updated_at": {"ts": "updatedAt"}, "version": {"ts": "version"}}, "required": ["created_at", "edge_scope", "endpoints", "id", "identity_generation", "ingress_applied", "ingress_detail", "ingress_mode", "inventory", "joined_by", "joined_by_key_id", "key_fingerprint", "labels", "name", "org_id", "protocol_version", "public_address", "revoked_by", "role", "status", "updated_at", "version"]}, @@ -887,7 +884,7 @@ export const CODECS: Record = { "Preferences": {"kind": "object", "fields": {"agent_email": {"ts": "agentEmail"}, "deployment_email": {"ts": "deploymentEmail"}, "mail_enabled": {"ts": "mailEnabled"}}, "required": ["agent_email", "deployment_email", "mail_enabled"]}, "PrepareInputBody": {"kind": "object", "fields": {"from": {"ts": "from"}, "replace": {"ts": "replace"}, "scope": {"ts": "scope", "codec": () => CODECS["PrepareInputBody.scope"]}, "to": {"ts": "to"}}}, "PrepareInputBody.scope": {"kind": "array"}, - "Preview": {"kind": "object", "fields": {"after": {"ts": "after", "codec": () => CODECS["CloudprofilesTarget"]}, "after_assignment": {"ts": "afterAssignment", "codec": () => CODECS["Assignment"]}, "after_default": {"ts": "afterDefault", "codec": () => CODECS["DefaultPlacement"]}, "before": {"ts": "before", "codec": () => CODECS["CloudprofilesTarget"]}, "before_assignment": {"ts": "beforeAssignment", "codec": () => CODECS["Assignment"]}, "before_default": {"ts": "beforeDefault", "codec": () => CODECS["DefaultPlacement"]}, "blockers": {"ts": "blockers", "codec": () => CODECS["Preview.blockers"]}, "created_at": {"ts": "createdAt"}, "environments": {"ts": "environments", "codec": () => CODECS["Preview.environments"]}, "id": {"ts": "id"}, "input": {"ts": "input", "codec": () => CODECS["ChangeInput"]}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "reverts": {"ts": "reverts"}, "revision": {"ts": "revision"}}, "required": ["blockers", "created_at", "environments", "id", "input", "org_id", "project_id", "revision"]}, + "Preview": {"kind": "object", "fields": {"after": {"ts": "after", "codec": () => CODECS["CloudprofilesTarget"]}, "after_cloud": {"ts": "afterCloud", "codec": () => CODECS["ProjectCloud"]}, "after_default": {"ts": "afterDefault", "codec": () => CODECS["DefaultPlacement"]}, "before": {"ts": "before", "codec": () => CODECS["CloudprofilesTarget"]}, "before_cloud": {"ts": "beforeCloud", "codec": () => CODECS["ProjectCloud"]}, "before_default": {"ts": "beforeDefault", "codec": () => CODECS["DefaultPlacement"]}, "blockers": {"ts": "blockers", "codec": () => CODECS["Preview.blockers"]}, "created_at": {"ts": "createdAt"}, "environments": {"ts": "environments", "codec": () => CODECS["Preview.environments"]}, "id": {"ts": "id"}, "input": {"ts": "input", "codec": () => CODECS["ChangeInput"]}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "reverts": {"ts": "reverts"}, "revision": {"ts": "revision"}}, "required": ["blockers", "created_at", "environments", "id", "input", "org_id", "project_id", "revision"]}, "Preview.blockers": {"kind": "array"}, "Preview.environments": {"kind": "array", "items": () => CODECS["EnvironmentChange"]}, "Problem": {"kind": "object", "fields": {"code": {"ts": "code"}, "message": {"ts": "message"}}, "required": ["code", "message"]}, @@ -895,11 +892,14 @@ export const CODECS: Record = { "Project": {"kind": "object", "fields": {"autonomous_promotion": {"ts": "autonomousPromotion"}, "color": {"ts": "color"}, "created_at": {"ts": "createdAt"}, "created_by": {"ts": "createdBy"}, "deployment_mode": {"ts": "deploymentMode"}, "description": {"ts": "description"}, "exclusions": {"ts": "exclusions", "codec": () => CODECS["Project.exclusions"]}, "icon": {"ts": "icon"}, "id": {"ts": "id"}, "kind": {"ts": "kind"}, "min_staging_soak_seconds": {"ts": "minStagingSoakSeconds"}, "name": {"ts": "name"}, "org_id": {"ts": "orgId"}, "repositories": {"ts": "repositories", "codec": () => CODECS["Project.repositories"]}, "responsible_team_id": {"ts": "responsibleTeamId"}, "slug": {"ts": "slug"}, "status": {"ts": "status"}, "updated_at": {"ts": "updatedAt"}}, "required": ["autonomous_promotion", "color", "created_at", "created_by", "deployment_mode", "description", "exclusions", "icon", "id", "kind", "min_staging_soak_seconds", "name", "org_id", "repositories", "responsible_team_id", "slug", "status", "updated_at"]}, "Project.exclusions": {"kind": "array", "items": () => CODECS["Exclusion"]}, "Project.repositories": {"kind": "array"}, + "ProjectCloud": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "cloud_revision": {"ts": "cloudRevision"}, "default": {"ts": "default"}, "default_placement": {"ts": "defaultPlacement", "codec": () => CODECS["DefaultPlacement"]}, "grant_revision": {"ts": "grantRevision"}, "name": {"ts": "name"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "targets": {"ts": "targets", "codec": () => CODECS["ProjectCloud.targets"]}}, "required": ["cloud_id", "cloud_revision", "default", "grant_revision", "name", "org_id", "project_id", "targets"]}, + "ProjectCloud.targets": {"kind": "array", "items": () => CODECS["CloudprofilesTarget"]}, + "ProjectCloudEvent": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}}, "required": ["cloud_id", "org_id", "project_id"]}, "ProjectDomain": {"kind": "object", "fields": {"hostnames": {"ts": "hostnames", "codec": () => CODECS["ProjectDomain.hostnames"]}, "mode": {"ts": "mode"}, "name": {"ts": "name"}, "provider": {"ts": "provider"}, "verified": {"ts": "verified"}, "wildcards": {"ts": "wildcards"}, "zone_id": {"ts": "zoneId"}}, "required": ["hostnames", "mode", "name", "verified", "wildcards", "zone_id"]}, "ProjectDomain.hostnames": {"kind": "array", "items": () => CODECS["HostnameUse"]}, "ProjectDomainList": {"kind": "object", "fields": {"domains": {"ts": "domains", "codec": () => CODECS["ProjectDomainList.domains"]}}, "required": ["domains"]}, "ProjectDomainList.domains": {"kind": "array", "items": () => CODECS["ProjectDomain"]}, - "ProjectGrant": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "revision": {"ts": "revision"}, "revoked": {"ts": "revoked"}, "target_ids": {"ts": "targetIds", "codec": () => CODECS["ProjectGrant.target_ids"]}}, "required": ["cloud_id", "org_id", "project_id", "revision", "revoked", "target_ids"]}, + "ProjectGrant": {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "default": {"ts": "default"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "revision": {"ts": "revision"}, "revoked": {"ts": "revoked"}, "target_ids": {"ts": "targetIds", "codec": () => CODECS["ProjectGrant.target_ids"]}}, "required": ["cloud_id", "default", "org_id", "project_id", "revision", "revoked", "target_ids"]}, "ProjectGrant.target_ids": {"kind": "array"}, "ProjectList": {"kind": "object", "fields": {"projects": {"ts": "projects", "codec": () => CODECS["ProjectList.projects"]}}, "required": ["projects"]}, "ProjectList.projects": {"kind": "array", "items": () => CODECS["Project"]}, diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/Assignment.ts b/apps/dashboard/src/client/forge/loomplane/codecs/Assignment.ts deleted file mode 100644 index c23673e11..000000000 --- a/apps/dashboard/src/client/forge/loomplane/codecs/Assignment.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { Codec } from '../codec-runtime'; -import { codec_Assignment_targets } from './Assignment.targets'; -import { codec_DefaultPlacement } from './DefaultPlacement'; - -export const codec_Assignment: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "cloud_revision": {"ts": "cloudRevision"}, "default_placement": {"ts": "defaultPlacement", "codec": () => codec_DefaultPlacement}, "environment_id": {"ts": "environmentId"}, "grant_revision": {"ts": "grantRevision"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "revision": {"ts": "revision"}, "targets": {"ts": "targets", "codec": () => codec_Assignment_targets}}, "required": ["cloud_id", "cloud_revision", "environment_id", "grant_revision", "org_id", "project_id", "revision", "targets"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/CapacityIntent.ts b/apps/dashboard/src/client/forge/loomplane/codecs/CapacityIntent.ts index 97e8230e8..dcd77f90f 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/CapacityIntent.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/CapacityIntent.ts @@ -2,4 +2,4 @@ import type { Codec } from '../codec-runtime'; import { codec_CapacityDemand } from './CapacityDemand'; import { codec_PoolExpansionPolicy } from './PoolExpansionPolicy'; -export const codec_CapacityIntent: Codec = {"kind": "object", "fields": {"assignment_revision": {"ts": "assignmentRevision"}, "cloud_revision": {"ts": "cloudRevision"}, "commit_sha": {"ts": "commitSha"}, "demand": {"ts": "demand", "codec": () => codec_CapacityDemand}, "grant_revision": {"ts": "grantRevision"}, "target_name": {"ts": "targetName"}, "target_revision": {"ts": "targetRevision"}, "template": {"ts": "template", "codec": () => codec_PoolExpansionPolicy}, "template_hash": {"ts": "templateHash"}}, "required": ["assignment_revision", "cloud_revision", "commit_sha", "demand", "grant_revision", "target_name", "target_revision", "template", "template_hash"]}; +export const codec_CapacityIntent: Codec = {"kind": "object", "fields": {"cloud_revision": {"ts": "cloudRevision"}, "commit_sha": {"ts": "commitSha"}, "demand": {"ts": "demand", "codec": () => codec_CapacityDemand}, "grant_revision": {"ts": "grantRevision"}, "target_name": {"ts": "targetName"}, "target_revision": {"ts": "targetRevision"}, "template": {"ts": "template", "codec": () => codec_PoolExpansionPolicy}, "template_hash": {"ts": "templateHash"}}, "required": ["cloud_revision", "commit_sha", "demand", "grant_revision", "target_name", "target_revision", "template", "template_hash"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/ChangeInput.ts b/apps/dashboard/src/client/forge/loomplane/codecs/ChangeInput.ts index f450af34f..00d745920 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/ChangeInput.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/ChangeInput.ts @@ -1,3 +1,3 @@ import type { Codec } from '../codec-runtime'; -export const codec_ChangeInput: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "connection_id": {"ts": "connectionId"}, "default": {"ts": "default"}, "environment_id": {"ts": "environmentId"}, "pool_id": {"ts": "poolId"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "revision": {"ts": "revision"}, "runtime": {"ts": "runtime"}, "target_id": {"ts": "targetId"}}, "required": ["cloud_id", "revision"]}; +export const codec_ChangeInput: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "connection_id": {"ts": "connectionId"}, "default": {"ts": "default"}, "pool_id": {"ts": "poolId"}, "project_default": {"ts": "projectDefault"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "revision": {"ts": "revision"}, "runtime": {"ts": "runtime"}, "target_id": {"ts": "targetId"}}, "required": ["cloud_id", "revision"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/ChangeInputBody.ts b/apps/dashboard/src/client/forge/loomplane/codecs/ChangeInputBody.ts index 3d359ede6..d579e4ae5 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/ChangeInputBody.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/ChangeInputBody.ts @@ -1,3 +1,3 @@ import type { Codec } from '../codec-runtime'; -export const codec_ChangeInputBody: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "connection_id": {"ts": "connectionId"}, "default": {"ts": "default"}, "environment_id": {"ts": "environmentId"}, "pool_id": {"ts": "poolId"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "revision": {"ts": "revision"}, "runtime": {"ts": "runtime"}, "target_id": {"ts": "targetId"}}, "required": ["cloud_id", "revision"]}; +export const codec_ChangeInputBody: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "connection_id": {"ts": "connectionId"}, "default": {"ts": "default"}, "pool_id": {"ts": "poolId"}, "project_default": {"ts": "projectDefault"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "revision": {"ts": "revision"}, "runtime": {"ts": "runtime"}, "target_id": {"ts": "targetId"}}, "required": ["cloud_id", "revision"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/CloudPlacement.ts b/apps/dashboard/src/client/forge/loomplane/codecs/CloudPlacement.ts index 0706ff219..2f6875803 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/CloudPlacement.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/CloudPlacement.ts @@ -1,3 +1,3 @@ import type { Codec } from '../codec-runtime'; -export const codec_CloudPlacement: Codec = {"kind": "object", "fields": {"account_identity": {"ts": "accountIdentity"}, "allocation": {"ts": "allocation"}, "assignment_revision": {"ts": "assignmentRevision"}, "cloud_id": {"ts": "cloudId"}, "cloud_revision": {"ts": "cloudRevision"}, "connection_generation": {"ts": "connectionGeneration"}, "connection_id": {"ts": "connectionId"}, "cpu_millis": {"ts": "cpuMillis"}, "default": {"ts": "default"}, "gpu_kind": {"ts": "gpuKind"}, "gpus": {"ts": "gpus"}, "grant_revision": {"ts": "grantRevision"}, "memory_bytes": {"ts": "memoryBytes"}, "pool_id": {"ts": "poolId"}, "pool_revision": {"ts": "poolRevision"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "region_source": {"ts": "regionSource"}, "server_id": {"ts": "serverId"}, "server_revision": {"ts": "serverRevision"}, "target_id": {"ts": "targetId"}, "target_name": {"ts": "targetName"}, "target_revision": {"ts": "targetRevision"}}, "required": ["account_identity", "assignment_revision", "cloud_id", "cloud_revision", "connection_id", "provider", "target_id", "target_name", "target_revision"]}; +export const codec_CloudPlacement: Codec = {"kind": "object", "fields": {"account_identity": {"ts": "accountIdentity"}, "allocation": {"ts": "allocation"}, "cloud_id": {"ts": "cloudId"}, "cloud_revision": {"ts": "cloudRevision"}, "connection_generation": {"ts": "connectionGeneration"}, "connection_id": {"ts": "connectionId"}, "cpu_millis": {"ts": "cpuMillis"}, "default": {"ts": "default"}, "gpu_kind": {"ts": "gpuKind"}, "gpus": {"ts": "gpus"}, "grant_revision": {"ts": "grantRevision"}, "memory_bytes": {"ts": "memoryBytes"}, "pool_id": {"ts": "poolId"}, "pool_revision": {"ts": "poolRevision"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "region_source": {"ts": "regionSource"}, "server_id": {"ts": "serverId"}, "server_revision": {"ts": "serverRevision"}, "target_id": {"ts": "targetId"}, "target_name": {"ts": "targetName"}, "target_revision": {"ts": "targetRevision"}}, "required": ["account_identity", "cloud_id", "cloud_revision", "connection_id", "provider", "target_id", "target_name", "target_revision"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/DefaultCloud.ts b/apps/dashboard/src/client/forge/loomplane/codecs/DefaultCloud.ts new file mode 100644 index 000000000..4280dcdd1 --- /dev/null +++ b/apps/dashboard/src/client/forge/loomplane/codecs/DefaultCloud.ts @@ -0,0 +1,4 @@ +import type { Codec } from '../codec-runtime'; +import { codec_ProjectCloud } from './ProjectCloud'; + +export const codec_DefaultCloud: Codec = {"kind": "object", "fields": {"cloud": {"ts": "cloud", "codec": () => codec_ProjectCloud}, "project_id": {"ts": "projectId"}, "revision": {"ts": "revision"}}, "required": ["cloud", "project_id", "revision"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/DefaultCloudInputBody.ts b/apps/dashboard/src/client/forge/loomplane/codecs/DefaultCloudInputBody.ts new file mode 100644 index 000000000..412cb88c1 --- /dev/null +++ b/apps/dashboard/src/client/forge/loomplane/codecs/DefaultCloudInputBody.ts @@ -0,0 +1,3 @@ +import type { Codec } from '../codec-runtime'; + +export const codec_DefaultCloudInputBody: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "revision": {"ts": "revision"}}, "required": ["cloud_id", "revision"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/EditInputBody.add_service.ts b/apps/dashboard/src/client/forge/loomplane/codecs/EditInputBody.add_service.ts index 3cc30f9e8..1e486747a 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/EditInputBody.add_service.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/EditInputBody.add_service.ts @@ -2,4 +2,4 @@ import type { Codec } from '../codec-runtime'; import { codec_EditInputBody_add_service_needed_by } from './EditInputBody.add_service.needed_by'; import { codec_EditInputBody_add_service_needs } from './EditInputBody.add_service.needs'; -export const codec_EditInputBody_add_service: Codec = {"kind": "object", "fields": {"enabled_in": {"ts": "enabledIn"}, "kind": {"ts": "kind"}, "name": {"ts": "name"}, "needed_by": {"ts": "neededBy", "codec": () => codec_EditInputBody_add_service_needed_by}, "needs": {"ts": "needs", "codec": () => codec_EditInputBody_add_service_needs}, "only": {"ts": "only"}, "port": {"ts": "port"}, "provider": {"ts": "provider"}, "public": {"ts": "public"}, "region": {"ts": "region"}, "repo": {"ts": "repo"}, "source": {"ts": "source"}, "target": {"ts": "target"}}, "required": ["name", "source"]}; +export const codec_EditInputBody_add_service: Codec = {"kind": "object", "fields": {"cloud": {"ts": "cloud"}, "cloud_target": {"ts": "cloudTarget"}, "enabled_in": {"ts": "enabledIn"}, "kind": {"ts": "kind"}, "name": {"ts": "name"}, "needed_by": {"ts": "neededBy", "codec": () => codec_EditInputBody_add_service_needed_by}, "needs": {"ts": "needs", "codec": () => codec_EditInputBody_add_service_needs}, "only": {"ts": "only"}, "port": {"ts": "port"}, "provider": {"ts": "provider"}, "public": {"ts": "public"}, "region": {"ts": "region"}, "repo": {"ts": "repo"}, "source": {"ts": "source"}, "target": {"ts": "target"}}, "required": ["name", "source"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/EditInputBody.placement.ts b/apps/dashboard/src/client/forge/loomplane/codecs/EditInputBody.placement.ts index cb5df6b58..17750fad2 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/EditInputBody.placement.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/EditInputBody.placement.ts @@ -8,4 +8,4 @@ import { codec_Scale } from './Scale'; import { codec_SizeEdit } from './SizeEdit'; import { codec_VercelSettings } from './VercelSettings'; -export const codec_EditInputBody_placement: Codec = {"kind": "object", "fields": {"build": {"ts": "build", "codec": () => codec_Build}, "cloud_sql_network": {"ts": "cloudSqlNetwork", "codec": () => codec_CloudSQLApplicationNetwork}, "cloud_tags": {"ts": "cloudTags", "codec": () => codec_EditInputBody_placement_cloud_tags}, "cloud_target": {"ts": "cloudTarget"}, "commands": {"ts": "commands", "codec": () => codec_BuildCommands}, "enabled": {"ts": "enabled"}, "endpoint": {"ts": "endpoint", "codec": () => codec_ManifestEndpoint}, "environment": {"ts": "environment"}, "health_path": {"ts": "healthPath"}, "name": {"ts": "name"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "scale": {"ts": "scale", "codec": () => codec_Scale}, "section": {"ts": "section"}, "size": {"ts": "size", "codec": () => codec_SizeEdit}, "target": {"ts": "target"}, "vercel": {"ts": "vercel", "codec": () => codec_VercelSettings}}, "required": ["name", "section"]}; +export const codec_EditInputBody_placement: Codec = {"kind": "object", "fields": {"build": {"ts": "build", "codec": () => codec_Build}, "cloud": {"ts": "cloud"}, "cloud_sql_network": {"ts": "cloudSqlNetwork", "codec": () => codec_CloudSQLApplicationNetwork}, "cloud_tags": {"ts": "cloudTags", "codec": () => codec_EditInputBody_placement_cloud_tags}, "cloud_target": {"ts": "cloudTarget"}, "commands": {"ts": "commands", "codec": () => codec_BuildCommands}, "enabled": {"ts": "enabled"}, "endpoint": {"ts": "endpoint", "codec": () => codec_ManifestEndpoint}, "environment": {"ts": "environment"}, "health_path": {"ts": "healthPath"}, "name": {"ts": "name"}, "provider": {"ts": "provider"}, "region": {"ts": "region"}, "scale": {"ts": "scale", "codec": () => codec_Scale}, "section": {"ts": "section"}, "size": {"ts": "size", "codec": () => codec_SizeEdit}, "target": {"ts": "target"}, "vercel": {"ts": "vercel", "codec": () => codec_VercelSettings}}, "required": ["name", "section"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloud.ts b/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloud.ts deleted file mode 100644 index 94b95c9eb..000000000 --- a/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloud.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { Codec } from '../codec-runtime'; -import { codec_Assignment } from './Assignment'; - -export const codec_EnvironmentCloud: Codec = {"kind": "object", "fields": {"assignment": {"ts": "assignment", "codec": () => codec_Assignment}, "revision": {"ts": "revision"}}, "required": ["assignment", "revision"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloudEvent.ts b/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloudEvent.ts deleted file mode 100644 index 14e0b24c5..000000000 --- a/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloudEvent.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Codec } from '../codec-runtime'; - -export const codec_EnvironmentCloudEvent: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "environment_id": {"ts": "environmentId"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "revision": {"ts": "revision"}}, "required": ["cloud_id", "environment_id", "org_id", "project_id", "revision"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloudInputBody.ts b/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloudInputBody.ts deleted file mode 100644 index 8fe22028e..000000000 --- a/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloudInputBody.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Codec } from '../codec-runtime'; - -export const codec_EnvironmentCloudInputBody: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "revision": {"ts": "revision"}}, "required": ["cloud_id", "revision"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentUsage.ts b/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentUsage.ts index 1d97c4454..b9727ef1b 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentUsage.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentUsage.ts @@ -1,4 +1,4 @@ import type { Codec } from '../codec-runtime'; import { codec_EnvironmentUsage_placements } from './EnvironmentUsage.placements'; -export const codec_EnvironmentUsage: Codec = {"kind": "object", "fields": {"assigned": {"ts": "assigned"}, "environment_id": {"ts": "environmentId"}, "environment_name": {"ts": "environmentName"}, "placements": {"ts": "placements", "codec": () => codec_EnvironmentUsage_placements}, "project_id": {"ts": "projectId"}, "project_name": {"ts": "projectName"}}, "required": ["assigned", "environment_id", "environment_name", "placements", "project_id", "project_name"]}; +export const codec_EnvironmentUsage: Codec = {"kind": "object", "fields": {"default": {"ts": "default"}, "environment_id": {"ts": "environmentId"}, "environment_name": {"ts": "environmentName"}, "placements": {"ts": "placements", "codec": () => codec_EnvironmentUsage_placements}, "project_id": {"ts": "projectId"}, "project_name": {"ts": "projectName"}}, "required": ["default", "environment_id", "environment_name", "placements", "project_id", "project_name"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/NewServiceInput.ts b/apps/dashboard/src/client/forge/loomplane/codecs/NewServiceInput.ts index c0ecf4eb8..1cc9ec138 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/NewServiceInput.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/NewServiceInput.ts @@ -2,4 +2,4 @@ import type { Codec } from '../codec-runtime'; import { codec_NewServiceInput_needed_by } from './NewServiceInput.needed_by'; import { codec_NewServiceInput_needs } from './NewServiceInput.needs'; -export const codec_NewServiceInput: Codec = {"kind": "object", "fields": {"enabled_in": {"ts": "enabledIn"}, "kind": {"ts": "kind"}, "name": {"ts": "name"}, "needed_by": {"ts": "neededBy", "codec": () => codec_NewServiceInput_needed_by}, "needs": {"ts": "needs", "codec": () => codec_NewServiceInput_needs}, "only": {"ts": "only"}, "port": {"ts": "port"}, "provider": {"ts": "provider"}, "public": {"ts": "public"}, "region": {"ts": "region"}, "repo": {"ts": "repo"}, "source": {"ts": "source"}, "target": {"ts": "target"}}, "required": ["name", "source"]}; +export const codec_NewServiceInput: Codec = {"kind": "object", "fields": {"cloud": {"ts": "cloud"}, "cloud_target": {"ts": "cloudTarget"}, "enabled_in": {"ts": "enabledIn"}, "kind": {"ts": "kind"}, "name": {"ts": "name"}, "needed_by": {"ts": "neededBy", "codec": () => codec_NewServiceInput_needed_by}, "needs": {"ts": "needs", "codec": () => codec_NewServiceInput_needs}, "only": {"ts": "only"}, "port": {"ts": "port"}, "provider": {"ts": "provider"}, "public": {"ts": "public"}, "region": {"ts": "region"}, "repo": {"ts": "repo"}, "source": {"ts": "source"}, "target": {"ts": "target"}}, "required": ["name", "source"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/Preview.ts b/apps/dashboard/src/client/forge/loomplane/codecs/Preview.ts index 1022f6cda..c01c85f41 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/Preview.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/Preview.ts @@ -1,9 +1,9 @@ import type { Codec } from '../codec-runtime'; -import { codec_Assignment } from './Assignment'; import { codec_ChangeInput } from './ChangeInput'; import { codec_CloudprofilesTarget } from './CloudprofilesTarget'; import { codec_DefaultPlacement } from './DefaultPlacement'; import { codec_Preview_blockers } from './Preview.blockers'; import { codec_Preview_environments } from './Preview.environments'; +import { codec_ProjectCloud } from './ProjectCloud'; -export const codec_Preview: Codec = {"kind": "object", "fields": {"after": {"ts": "after", "codec": () => codec_CloudprofilesTarget}, "after_assignment": {"ts": "afterAssignment", "codec": () => codec_Assignment}, "after_default": {"ts": "afterDefault", "codec": () => codec_DefaultPlacement}, "before": {"ts": "before", "codec": () => codec_CloudprofilesTarget}, "before_assignment": {"ts": "beforeAssignment", "codec": () => codec_Assignment}, "before_default": {"ts": "beforeDefault", "codec": () => codec_DefaultPlacement}, "blockers": {"ts": "blockers", "codec": () => codec_Preview_blockers}, "created_at": {"ts": "createdAt"}, "environments": {"ts": "environments", "codec": () => codec_Preview_environments}, "id": {"ts": "id"}, "input": {"ts": "input", "codec": () => codec_ChangeInput}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "reverts": {"ts": "reverts"}, "revision": {"ts": "revision"}}, "required": ["blockers", "created_at", "environments", "id", "input", "org_id", "project_id", "revision"]}; +export const codec_Preview: Codec = {"kind": "object", "fields": {"after": {"ts": "after", "codec": () => codec_CloudprofilesTarget}, "after_cloud": {"ts": "afterCloud", "codec": () => codec_ProjectCloud}, "after_default": {"ts": "afterDefault", "codec": () => codec_DefaultPlacement}, "before": {"ts": "before", "codec": () => codec_CloudprofilesTarget}, "before_cloud": {"ts": "beforeCloud", "codec": () => codec_ProjectCloud}, "before_default": {"ts": "beforeDefault", "codec": () => codec_DefaultPlacement}, "blockers": {"ts": "blockers", "codec": () => codec_Preview_blockers}, "created_at": {"ts": "createdAt"}, "environments": {"ts": "environments", "codec": () => codec_Preview_environments}, "id": {"ts": "id"}, "input": {"ts": "input", "codec": () => codec_ChangeInput}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "reverts": {"ts": "reverts"}, "revision": {"ts": "revision"}}, "required": ["blockers", "created_at", "environments", "id", "input", "org_id", "project_id", "revision"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/Assignment.targets.ts b/apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloud.targets.ts similarity index 51% rename from apps/dashboard/src/client/forge/loomplane/codecs/Assignment.targets.ts rename to apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloud.targets.ts index 6eb2d42a6..71f8514f7 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/Assignment.targets.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloud.targets.ts @@ -1,4 +1,4 @@ import type { Codec } from '../codec-runtime'; import { codec_CloudprofilesTarget } from './CloudprofilesTarget'; -export const codec_Assignment_targets: Codec = {"kind": "array", "items": () => codec_CloudprofilesTarget}; +export const codec_ProjectCloud_targets: Codec = {"kind": "array", "items": () => codec_CloudprofilesTarget}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloud.ts b/apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloud.ts new file mode 100644 index 000000000..a910a3c03 --- /dev/null +++ b/apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloud.ts @@ -0,0 +1,5 @@ +import type { Codec } from '../codec-runtime'; +import { codec_DefaultPlacement } from './DefaultPlacement'; +import { codec_ProjectCloud_targets } from './ProjectCloud.targets'; + +export const codec_ProjectCloud: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "cloud_revision": {"ts": "cloudRevision"}, "default": {"ts": "default"}, "default_placement": {"ts": "defaultPlacement", "codec": () => codec_DefaultPlacement}, "grant_revision": {"ts": "grantRevision"}, "name": {"ts": "name"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "targets": {"ts": "targets", "codec": () => codec_ProjectCloud_targets}}, "required": ["cloud_id", "cloud_revision", "default", "grant_revision", "name", "org_id", "project_id", "targets"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloudEvent.ts b/apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloudEvent.ts new file mode 100644 index 000000000..f8a168e4c --- /dev/null +++ b/apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloudEvent.ts @@ -0,0 +1,3 @@ +import type { Codec } from '../codec-runtime'; + +export const codec_ProjectCloudEvent: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}}, "required": ["cloud_id", "org_id", "project_id"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/codecs/ProjectGrant.ts b/apps/dashboard/src/client/forge/loomplane/codecs/ProjectGrant.ts index f28edd1d6..033991fc9 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/ProjectGrant.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/ProjectGrant.ts @@ -1,4 +1,4 @@ import type { Codec } from '../codec-runtime'; import { codec_ProjectGrant_target_ids } from './ProjectGrant.target_ids'; -export const codec_ProjectGrant: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "revision": {"ts": "revision"}, "revoked": {"ts": "revoked"}, "target_ids": {"ts": "targetIds", "codec": () => codec_ProjectGrant_target_ids}}, "required": ["cloud_id", "org_id", "project_id", "revision", "revoked", "target_ids"]}; +export const codec_ProjectGrant: Codec = {"kind": "object", "fields": {"cloud_id": {"ts": "cloudId"}, "default": {"ts": "default"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "revision": {"ts": "revision"}, "revoked": {"ts": "revoked"}, "target_ids": {"ts": "targetIds", "codec": () => codec_ProjectGrant_target_ids}}, "required": ["cloud_id", "default", "org_id", "project_id", "revision", "revoked", "target_ids"]}; diff --git a/apps/dashboard/src/client/forge/loomplane/entities.ts b/apps/dashboard/src/client/forge/loomplane/entities.ts index 76bfbff1d..b06ddd410 100644 --- a/apps/dashboard/src/client/forge/loomplane/entities.ts +++ b/apps/dashboard/src/client/forge/loomplane/entities.ts @@ -7,13 +7,11 @@ export const entities = { 'Analysis': { idField: 'id' }, 'AnalysisGraph': { idField: 'id' }, 'AnalysisList': { fields: { 'analyses': 'Analysis' } }, - 'Assignment': { fields: { 'targets': 'CloudprofilesTarget' } }, 'Backup': { idField: 'id' }, 'BackupList': { fields: { 'backups': 'Backup' } }, 'Binding': { idField: 'id' }, 'BindingList': { fields: { 'bindings': 'Binding' } }, 'BitbucketStatus': { fields: { 'workspaces': 'BitbucketWorkspaceView' } }, - 'BitbucketWorkspace': { idField: 'id' }, 'BitbucketWorkspaceView': { idField: 'id' }, 'CLIOrganization': { idField: 'id' }, 'CLIOrganizationList': { fields: { 'organizations': 'CLIOrganization' } }, @@ -30,6 +28,8 @@ export const entities = { 'CloudLocation': { idField: 'id' }, 'CloudLocationList': { fields: { 'locations': 'CloudLocation' } }, 'CloudSyncEvent': { idField: 'id' }, + 'CloudSyncList': { fields: { 'syncs': 'Sync' } }, + 'CloudTargetList': { fields: { 'targets': 'CloudprofilesTarget' } }, 'CloudinfraRoute': { idField: 'id' }, 'CloudprofilesTarget': { idField: 'id' }, 'ClusterCapacity': { idField: 'resourceId' }, @@ -44,6 +44,7 @@ export const entities = { 'ConversationList': { fields: { 'conversations': 'Conversation' } }, 'CreatedKey': { fields: { 'key': 'APIKey' } }, 'DNSZone': { idField: 'id' }, + 'DefaultCloud': { idField: 'projectId', fields: { 'cloud': 'ProjectCloud' } }, 'Delivery': { idField: 'id' }, 'DeliveryList': { fields: { 'items': 'Delivery' } }, 'DeployPreview': { fields: { 'entry': 'EntrySummary', 'server': 'Operation' } }, @@ -52,7 +53,10 @@ export const entities = { 'DeploymentsDeployment': { idField: 'id' }, 'DiscoverySource': { idField: 'id' }, 'DomainDetail': { fields: { 'domain': 'ZoneOverview', 'parent': 'ZoneOverview', 'proofZone': 'ZoneOverview', 'registration': 'Registration', 'subdomains': 'ZoneOverview' } }, - 'DomainOverview': { fields: { 'zones': 'ZoneOverview' } }, + 'DomainOperationList': { fields: { 'operations': 'RouteOperation' } }, + 'DomainOverview': { fields: { 'registrations': 'Registration', 'zones': 'ZoneOverview' } }, + 'DomainRouteList': { fields: { 'routes': 'CloudinfraRoute' } }, + 'EndpointList': { fields: { 'endpoints': 'CatalogconnectEndpoint' } }, 'EntryDetail': { idField: 'id' }, 'EntrySummary': { idField: 'id' }, 'Environment': { idField: 'id' }, @@ -88,6 +92,7 @@ export const entities = { 'ManagedRegistryView': { fields: { 'backups': 'ManagedRegistryBackup' } }, 'ManifestDraft': { idField: 'projectId' }, 'MemberPrerequisite': { idField: 'id' }, + 'ModelDeploymentList': { fields: { 'models': 'ModelsStatus' } }, 'ModelsStatus': { fields: { 'entry': 'EntrySummary' } }, 'MoveAll': { fields: { 'host': 'Host' } }, 'NativeInventory': { fields: { 'points': 'NativePoint', 'source': 'NativeSource' } }, @@ -108,6 +113,7 @@ export const entities = { 'NotificationCreated': { idField: 'id' }, 'NotificationList': { fields: { 'items': 'Notification' } }, 'Operation': { idField: 'id' }, + 'OperationList': { fields: { 'operations': 'Operation' } }, 'OperationResult': { fields: { 'instance': 'Instance', 'operation': 'FleetOperation' } }, 'OrgInvitation': { idField: 'id' }, 'OrgInvitationList': { fields: { 'invitations': 'OrgInvitation' } }, @@ -116,19 +122,23 @@ export const entities = { 'PendingNodeJoinToken': { idField: 'id' }, 'Plan': { idField: 'id', fields: { 'actions': 'Action' } }, 'PlanList': { fields: { 'plans': 'Plan' } }, + 'PlanningCloudList': { fields: { 'clouds': 'Profile' } }, 'PlanningTenantList': { fields: { 'tenants': 'FabriqloomTenant' } }, 'Policy': { idField: 'id' }, 'PolicyList': { fields: { 'policies': 'Policy' } }, 'Pool': { idField: 'id' }, - 'Preview': { idField: 'id', fields: { 'after': 'CloudprofilesTarget', 'afterAssignment': 'Assignment', 'before': 'CloudprofilesTarget', 'beforeAssignment': 'Assignment' } }, + 'PoolList': { fields: { 'pools': 'Pool' } }, + 'Preview': { idField: 'id', fields: { 'after': 'CloudprofilesTarget', 'afterCloud': 'ProjectCloud', 'before': 'CloudprofilesTarget', 'beforeCloud': 'ProjectCloud' } }, 'Profile': { idField: 'id' }, 'Project': { idField: 'id' }, + 'ProjectCloud': { fields: { 'targets': 'CloudprofilesTarget' } }, 'ProjectList': { fields: { 'projects': 'Project' } }, 'ProjectView': { idField: 'projectId', fields: { 'sources': 'SourceState' } }, 'ProjectZone': { idField: 'id' }, 'ProjectZoneList': { fields: { 'zones': 'ProjectZone' } }, 'ProviderKey': { idField: 'id' }, 'ProviderResource': { idField: 'id' }, + 'ProviderResourceList': { fields: { 'resources': 'ProviderResource', 'syncs': 'ProviderResourceSync' } }, 'ProviderResourceSync': { idField: 'id' }, 'ProviderZoneList': { fields: { 'zones': 'DNSZone' } }, 'PushDevice': { idField: 'id' }, @@ -137,12 +147,16 @@ export const entities = { 'Region': { idField: 'id' }, 'RegionList': { fields: { 'regions': 'Region' } }, 'Registration': { idField: 'id' }, + 'RegistrationList': { fields: { 'registrations': 'Registration' } }, 'RegistryList': { fields: { 'entries': 'EntrySummary' } }, 'ReleaseReport': { idField: 'id' }, 'ReleaseReportEvent': { idField: 'id' }, + 'ReleaseReportList': { fields: { 'reports': 'ReleaseReport' } }, 'Report': { idField: 'id' }, + 'ReportList': { fields: { 'reports': 'Report' } }, 'Request': { idField: 'id' }, 'RequestEvent': { idField: 'id' }, + 'RequestList': { fields: { 'requests': 'Request' } }, 'Resolution': { fields: { 'variables': 'ResolvedVariable' } }, 'ResolvedVariable': { fields: { 'overrides': 'Variable', 'variable': 'Variable' } }, 'Restore': { idField: 'id' }, @@ -159,6 +173,7 @@ export const entities = { 'ScalingPool': { fields: { 'pool': 'Pool' } }, 'Sent': { fields: { 'conversation': 'Conversation', 'task': 'Task' } }, 'Server': { idField: 'id' }, + 'ServerList': { fields: { 'servers': 'Server' } }, 'ServiceSuggestions': { idField: 'projectId' }, 'Source': { idField: 'id' }, 'SourceList': { fields: { 'sources': 'DiscoverySource' } }, @@ -175,10 +190,12 @@ export const entities = { 'TemplateRelease': { idField: 'id' }, 'Variable': { idField: 'id' }, 'VariableList': { fields: { 'variables': 'Variable' } }, + 'View': { fields: { 'providerKeys': 'ProviderKey' } }, 'Watch': { idField: 'id' }, 'WebhookEndpoint': { idField: 'id' }, 'WebhookEndpointList': { fields: { 'items': 'WebhookEndpoint' } }, 'WebhookEndpointSecret': { fields: { 'endpoint': 'WebhookEndpoint' } }, 'Zone': { idField: 'id', fields: { 'providerZone': 'DNSZone' } }, + 'ZoneList': { fields: { 'zones': 'Zone' } }, 'ZoneOverview': { fields: { 'zone': 'Zone' } }, } as const satisfies Record; diff --git a/apps/dashboard/src/client/forge/loomplane/hooks.ts b/apps/dashboard/src/client/forge/loomplane/hooks.ts index ec086165a..0ceec8ebd 100644 --- a/apps/dashboard/src/client/forge/loomplane/hooks.ts +++ b/apps/dashboard/src/client/forge/loomplane/hooks.ts @@ -10,7 +10,7 @@ import { query, mutation } from '@forge-go/client-core'; import { ops } from './ops'; -import type { APIKey, APIKeyList, ActivitySummary, AgentView, AgentsettingsStatus, AgentwatchStatus, Analysis, AnalysisGraph, AnalysisList, Backup, BackupList, Binding, BindingList, BitbucketRepositoryList, BitbucketStatus, BitbucketWorkspaceView, Board, CLIOrganizationList, CanaryReport, CapacityPolicyView, CapacityUsage, Card, CatalogKindList, CatalogconnectEndpoint, CloudCluster, CloudClusterOperation, CloudClusterOperationPage, CloudClusterPage, CloudLocation, CloudLocationList, CloudProjectGrantList, CloudSyncList, CloudTargetList, CloudinfraRoute, CloudinfraRouteStatus, CloudprofilesTarget, ClusterCapacity, ClusterOptions, ClusterPage, CompromisedRevoke, ConnectedRepositoryList, Connection, ConnectionList, ConnectionsCloudList, ConsumerKey, Conversation, ConversationList, Coverage, DeletionPreview, DeliveryList, DeployedList, DeploymentList, DeploymentsDeployment, DiscoverySource, DiscoverySummary, DomainDetail, DomainOfferList, DomainOperationList, DomainOverview, DomainRouteList, EdgeState, EndpointList, EntryDetail, Environment, EnvironmentCloud, EnvironmentConnections, EnvironmentList, EventPage, Expansion, ExpansionList, FabriqKeyList, FabriqloomStatus, FabriqloomTenant, FailedCleanup, Flag, FlagList, Fleet, FleetOperation, GPUInventory, GPUTargetList, GatewayList, GitHubInstallation, GitHubStatus, GitLabConnectionView, GitLabHostView, GitLabRepositoryList, GitLabStatus, GroupVerificationResult, History, Host, HostList, IdentitySession, InfrastructureStatus, Instance, InstancePage, JoinTokenList, KeylessSetup, LocationPolicy, LogPage, ManagedRegistryView, ManifestDraft, MemberPrerequisite, MetricSummary, ModelDeploymentList, ModelsStatus, NativeInventory, NativePITRWindow, NativeRecoveryCopies, NativeRecoverySources, NativeRestore, NativeRetentionPolicy, NativeRetentionPolicyState, NativeRetirement, NativeRetirementPage, Node, NodeAdoptionList, NodeList, NodeWorkloadList, NotificationList, OctopusStatus, Operation, OperationList, OrgInvitationList, OrgMemberList, Plan, PlanList, PlanningCloudList, PlanningTenantList, PlatformcloudTenantList, Policy, PolicyList, Pool, PoolList, Preferences, Preview, Profile, Project, ProjectDomainList, ProjectList, ProjectPermissions, ProjectView, ProjectZoneList, ProviderEnvironmentList, ProviderKey, ProviderList, ProviderResource, ProviderResourceList, ProviderResourceSync, ProviderZoneList, PublicConfig, PushConfig, PushDevice, Rebuild, RebuildList, Region, RegionList, Registration, RegistrationExtensionList, RegistrationList, RegistryList, ReleaseEvidence, ReleaseReport, ReleaseReportList, Report, ReportList, Request, RequestList, Resolution, Restore, RestoreList, RetentionPolicy, RetentionPolicyHistory, RetentionPolicyState, RetentionPreview, Retirement, RetirementHistory, RetirementPage, Revision, RevisionList, RollbackTarget, RouteOperation, RouteSummary, RuntimeAttachmentPage, Server, ServerList, ServerOptions, ServerUsage, ServiceSuggestions, SettingsView, SetupStatus, SignInAppList, Snapshot, Soak, SourceList, SpendReport, StorageVolumeList, Sync, TLSRenewalAuthority, Task, Team, TeamList, TemplateRelease, TrafficReport, TwoStep, Usage, Variable, VariableList, View, Watch, WebhookEndpointList, WorkspaceView, Zone, ZoneList } from './types'; +import type { APIKey, APIKeyList, ActivitySummary, AgentView, AgentsettingsStatus, AgentwatchStatus, Analysis, AnalysisGraph, AnalysisList, Backup, BackupList, Binding, BindingList, BitbucketRepositoryList, BitbucketStatus, BitbucketWorkspaceView, Board, CLIOrganizationList, CanaryReport, CapacityPolicyView, CapacityUsage, Card, CatalogKindList, CatalogconnectEndpoint, CloudCluster, CloudClusterOperation, CloudClusterOperationPage, CloudClusterPage, CloudLocation, CloudLocationList, CloudProjectGrantList, CloudSyncList, CloudTargetList, CloudinfraRoute, CloudinfraRouteStatus, CloudprofilesTarget, ClusterCapacity, ClusterOptions, ClusterPage, CompromisedRevoke, ConnectedRepositoryList, Connection, ConnectionList, ConnectionsCloudList, ConsumerKey, Conversation, ConversationList, Coverage, DefaultCloud, DeletionPreview, DeliveryList, DeployedList, DeploymentList, DeploymentsDeployment, DiscoverySource, DiscoverySummary, DomainDetail, DomainOfferList, DomainOperationList, DomainOverview, DomainRouteList, EdgeState, EndpointList, EntryDetail, Environment, EnvironmentConnections, EnvironmentList, EventPage, Expansion, ExpansionList, FabriqKeyList, FabriqloomStatus, FabriqloomTenant, FailedCleanup, Flag, FlagList, Fleet, FleetOperation, GPUInventory, GPUTargetList, GatewayList, GitHubInstallation, GitHubStatus, GitLabConnectionView, GitLabHostView, GitLabRepositoryList, GitLabStatus, GroupVerificationResult, History, Host, HostList, IdentitySession, InfrastructureStatus, Instance, InstancePage, JoinTokenList, KeylessSetup, LocationPolicy, LogPage, ManagedRegistryView, ManifestDraft, MemberPrerequisite, MetricSummary, ModelDeploymentList, ModelsStatus, NativeInventory, NativePITRWindow, NativeRecoveryCopies, NativeRecoverySources, NativeRestore, NativeRetentionPolicy, NativeRetentionPolicyState, NativeRetirement, NativeRetirementPage, Node, NodeAdoptionList, NodeList, NodeWorkloadList, NotificationList, OctopusStatus, Operation, OperationList, OrgInvitationList, OrgMemberList, Plan, PlanList, PlanningCloudList, PlanningTenantList, PlatformcloudTenantList, Policy, PolicyList, Pool, PoolList, Preferences, Preview, Profile, Project, ProjectDomainList, ProjectList, ProjectPermissions, ProjectView, ProjectZoneList, ProviderEnvironmentList, ProviderKey, ProviderList, ProviderResource, ProviderResourceList, ProviderResourceSync, ProviderZoneList, PublicConfig, PushConfig, PushDevice, Rebuild, RebuildList, Region, RegionList, Registration, RegistrationExtensionList, RegistrationList, RegistryList, ReleaseEvidence, ReleaseReport, ReleaseReportList, Report, ReportList, Request, RequestList, Resolution, Restore, RestoreList, RetentionPolicy, RetentionPolicyHistory, RetentionPolicyState, RetentionPreview, Retirement, RetirementHistory, RetirementPage, Revision, RevisionList, RollbackTarget, RouteOperation, RouteSummary, RuntimeAttachmentPage, Server, ServerList, ServerOptions, ServerUsage, ServiceSuggestions, SettingsView, SetupStatus, SignInAppList, Snapshot, Soak, SourceList, SpendReport, StorageVolumeList, Sync, TLSRenewalAuthority, Task, Team, TeamList, TemplateRelease, TrafficReport, TwoStep, Usage, Variable, VariableList, View, Watch, WebhookEndpointList, WorkspaceView, Zone, ZoneList } from './types'; export const useAccountTwoStepGet = query(ops['account.twoStep.get']); export const useActivityGet = query(ops['activity.get']); @@ -33,7 +33,6 @@ export const useAgentRequestsProvideSecret = mutation(ops['age export const useAgentStatusGet = query(ops['agentStatus.get']); export const useAgentTasksGet = query(ops['agentTasks.get']); export const useAgentTasksCancel = mutation(ops['agentTasks.cancel']); -export const useAgentTasksStream = query(ops['agentTasks.stream']); export const useAgentWatcherGet = query(ops['agentWatcher.get']); export const useAiModelDeploymentsList = query(ops['aiModelDeployments.list']); export const useAiModelsInspect = mutation(ops['aiModels.inspect']); @@ -313,13 +312,13 @@ export const useCloudsUsage = query(ops['clouds.usage']); export const useDbGatewaysList = query(ops['dbGateways.list']); export const useDbGatewaysPauseRoute = mutation(ops['dbGateways.pauseRoute']); export const useDbGatewaysResumeRoute = mutation(ops['dbGateways.resumeRoute']); +export const useDefaultCloudGet = query(ops['defaultCloud.get']); +export const useDefaultCloudPreview = mutation(ops['defaultCloud.preview']); export const useProjectsDeletion = query(ops['projects.deletion']); export const useDeploymentsList = query(ops['deployments.list']); export const useEnvironmentsList = query(ops['environments.list']); export const useEnvironmentsCreate = mutation(ops['environments.create']); export const useEnvironmentsDelete = mutation(ops['environments.delete']); -export const useEnvironmentCloudsGet = query(ops['environmentClouds.get']); -export const useEnvironmentCloudsPreview = mutation(ops['environmentClouds.preview']); export const useProviderEnvironmentsRetry = mutation(ops['providerEnvironments.retry']); export const useEnvironmentConnectionsGet = query(ops['environmentConnections.get']); export const useEnvironmentConnectionsChoose = mutation(ops['environmentConnections.choose']); @@ -428,9 +427,7 @@ export const usePushDevicesCreate = mutation(ops['push.d export const usePushDevicesUpdate = mutation(ops['push.devices.update']); export const usePushDevicesDelete = mutation(ops['push.devices.delete']); export const usePushDevicesTest = mutation(ops['push.devices.test']); -export const useRealtimeEvents = query(ops['realtime.events']); export const useRealtimeSnapshot = query(ops['realtime.snapshot']); -export const useRealtimeWs = query(ops['realtime.ws']); export const useReleaseReportsGet = query(ops['releaseReports.get']); export const useReleaseReportsCancel = mutation(ops['releaseReports.cancel']); export const useServiceRetirementsGet = query(ops['serviceRetirements.get']); diff --git a/apps/dashboard/src/client/forge/loomplane/hooks/useAgentTasksStream.ts b/apps/dashboard/src/client/forge/loomplane/hooks/useAgentTasksStream.ts deleted file mode 100644 index 5aa2152b2..000000000 --- a/apps/dashboard/src/client/forge/loomplane/hooks/useAgentTasksStream.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { query } from '@forge-go/client-core'; -import { op_agentTasks_stream } from '../ops/agentTasks.stream'; - -export const useAgentTasksStream = /*#__PURE__*/ query(op_agentTasks_stream); diff --git a/apps/dashboard/src/client/forge/loomplane/hooks/useDefaultCloudGet.ts b/apps/dashboard/src/client/forge/loomplane/hooks/useDefaultCloudGet.ts new file mode 100644 index 000000000..7986d3c30 --- /dev/null +++ b/apps/dashboard/src/client/forge/loomplane/hooks/useDefaultCloudGet.ts @@ -0,0 +1,5 @@ +import { query } from '@forge-go/client-core'; +import { op_defaultCloud_get } from '../ops/defaultCloud.get'; +import type { DefaultCloud } from '../types'; + +export const useDefaultCloudGet = /*#__PURE__*/ query(op_defaultCloud_get); diff --git a/apps/dashboard/src/client/forge/loomplane/hooks/useDefaultCloudPreview.ts b/apps/dashboard/src/client/forge/loomplane/hooks/useDefaultCloudPreview.ts new file mode 100644 index 000000000..3e7900147 --- /dev/null +++ b/apps/dashboard/src/client/forge/loomplane/hooks/useDefaultCloudPreview.ts @@ -0,0 +1,5 @@ +import { mutation } from '@forge-go/client-core'; +import { op_defaultCloud_preview } from '../ops/defaultCloud.preview'; +import type { Preview } from '../types'; + +export const useDefaultCloudPreview = /*#__PURE__*/ mutation(op_defaultCloud_preview); diff --git a/apps/dashboard/src/client/forge/loomplane/hooks/useEnvironmentCloudsGet.ts b/apps/dashboard/src/client/forge/loomplane/hooks/useEnvironmentCloudsGet.ts deleted file mode 100644 index da804e6e9..000000000 --- a/apps/dashboard/src/client/forge/loomplane/hooks/useEnvironmentCloudsGet.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { query } from '@forge-go/client-core'; -import { op_environmentClouds_get } from '../ops/environmentClouds.get'; -import type { EnvironmentCloud } from '../types'; - -export const useEnvironmentCloudsGet = /*#__PURE__*/ query(op_environmentClouds_get); diff --git a/apps/dashboard/src/client/forge/loomplane/hooks/useEnvironmentCloudsPreview.ts b/apps/dashboard/src/client/forge/loomplane/hooks/useEnvironmentCloudsPreview.ts deleted file mode 100644 index 85a9ba6db..000000000 --- a/apps/dashboard/src/client/forge/loomplane/hooks/useEnvironmentCloudsPreview.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { mutation } from '@forge-go/client-core'; -import { op_environmentClouds_preview } from '../ops/environmentClouds.preview'; -import type { Preview } from '../types'; - -export const useEnvironmentCloudsPreview = /*#__PURE__*/ mutation(op_environmentClouds_preview); diff --git a/apps/dashboard/src/client/forge/loomplane/hooks/useRealtimeEvents.ts b/apps/dashboard/src/client/forge/loomplane/hooks/useRealtimeEvents.ts deleted file mode 100644 index 1231c09d8..000000000 --- a/apps/dashboard/src/client/forge/loomplane/hooks/useRealtimeEvents.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { query } from '@forge-go/client-core'; -import { op_realtime_events } from '../ops/realtime.events'; - -export const useRealtimeEvents = /*#__PURE__*/ query(op_realtime_events); diff --git a/apps/dashboard/src/client/forge/loomplane/hooks/useRealtimeWs.ts b/apps/dashboard/src/client/forge/loomplane/hooks/useRealtimeWs.ts deleted file mode 100644 index 2ebd02d88..000000000 --- a/apps/dashboard/src/client/forge/loomplane/hooks/useRealtimeWs.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { query } from '@forge-go/client-core'; -import { op_realtime_ws } from '../ops/realtime.ws'; - -export const useRealtimeWs = /*#__PURE__*/ query(op_realtime_ws); diff --git a/apps/dashboard/src/client/forge/loomplane/ops.ts b/apps/dashboard/src/client/forge/loomplane/ops.ts index e31418bfa..138fd820c 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops.ts @@ -156,7 +156,9 @@ export const ops = { 'agentReports.list': { method: 'GET', path: '/api/v1/agent/reports', - provides: [], + entity: 'Report', + rootType: 'ReportList', + provides: ['Report:{id}', 'Report[]'], invalidates: [], responseCodec: CODECS['ReportList'], }, @@ -182,7 +184,9 @@ export const ops = { 'agentRequests.list': { method: 'GET', path: '/api/v1/agent/requests', - provides: [], + entity: 'Request', + rootType: 'RequestList', + provides: ['Request:{id}', 'Request[]'], invalidates: [], responseCodec: CODECS['RequestList'], }, @@ -259,12 +263,6 @@ export const ops = { invalidates: ['Task[]'], responseCodec: CODECS['Task'], }, - 'agentTasks.stream': { - method: 'GET', - path: '/api/v1/agent/tasks/{id}/stream', - provides: [], - invalidates: [], - }, 'agentWatcher.get': { method: 'GET', path: '/api/v1/agent/watcher', @@ -275,6 +273,7 @@ export const ops = { 'aiModelDeployments.list': { method: 'GET', path: '/api/v1/ai/models/deployments', + rootType: 'ModelDeploymentList', provides: [], invalidates: [], responseCodec: CODECS['ModelDeploymentList'], @@ -317,7 +316,9 @@ export const ops = { 'aiSettings.get': { method: 'GET', path: '/api/v1/ai/settings', - provides: [], + entity: 'ProviderKey', + rootType: 'View', + provides: ['ProviderKey:{id}', 'ProviderKey[]'], invalidates: [], responseCodec: CODECS['View'], }, @@ -347,6 +348,7 @@ export const ops = { 'aiSettings.setBudget': { method: 'PUT', path: '/api/v1/ai/settings/budget', + rootType: 'View', provides: [], invalidates: [], bodyCodec: CODECS['WorkspaceBudgetInputBody'], @@ -472,14 +474,16 @@ export const ops = { 'bitbucket.disconnect': { method: 'DELETE', path: '/api/v1/bitbucket/workspaces/{id}', - entity: 'BitbucketWorkspace', + entity: 'BitbucketWorkspaceView', provides: [], - invalidates: ['BitbucketWorkspace[]'], + invalidates: ['BitbucketWorkspaceView[]'], }, 'catalogEndpoints.list': { method: 'GET', path: '/api/v1/catalog/endpoints', - provides: [], + entity: 'CatalogconnectEndpoint', + rootType: 'EndpointList', + provides: ['CatalogconnectEndpoint:{id}', 'CatalogconnectEndpoint[]'], invalidates: [], responseCodec: CODECS['EndpointList'], }, @@ -535,7 +539,9 @@ export const ops = { 'organizationClouds.list': { method: 'GET', path: '/api/v1/clouds', - provides: [], + entity: 'Profile', + rootType: 'PlanningCloudList', + provides: ['Profile:{id}', 'Profile[]'], invalidates: [], responseCodec: CODECS['PlanningCloudList'], }, @@ -581,7 +587,9 @@ export const ops = { 'organizationCloudSyncs.list': { method: 'GET', path: '/api/v1/clouds/syncs', - provides: [], + entity: 'Sync', + rootType: 'CloudSyncList', + provides: ['Sync:{id}', 'Sync[]'], invalidates: [], responseCodec: CODECS['CloudSyncList'], }, @@ -718,7 +726,7 @@ export const ops = { entity: 'CloudClusterOperation', rootType: 'CloudClusterOperation', provides: ['CloudClusterOperation:{id}'], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterOperation[]', 'CloudClusterPage', 'RuntimeAttachmentPage'], + invalidates: ['CloudCluster:{res.resourceId}', 'CloudClusterOperation[]', 'CloudCluster[]', 'RuntimeAttachmentPage:{res.resourceId}'], bodyCodec: CODECS['ApplyInputBody'], responseCodec: CODECS['CloudClusterOperation'], }, @@ -728,7 +736,7 @@ export const ops = { entity: 'CloudClusterOperation', rootType: 'CloudClusterOperation', provides: ['CloudClusterOperation:{id}'], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterOperation[]', 'CloudClusterPage', 'RuntimeAttachmentPage'], + invalidates: ['CloudCluster:{res.resourceId}', 'CloudClusterOperation[]', 'CloudCluster[]', 'RuntimeAttachmentPage:{res.resourceId}'], responseCodec: CODECS['CloudClusterOperation'], }, 'clusterOperations.retry': { @@ -737,7 +745,7 @@ export const ops = { entity: 'CloudClusterOperation', rootType: 'CloudClusterOperation', provides: ['CloudClusterOperation:{id}'], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterOperation[]', 'CloudClusterPage', 'RuntimeAttachmentPage'], + invalidates: ['CloudCluster:{res.resourceId}', 'CloudClusterOperation[]', 'CloudCluster[]', 'RuntimeAttachmentPage:{res.resourceId}'], responseCodec: CODECS['CloudClusterOperation'], }, 'cloudClusters.options': { @@ -764,7 +772,7 @@ export const ops = { entity: 'CloudClusterOperation', rootType: 'CloudClusterOperation', provides: ['CloudClusterOperation:{id}'], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterOperation[]', 'CloudClusterPage', 'RuntimeAttachmentPage'], + invalidates: ['CloudClusterOperation[]', 'CloudCluster[]'], bodyCodec: CODECS['ClusterInputBody'], responseCodec: CODECS['CloudClusterOperation'], }, @@ -801,14 +809,14 @@ export const ops = { entity: 'ClusterCapacity', rootType: 'ClusterCapacity', provides: ['ClusterCapacity:{resourceId}'], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterPage', 'ClusterCapacity[]', 'RuntimeAttachmentPage'], + invalidates: ['CloudCluster:{res.resourceId}', 'CloudClusterOperation[]', 'CloudCluster[]', 'ClusterCapacity[]', 'RuntimeAttachmentPage:{res.resourceId}'], responseCodec: CODECS['ClusterCapacity'], }, 'cloudClusters.retirementPreview': { method: 'POST', path: '/api/v1/clouds/{cloudId}/clusters/{clusterId}/retirement/preview', provides: [], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterPage', 'RuntimeAttachmentPage'], + invalidates: ['CloudCluster:{res.resourceId}', 'CloudClusterOperation[]', 'CloudCluster[]', 'RuntimeAttachmentPage:{res.resourceId}'], bodyCodec: CODECS['ClusterRetirementPreviewInputBody'], responseCodec: CODECS['ClusterRetirementReview'], }, @@ -844,7 +852,9 @@ export const ops = { 'infrastructureOperations.list': { method: 'GET', path: '/api/v1/clouds/{cloudId}/infrastructure-operations', - provides: [], + entity: 'Operation', + rootType: 'OperationList', + provides: ['Operation:{id}', 'Operation[]'], invalidates: [], responseCodec: CODECS['OperationList'], }, @@ -987,7 +997,9 @@ export const ops = { 'cloudPools.list': { method: 'GET', path: '/api/v1/clouds/{cloudId}/pools', - provides: [], + entity: 'Pool', + rootType: 'PoolList', + provides: ['Pool:{id}', 'Pool[]'], invalidates: [], responseCodec: CODECS['PoolList'], }, @@ -1052,7 +1064,9 @@ export const ops = { 'cloudServers.list': { method: 'GET', path: '/api/v1/clouds/{cloudId}/servers', - provides: [], + entity: 'Server', + rootType: 'ServerList', + provides: ['Server:{id}', 'Server[]'], invalidates: [], responseCodec: CODECS['ServerList'], }, @@ -1102,7 +1116,9 @@ export const ops = { 'organizationCloudTargets.list': { method: 'GET', path: '/api/v1/clouds/{cloudId}/targets', - provides: [], + entity: 'CloudprofilesTarget', + rootType: 'CloudTargetList', + provides: ['CloudprofilesTarget:{id}', 'CloudprofilesTarget[]'], invalidates: [], responseCodec: CODECS['CloudTargetList'], }, @@ -1451,7 +1467,9 @@ export const ops = { 'dnsZones.list': { method: 'GET', path: '/api/v1/dns-zones', - provides: [], + entity: 'Zone', + rootType: 'ZoneList', + provides: ['Zone:{id}', 'Zone[]'], invalidates: [], responseCodec: CODECS['ZoneList'], }, @@ -1543,7 +1561,9 @@ export const ops = { 'domainRegistrations.list': { method: 'GET', path: '/api/v1/domain-registrations', - provides: [], + entity: 'Registration', + rootType: 'RegistrationList', + provides: ['Registration:{id}', 'Registration[]'], invalidates: [], responseCodec: CODECS['RegistrationList'], }, @@ -1589,8 +1609,9 @@ export const ops = { 'domains.overview': { method: 'GET', path: '/api/v1/domains', + entity: 'Registration', rootType: 'DomainOverview', - provides: [], + provides: ['Registration:{id}', 'Registration[]'], invalidates: [], responseCodec: CODECS['DomainOverview'], }, @@ -2440,7 +2461,9 @@ export const ops = { 'cloudSyncs.list': { method: 'GET', path: '/api/v1/projects/{id}/cloud-syncs', - provides: [], + entity: 'Sync', + rootType: 'CloudSyncList', + provides: ['Sync:{id}', 'Sync[]'], invalidates: [], responseCodec: CODECS['CloudSyncList'], }, @@ -2494,7 +2517,9 @@ export const ops = { 'clouds.list': { method: 'GET', path: '/api/v1/projects/{id}/clouds', - provides: [], + entity: 'Profile', + rootType: 'PlanningCloudList', + provides: ['Profile:{id}', 'Profile[]'], invalidates: [], responseCodec: CODECS['PlanningCloudList'], }, @@ -2564,7 +2589,9 @@ export const ops = { 'cloudTargets.list': { method: 'GET', path: '/api/v1/projects/{id}/clouds/{cloudId}/targets', - provides: [], + entity: 'CloudprofilesTarget', + rootType: 'CloudTargetList', + provides: ['CloudprofilesTarget:{id}', 'CloudprofilesTarget[]'], invalidates: [], responseCodec: CODECS['CloudTargetList'], }, @@ -2637,6 +2664,25 @@ export const ops = { invalidates: ['RouteSummary[]'], responseCodec: CODECS['RouteSummary'], }, + 'defaultCloud.get': { + method: 'GET', + path: '/api/v1/projects/{id}/default-cloud', + entity: 'DefaultCloud', + rootType: 'DefaultCloud', + provides: ['DefaultCloud:{projectId}'], + invalidates: [], + responseCodec: CODECS['DefaultCloud'], + }, + 'defaultCloud.preview': { + method: 'POST', + path: '/api/v1/projects/{id}/default-cloud/preview', + entity: 'Preview', + rootType: 'Preview', + provides: ['Preview:{id}'], + invalidates: ['Preview[]'], + bodyCodec: CODECS['DefaultCloudInputBody'], + responseCodec: CODECS['Preview'], + }, 'projects.deletion': { method: 'GET', path: '/api/v1/projects/{id}/deletion', @@ -2679,23 +2725,6 @@ export const ops = { provides: [], invalidates: ['Environment[]'], }, - 'environmentClouds.get': { - method: 'GET', - path: '/api/v1/projects/{id}/environments/{environmentId}/cloud', - provides: [], - invalidates: [], - responseCodec: CODECS['EnvironmentCloud'], - }, - 'environmentClouds.preview': { - method: 'POST', - path: '/api/v1/projects/{id}/environments/{environmentId}/cloud/preview', - entity: 'Preview', - rootType: 'Preview', - provides: ['Preview:{id}'], - invalidates: ['Preview[]'], - bodyCodec: CODECS['EnvironmentCloudInputBody'], - responseCodec: CODECS['Preview'], - }, 'providerEnvironments.retry': { method: 'POST', path: '/api/v1/projects/{id}/environments/{environmentId}/provider-environments/retry', @@ -2917,7 +2946,9 @@ export const ops = { 'releaseReports.list': { method: 'GET', path: '/api/v1/projects/{id}/release-reports', - provides: [], + entity: 'ReleaseReport', + rootType: 'ReleaseReportList', + provides: ['ReleaseReport:{id}', 'ReleaseReport[]'], invalidates: [], responseCodec: CODECS['ReleaseReportList'], }, @@ -3010,9 +3041,9 @@ export const ops = { 'sources.delete': { method: 'DELETE', path: '/api/v1/projects/{id}/sources/{alias}', - entity: 'Source', + entity: 'DiscoverySource', provides: [], - invalidates: ['Source[]'], + invalidates: ['DiscoverySource[]'], }, 'projects.setTeam': { method: 'PUT', @@ -3063,7 +3094,9 @@ export const ops = { 'domainRoutes.list': { method: 'GET', path: '/api/v1/projects/{projectId}/domain-routes', - provides: [], + entity: 'CloudinfraRoute', + rootType: 'DomainRouteList', + provides: ['CloudinfraRoute:{id}', 'CloudinfraRoute[]'], invalidates: [], responseCodec: CODECS['DomainRouteList'], }, @@ -3111,7 +3144,9 @@ export const ops = { 'domainRoutes.history': { method: 'GET', path: '/api/v1/projects/{projectId}/domain-routes/{routeId}/operations', - provides: [], + entity: 'RouteOperation', + rootType: 'DomainOperationList', + provides: ['RouteOperation:{id}', 'RouteOperation[]'], invalidates: [], responseCodec: CODECS['DomainOperationList'], }, @@ -3545,6 +3580,7 @@ export const ops = { 'providerResources.list': { method: 'GET', path: '/api/v1/provider-resources', + rootType: 'ProviderResourceList', provides: [], invalidates: [], responseCodec: CODECS['ProviderResourceList'], @@ -3622,12 +3658,6 @@ export const ops = { invalidates: [], responseCodec: CODECS['TestPushResult'], }, - 'realtime.events': { - method: 'GET', - path: '/api/v1/realtime/events', - provides: [], - invalidates: [], - }, 'realtime.snapshot': { method: 'GET', path: '/api/v1/realtime/snapshot', @@ -3635,12 +3665,6 @@ export const ops = { invalidates: [], responseCodec: CODECS['Snapshot'], }, - 'realtime.ws': { - method: 'GET', - path: '/api/v1/realtime/ws', - provides: [], - invalidates: [], - }, 'releaseReports.get': { method: 'GET', path: '/api/v1/release-reports/{id}', @@ -3938,13 +3962,11 @@ export const entities = { 'Analysis': { idField: 'id' }, 'AnalysisGraph': { idField: 'id' }, 'AnalysisList': { fields: { 'analyses': 'Analysis' } }, - 'Assignment': { fields: { 'targets': 'CloudprofilesTarget' } }, 'Backup': { idField: 'id' }, 'BackupList': { fields: { 'backups': 'Backup' } }, 'Binding': { idField: 'id' }, 'BindingList': { fields: { 'bindings': 'Binding' } }, 'BitbucketStatus': { fields: { 'workspaces': 'BitbucketWorkspaceView' } }, - 'BitbucketWorkspace': { idField: 'id' }, 'BitbucketWorkspaceView': { idField: 'id' }, 'CLIOrganization': { idField: 'id' }, 'CLIOrganizationList': { fields: { 'organizations': 'CLIOrganization' } }, @@ -3961,6 +3983,8 @@ export const entities = { 'CloudLocation': { idField: 'id' }, 'CloudLocationList': { fields: { 'locations': 'CloudLocation' } }, 'CloudSyncEvent': { idField: 'id' }, + 'CloudSyncList': { fields: { 'syncs': 'Sync' } }, + 'CloudTargetList': { fields: { 'targets': 'CloudprofilesTarget' } }, 'CloudinfraRoute': { idField: 'id' }, 'CloudprofilesTarget': { idField: 'id' }, 'ClusterCapacity': { idField: 'resourceId' }, @@ -3975,6 +3999,7 @@ export const entities = { 'ConversationList': { fields: { 'conversations': 'Conversation' } }, 'CreatedKey': { fields: { 'key': 'APIKey' } }, 'DNSZone': { idField: 'id' }, + 'DefaultCloud': { idField: 'projectId', fields: { 'cloud': 'ProjectCloud' } }, 'Delivery': { idField: 'id' }, 'DeliveryList': { fields: { 'items': 'Delivery' } }, 'DeployPreview': { fields: { 'entry': 'EntrySummary', 'server': 'Operation' } }, @@ -3983,7 +4008,10 @@ export const entities = { 'DeploymentsDeployment': { idField: 'id' }, 'DiscoverySource': { idField: 'id' }, 'DomainDetail': { fields: { 'domain': 'ZoneOverview', 'parent': 'ZoneOverview', 'proofZone': 'ZoneOverview', 'registration': 'Registration', 'subdomains': 'ZoneOverview' } }, - 'DomainOverview': { fields: { 'zones': 'ZoneOverview' } }, + 'DomainOperationList': { fields: { 'operations': 'RouteOperation' } }, + 'DomainOverview': { fields: { 'registrations': 'Registration', 'zones': 'ZoneOverview' } }, + 'DomainRouteList': { fields: { 'routes': 'CloudinfraRoute' } }, + 'EndpointList': { fields: { 'endpoints': 'CatalogconnectEndpoint' } }, 'EntryDetail': { idField: 'id' }, 'EntrySummary': { idField: 'id' }, 'Environment': { idField: 'id' }, @@ -4019,6 +4047,7 @@ export const entities = { 'ManagedRegistryView': { fields: { 'backups': 'ManagedRegistryBackup' } }, 'ManifestDraft': { idField: 'projectId' }, 'MemberPrerequisite': { idField: 'id' }, + 'ModelDeploymentList': { fields: { 'models': 'ModelsStatus' } }, 'ModelsStatus': { fields: { 'entry': 'EntrySummary' } }, 'MoveAll': { fields: { 'host': 'Host' } }, 'NativeInventory': { fields: { 'points': 'NativePoint', 'source': 'NativeSource' } }, @@ -4039,6 +4068,7 @@ export const entities = { 'NotificationCreated': { idField: 'id' }, 'NotificationList': { fields: { 'items': 'Notification' } }, 'Operation': { idField: 'id' }, + 'OperationList': { fields: { 'operations': 'Operation' } }, 'OperationResult': { fields: { 'instance': 'Instance', 'operation': 'FleetOperation' } }, 'OrgInvitation': { idField: 'id' }, 'OrgInvitationList': { fields: { 'invitations': 'OrgInvitation' } }, @@ -4047,19 +4077,23 @@ export const entities = { 'PendingNodeJoinToken': { idField: 'id' }, 'Plan': { idField: 'id', fields: { 'actions': 'Action' } }, 'PlanList': { fields: { 'plans': 'Plan' } }, + 'PlanningCloudList': { fields: { 'clouds': 'Profile' } }, 'PlanningTenantList': { fields: { 'tenants': 'FabriqloomTenant' } }, 'Policy': { idField: 'id' }, 'PolicyList': { fields: { 'policies': 'Policy' } }, 'Pool': { idField: 'id' }, - 'Preview': { idField: 'id', fields: { 'after': 'CloudprofilesTarget', 'afterAssignment': 'Assignment', 'before': 'CloudprofilesTarget', 'beforeAssignment': 'Assignment' } }, + 'PoolList': { fields: { 'pools': 'Pool' } }, + 'Preview': { idField: 'id', fields: { 'after': 'CloudprofilesTarget', 'afterCloud': 'ProjectCloud', 'before': 'CloudprofilesTarget', 'beforeCloud': 'ProjectCloud' } }, 'Profile': { idField: 'id' }, 'Project': { idField: 'id' }, + 'ProjectCloud': { fields: { 'targets': 'CloudprofilesTarget' } }, 'ProjectList': { fields: { 'projects': 'Project' } }, 'ProjectView': { idField: 'projectId', fields: { 'sources': 'SourceState' } }, 'ProjectZone': { idField: 'id' }, 'ProjectZoneList': { fields: { 'zones': 'ProjectZone' } }, 'ProviderKey': { idField: 'id' }, 'ProviderResource': { idField: 'id' }, + 'ProviderResourceList': { fields: { 'resources': 'ProviderResource', 'syncs': 'ProviderResourceSync' } }, 'ProviderResourceSync': { idField: 'id' }, 'ProviderZoneList': { fields: { 'zones': 'DNSZone' } }, 'PushDevice': { idField: 'id' }, @@ -4068,12 +4102,16 @@ export const entities = { 'Region': { idField: 'id' }, 'RegionList': { fields: { 'regions': 'Region' } }, 'Registration': { idField: 'id' }, + 'RegistrationList': { fields: { 'registrations': 'Registration' } }, 'RegistryList': { fields: { 'entries': 'EntrySummary' } }, 'ReleaseReport': { idField: 'id' }, 'ReleaseReportEvent': { idField: 'id' }, + 'ReleaseReportList': { fields: { 'reports': 'ReleaseReport' } }, 'Report': { idField: 'id' }, + 'ReportList': { fields: { 'reports': 'Report' } }, 'Request': { idField: 'id' }, 'RequestEvent': { idField: 'id' }, + 'RequestList': { fields: { 'requests': 'Request' } }, 'Resolution': { fields: { 'variables': 'ResolvedVariable' } }, 'ResolvedVariable': { fields: { 'overrides': 'Variable', 'variable': 'Variable' } }, 'Restore': { idField: 'id' }, @@ -4090,6 +4128,7 @@ export const entities = { 'ScalingPool': { fields: { 'pool': 'Pool' } }, 'Sent': { fields: { 'conversation': 'Conversation', 'task': 'Task' } }, 'Server': { idField: 'id' }, + 'ServerList': { fields: { 'servers': 'Server' } }, 'ServiceSuggestions': { idField: 'projectId' }, 'Source': { idField: 'id' }, 'SourceList': { fields: { 'sources': 'DiscoverySource' } }, @@ -4106,11 +4145,13 @@ export const entities = { 'TemplateRelease': { idField: 'id' }, 'Variable': { idField: 'id' }, 'VariableList': { fields: { 'variables': 'Variable' } }, + 'View': { fields: { 'providerKeys': 'ProviderKey' } }, 'Watch': { idField: 'id' }, 'WebhookEndpoint': { idField: 'id' }, 'WebhookEndpointList': { fields: { 'items': 'WebhookEndpoint' } }, 'WebhookEndpointSecret': { fields: { 'endpoint': 'WebhookEndpoint' } }, 'Zone': { idField: 'id', fields: { 'providerZone': 'DNSZone' } }, + 'ZoneList': { fields: { 'zones': 'Zone' } }, 'ZoneOverview': { fields: { 'zone': 'Zone' } }, } as const satisfies Record; @@ -4155,19 +4196,19 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/events', message: 'source.updated', - entity: 'Source', + entity: 'DiscoverySource', intent: 'upsert', - invalidates: ['Source[]'], - decode: (payload: unknown) => decode(payload, CODECS['Source']), + invalidates: ['DiscoverySource[]'], + decode: (payload: unknown) => decode(payload, CODECS['DiscoverySource']), }, { kind: 'entity', channel: '/api/v1/realtime/events', message: 'source.deleted', - entity: 'Source', + entity: 'DiscoverySource', intent: 'evict', - invalidates: ['Source[]'], - decode: (payload: unknown) => decode(payload, CODECS['Source']), + invalidates: ['DiscoverySource[]'], + decode: (payload: unknown) => decode(payload, CODECS['DiscoverySource']), }, { kind: 'entity', @@ -4263,19 +4304,19 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/events', message: 'deployment.updated', - entity: 'Deployment', + entity: 'DeploymentsDeployment', intent: 'upsert', - invalidates: ['Deployment[]', 'Instance[]'], - decode: (payload: unknown) => decode(payload, CODECS['Deployment']), + invalidates: ['DeploymentsDeployment[]', 'Instance[]'], + decode: (payload: unknown) => decode(payload, CODECS['DeploymentsDeployment']), }, { kind: 'entity', channel: '/api/v1/realtime/events', message: 'deployment.deleted', - entity: 'Deployment', + entity: 'DeploymentsDeployment', intent: 'evict', - invalidates: ['Deployment[]'], - decode: (payload: unknown) => decode(payload, CODECS['Deployment']), + invalidates: ['DeploymentsDeployment[]'], + decode: (payload: unknown) => decode(payload, CODECS['DeploymentsDeployment']), }, { kind: 'entity', @@ -4283,7 +4324,7 @@ export const streams = [ message: 'canary_verdict.updated', entity: 'CanaryVerdict', intent: 'upsert', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -4292,7 +4333,7 @@ export const streams = [ message: 'canary_verdict.deleted', entity: 'CanaryVerdict', intent: 'evict', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -4335,28 +4376,28 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/events', message: 'cloud_target.updated', - entity: 'Target', + entity: 'CloudprofilesTarget', intent: 'upsert', - invalidates: ['Target[]'], - decode: (payload: unknown) => decode(payload, CODECS['Target']), + invalidates: ['CloudprofilesTarget[]'], + decode: (payload: unknown) => decode(payload, CODECS['CloudprofilesTarget']), }, { kind: 'entity', channel: '/api/v1/realtime/events', message: 'cloud_target.deleted', - entity: 'Target', + entity: 'CloudprofilesTarget', intent: 'evict', - invalidates: ['Target[]'], - decode: (payload: unknown) => decode(payload, CODECS['Target']), + invalidates: ['CloudprofilesTarget[]'], + decode: (payload: unknown) => decode(payload, CODECS['CloudprofilesTarget']), }, { kind: 'entity', channel: '/api/v1/realtime/events', - message: 'environment_cloud.updated', - entity: 'EnvironmentCloudEvent', + message: 'project_cloud.updated', + entity: 'ProjectCloudEvent', intent: 'patch', - invalidates: ['EnvironmentCloud'], - decode: (payload: unknown) => decode(payload, CODECS['EnvironmentCloudEvent']), + invalidates: ['DefaultCloud:{projectId}'], + decode: (payload: unknown) => decode(payload, CODECS['ProjectCloudEvent']), }, { kind: 'entity', @@ -4364,7 +4405,7 @@ export const streams = [ message: 'cloud_sync.updated', entity: 'CloudSyncEvent', intent: 'patch', - invalidates: ['Sync', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'DefaultCloud:{projectId}'], decode: (payload: unknown) => decode(payload, CODECS['CloudSyncEvent']), }, { @@ -4373,7 +4414,7 @@ export const streams = [ message: 'cloud_cluster.updated', entity: 'ClusterChange', intent: 'patch', - invalidates: ['CloudCluster', 'CloudClusterPage', 'CloudClusterOperation', 'CloudClusterOperationPage', 'Target', 'Target[]', 'Connection', 'Connection[]', 'Profile', 'Profile[]'], + invalidates: ['CloudCluster:{resourceId}', 'CloudCluster[]', 'CloudClusterOperation:{operationId}', 'CloudClusterOperation[]', 'CloudprofilesTarget[]', 'Connection[]', 'Profile:{cloudId}'], decode: (payload: unknown) => decode(payload, CODECS['ClusterChange']), }, { @@ -4382,7 +4423,7 @@ export const streams = [ message: 'cloud_capacity.updated', entity: 'CapacityChange', intent: 'patch', - invalidates: ['CapacityPolicyView:{cloud_id}', 'CapacityUsage:{cloud_id}', 'Expansion[]'], + invalidates: ['CapacityPolicyView:{cloudId}', 'CapacityUsage:{cloudId}', 'Expansion[]'], decode: (payload: unknown) => decode(payload, CODECS['CapacityChange']), }, { @@ -4391,7 +4432,7 @@ export const streams = [ message: 'notification.created', entity: 'NotificationCreated', intent: 'upsert', - invalidates: ['NotificationList'], + invalidates: ['Notification[]'], decode: (payload: unknown) => decode(payload, CODECS['NotificationCreated']), }, { @@ -4408,8 +4449,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'agent_task.updated', entity: 'TaskEvent', - intent: 'upsert', - invalidates: ['AgentTask', 'AgentTask[]'], + intent: 'patch', + invalidates: ['Task:{id}'], decode: (payload: unknown) => decode(payload, CODECS['TaskEvent']), }, { @@ -4417,8 +4458,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'agent_task.deleted', entity: 'TaskEvent', - intent: 'evict', - invalidates: ['TaskEvent[]'], + intent: 'patch', + invalidates: ['Task:{id}'], decode: (payload: unknown) => decode(payload, CODECS['TaskEvent']), }, { @@ -4427,7 +4468,7 @@ export const streams = [ message: 'agent_report.updated', entity: 'Report', intent: 'upsert', - invalidates: ['AgentReport', 'AgentReport[]'], + invalidates: ['Report[]'], decode: (payload: unknown) => decode(payload, CODECS['Report']), }, { @@ -4444,8 +4485,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'agent_request.updated', entity: 'RequestEvent', - intent: 'upsert', - invalidates: ['AgentRequest', 'AgentRequest[]'], + intent: 'patch', + invalidates: ['Request:{id}', 'Request[]'], decode: (payload: unknown) => decode(payload, CODECS['RequestEvent']), }, { @@ -4453,8 +4494,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'agent_request.deleted', entity: 'RequestEvent', - intent: 'evict', - invalidates: ['RequestEvent[]'], + intent: 'patch', + invalidates: ['Request:{id}', 'Request[]'], decode: (payload: unknown) => decode(payload, CODECS['RequestEvent']), }, { @@ -4462,8 +4503,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'release_report.updated', entity: 'ReleaseReportEvent', - intent: 'upsert', - invalidates: ['ReleaseReport', 'ReleaseReport[]'], + intent: 'patch', + invalidates: ['ReleaseReport:{id}', 'ReleaseReport[]'], decode: (payload: unknown) => decode(payload, CODECS['ReleaseReportEvent']), }, { @@ -4471,8 +4512,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'release_report.deleted', entity: 'ReleaseReportEvent', - intent: 'evict', - invalidates: ['ReleaseReport', 'ReleaseReport[]'], + intent: 'patch', + invalidates: ['ReleaseReport:{id}', 'ReleaseReport[]'], decode: (payload: unknown) => decode(payload, CODECS['ReleaseReportEvent']), }, { @@ -4533,19 +4574,19 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/ws', message: 'source.updated', - entity: 'Source', + entity: 'DiscoverySource', intent: 'upsert', - invalidates: ['Source[]'], - decode: (payload: unknown) => decode(payload, CODECS['Source']), + invalidates: ['DiscoverySource[]'], + decode: (payload: unknown) => decode(payload, CODECS['DiscoverySource']), }, { kind: 'entity', channel: '/api/v1/realtime/ws', message: 'source.deleted', - entity: 'Source', + entity: 'DiscoverySource', intent: 'evict', - invalidates: ['Source[]'], - decode: (payload: unknown) => decode(payload, CODECS['Source']), + invalidates: ['DiscoverySource[]'], + decode: (payload: unknown) => decode(payload, CODECS['DiscoverySource']), }, { kind: 'entity', @@ -4641,19 +4682,19 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/ws', message: 'deployment.updated', - entity: 'Deployment', + entity: 'DeploymentsDeployment', intent: 'upsert', - invalidates: ['Deployment[]', 'Instance[]'], - decode: (payload: unknown) => decode(payload, CODECS['Deployment']), + invalidates: ['DeploymentsDeployment[]', 'Instance[]'], + decode: (payload: unknown) => decode(payload, CODECS['DeploymentsDeployment']), }, { kind: 'entity', channel: '/api/v1/realtime/ws', message: 'deployment.deleted', - entity: 'Deployment', + entity: 'DeploymentsDeployment', intent: 'evict', - invalidates: ['Deployment[]'], - decode: (payload: unknown) => decode(payload, CODECS['Deployment']), + invalidates: ['DeploymentsDeployment[]'], + decode: (payload: unknown) => decode(payload, CODECS['DeploymentsDeployment']), }, { kind: 'entity', @@ -4661,7 +4702,7 @@ export const streams = [ message: 'canary_verdict.updated', entity: 'CanaryVerdict', intent: 'upsert', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -4670,7 +4711,7 @@ export const streams = [ message: 'canary_verdict.deleted', entity: 'CanaryVerdict', intent: 'evict', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -4713,28 +4754,28 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/ws', message: 'cloud_target.updated', - entity: 'Target', + entity: 'CloudprofilesTarget', intent: 'upsert', - invalidates: ['Target[]'], - decode: (payload: unknown) => decode(payload, CODECS['Target']), + invalidates: ['CloudprofilesTarget[]'], + decode: (payload: unknown) => decode(payload, CODECS['CloudprofilesTarget']), }, { kind: 'entity', channel: '/api/v1/realtime/ws', message: 'cloud_target.deleted', - entity: 'Target', + entity: 'CloudprofilesTarget', intent: 'evict', - invalidates: ['Target[]'], - decode: (payload: unknown) => decode(payload, CODECS['Target']), + invalidates: ['CloudprofilesTarget[]'], + decode: (payload: unknown) => decode(payload, CODECS['CloudprofilesTarget']), }, { kind: 'entity', channel: '/api/v1/realtime/ws', - message: 'environment_cloud.updated', - entity: 'EnvironmentCloudEvent', + message: 'project_cloud.updated', + entity: 'ProjectCloudEvent', intent: 'patch', - invalidates: ['EnvironmentCloud'], - decode: (payload: unknown) => decode(payload, CODECS['EnvironmentCloudEvent']), + invalidates: ['DefaultCloud:{projectId}'], + decode: (payload: unknown) => decode(payload, CODECS['ProjectCloudEvent']), }, { kind: 'entity', @@ -4742,7 +4783,7 @@ export const streams = [ message: 'cloud_sync.updated', entity: 'CloudSyncEvent', intent: 'patch', - invalidates: ['Sync', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'DefaultCloud:{projectId}'], decode: (payload: unknown) => decode(payload, CODECS['CloudSyncEvent']), }, { @@ -4751,7 +4792,7 @@ export const streams = [ message: 'cloud_cluster.updated', entity: 'ClusterChange', intent: 'patch', - invalidates: ['CloudCluster', 'CloudClusterPage', 'CloudClusterOperation', 'CloudClusterOperationPage', 'Target', 'Target[]', 'Connection', 'Connection[]', 'Profile', 'Profile[]'], + invalidates: ['CloudCluster:{resourceId}', 'CloudCluster[]', 'CloudClusterOperation:{operationId}', 'CloudClusterOperation[]', 'CloudprofilesTarget[]', 'Connection[]', 'Profile:{cloudId}'], decode: (payload: unknown) => decode(payload, CODECS['ClusterChange']), }, { @@ -4760,7 +4801,7 @@ export const streams = [ message: 'cloud_capacity.updated', entity: 'CapacityChange', intent: 'patch', - invalidates: ['CapacityPolicyView:{cloud_id}', 'CapacityUsage:{cloud_id}', 'Expansion[]'], + invalidates: ['CapacityPolicyView:{cloudId}', 'CapacityUsage:{cloudId}', 'Expansion[]'], decode: (payload: unknown) => decode(payload, CODECS['CapacityChange']), }, { @@ -4769,7 +4810,7 @@ export const streams = [ message: 'notification.created', entity: 'NotificationCreated', intent: 'upsert', - invalidates: ['NotificationList'], + invalidates: ['Notification[]'], decode: (payload: unknown) => decode(payload, CODECS['NotificationCreated']), }, { @@ -4786,8 +4827,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'agent_task.updated', entity: 'TaskEvent', - intent: 'upsert', - invalidates: ['AgentTask', 'AgentTask[]'], + intent: 'patch', + invalidates: ['Task:{id}'], decode: (payload: unknown) => decode(payload, CODECS['TaskEvent']), }, { @@ -4795,8 +4836,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'agent_task.deleted', entity: 'TaskEvent', - intent: 'evict', - invalidates: ['TaskEvent[]'], + intent: 'patch', + invalidates: ['Task:{id}'], decode: (payload: unknown) => decode(payload, CODECS['TaskEvent']), }, { @@ -4805,7 +4846,7 @@ export const streams = [ message: 'agent_report.updated', entity: 'Report', intent: 'upsert', - invalidates: ['AgentReport', 'AgentReport[]'], + invalidates: ['Report[]'], decode: (payload: unknown) => decode(payload, CODECS['Report']), }, { @@ -4822,8 +4863,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'agent_request.updated', entity: 'RequestEvent', - intent: 'upsert', - invalidates: ['AgentRequest', 'AgentRequest[]'], + intent: 'patch', + invalidates: ['Request:{id}', 'Request[]'], decode: (payload: unknown) => decode(payload, CODECS['RequestEvent']), }, { @@ -4831,8 +4872,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'agent_request.deleted', entity: 'RequestEvent', - intent: 'evict', - invalidates: ['RequestEvent[]'], + intent: 'patch', + invalidates: ['Request:{id}', 'Request[]'], decode: (payload: unknown) => decode(payload, CODECS['RequestEvent']), }, { @@ -4840,8 +4881,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'release_report.updated', entity: 'ReleaseReportEvent', - intent: 'upsert', - invalidates: ['ReleaseReport', 'ReleaseReport[]'], + intent: 'patch', + invalidates: ['ReleaseReport:{id}', 'ReleaseReport[]'], decode: (payload: unknown) => decode(payload, CODECS['ReleaseReportEvent']), }, { @@ -4849,8 +4890,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'release_report.deleted', entity: 'ReleaseReportEvent', - intent: 'evict', - invalidates: ['ReleaseReport', 'ReleaseReport[]'], + intent: 'patch', + invalidates: ['ReleaseReport:{id}', 'ReleaseReport[]'], decode: (payload: unknown) => decode(payload, CODECS['ReleaseReportEvent']), }, { diff --git a/apps/dashboard/src/client/forge/loomplane/ops/agentReports.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/agentReports.list.ts index b43fc2af4..536a6d175 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/agentReports.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/agentReports.list.ts @@ -4,7 +4,9 @@ import { codec_ReportList } from '../codecs/ReportList'; export const op_agentReports_list = { method: 'GET', path: '/api/v1/agent/reports', - provides: [], + entity: 'Report', + rootType: 'ReportList', + provides: ['Report:{id}', 'Report[]'], invalidates: [], responseCodec: codec_ReportList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/agentRequests.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/agentRequests.list.ts index abefc617b..2f3d0be10 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/agentRequests.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/agentRequests.list.ts @@ -4,7 +4,9 @@ import { codec_RequestList } from '../codecs/RequestList'; export const op_agentRequests_list = { method: 'GET', path: '/api/v1/agent/requests', - provides: [], + entity: 'Request', + rootType: 'RequestList', + provides: ['Request:{id}', 'Request[]'], invalidates: [], responseCodec: codec_RequestList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/agentTasks.stream.ts b/apps/dashboard/src/client/forge/loomplane/ops/agentTasks.stream.ts deleted file mode 100644 index 74e6ed139..000000000 --- a/apps/dashboard/src/client/forge/loomplane/ops/agentTasks.stream.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { OperationMeta } from '../ops'; - -export const op_agentTasks_stream = { - method: 'GET', - path: '/api/v1/agent/tasks/{id}/stream', - provides: [], - invalidates: [], -} as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/aiModelDeployments.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/aiModelDeployments.list.ts index dd1286474..ea0c080cb 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/aiModelDeployments.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/aiModelDeployments.list.ts @@ -4,6 +4,7 @@ import { codec_ModelDeploymentList } from '../codecs/ModelDeploymentList'; export const op_aiModelDeployments_list = { method: 'GET', path: '/api/v1/ai/models/deployments', + rootType: 'ModelDeploymentList', provides: [], invalidates: [], responseCodec: codec_ModelDeploymentList, diff --git a/apps/dashboard/src/client/forge/loomplane/ops/aiSettings.get.ts b/apps/dashboard/src/client/forge/loomplane/ops/aiSettings.get.ts index 3db62af07..86a442694 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/aiSettings.get.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/aiSettings.get.ts @@ -4,7 +4,9 @@ import { codec_View } from '../codecs/View'; export const op_aiSettings_get = { method: 'GET', path: '/api/v1/ai/settings', - provides: [], + entity: 'ProviderKey', + rootType: 'View', + provides: ['ProviderKey:{id}', 'ProviderKey[]'], invalidates: [], responseCodec: codec_View, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/aiSettings.setBudget.ts b/apps/dashboard/src/client/forge/loomplane/ops/aiSettings.setBudget.ts index bffd19705..1daad4875 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/aiSettings.setBudget.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/aiSettings.setBudget.ts @@ -5,6 +5,7 @@ import { codec_WorkspaceBudgetInputBody } from '../codecs/WorkspaceBudgetInputBo export const op_aiSettings_setBudget = { method: 'PUT', path: '/api/v1/ai/settings/budget', + rootType: 'View', provides: [], invalidates: [], bodyCodec: codec_WorkspaceBudgetInputBody, diff --git a/apps/dashboard/src/client/forge/loomplane/ops/bitbucket.disconnect.ts b/apps/dashboard/src/client/forge/loomplane/ops/bitbucket.disconnect.ts index 466bd9a30..730b4df05 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/bitbucket.disconnect.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/bitbucket.disconnect.ts @@ -3,7 +3,7 @@ import type { OperationMeta } from '../ops'; export const op_bitbucket_disconnect = { method: 'DELETE', path: '/api/v1/bitbucket/workspaces/{id}', - entity: 'BitbucketWorkspace', + entity: 'BitbucketWorkspaceView', provides: [], - invalidates: ['BitbucketWorkspace[]'], + invalidates: ['BitbucketWorkspaceView[]'], } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/catalogEndpoints.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/catalogEndpoints.list.ts index 43297661c..2dd2528b9 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/catalogEndpoints.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/catalogEndpoints.list.ts @@ -4,7 +4,9 @@ import { codec_EndpointList } from '../codecs/EndpointList'; export const op_catalogEndpoints_list = { method: 'GET', path: '/api/v1/catalog/endpoints', - provides: [], + entity: 'CatalogconnectEndpoint', + rootType: 'EndpointList', + provides: ['CatalogconnectEndpoint:{id}', 'CatalogconnectEndpoint[]'], invalidates: [], responseCodec: codec_EndpointList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.preview.ts b/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.preview.ts index 67142d464..272e92fb7 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.preview.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.preview.ts @@ -8,7 +8,7 @@ export const op_cloudClusters_preview = { entity: 'CloudClusterOperation', rootType: 'CloudClusterOperation', provides: ['CloudClusterOperation:{id}'], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterOperation[]', 'CloudClusterPage', 'RuntimeAttachmentPage'], + invalidates: ['CloudClusterOperation[]', 'CloudCluster[]'], bodyCodec: codec_ClusterInputBody, responseCodec: codec_CloudClusterOperation, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.refreshCapacity.ts b/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.refreshCapacity.ts index f1bded4d3..1a74e0ddc 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.refreshCapacity.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.refreshCapacity.ts @@ -7,6 +7,6 @@ export const op_cloudClusters_refreshCapacity = { entity: 'ClusterCapacity', rootType: 'ClusterCapacity', provides: ['ClusterCapacity:{resourceId}'], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterPage', 'ClusterCapacity[]', 'RuntimeAttachmentPage'], + invalidates: ['CloudCluster:{res.resourceId}', 'CloudClusterOperation[]', 'CloudCluster[]', 'ClusterCapacity[]', 'RuntimeAttachmentPage:{res.resourceId}'], responseCodec: codec_ClusterCapacity, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.retirementPreview.ts b/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.retirementPreview.ts index 756523d29..7c3e2f606 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.retirementPreview.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/cloudClusters.retirementPreview.ts @@ -6,7 +6,7 @@ export const op_cloudClusters_retirementPreview = { method: 'POST', path: '/api/v1/clouds/{cloudId}/clusters/{clusterId}/retirement/preview', provides: [], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterPage', 'RuntimeAttachmentPage'], + invalidates: ['CloudCluster:{res.resourceId}', 'CloudClusterOperation[]', 'CloudCluster[]', 'RuntimeAttachmentPage:{res.resourceId}'], bodyCodec: codec_ClusterRetirementPreviewInputBody, responseCodec: codec_ClusterRetirementReview, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/cloudPools.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/cloudPools.list.ts index f2c9cec64..9f48eee53 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/cloudPools.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/cloudPools.list.ts @@ -4,7 +4,9 @@ import { codec_PoolList } from '../codecs/PoolList'; export const op_cloudPools_list = { method: 'GET', path: '/api/v1/clouds/{cloudId}/pools', - provides: [], + entity: 'Pool', + rootType: 'PoolList', + provides: ['Pool:{id}', 'Pool[]'], invalidates: [], responseCodec: codec_PoolList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/cloudServers.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/cloudServers.list.ts index f86cd8b77..37b81ba59 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/cloudServers.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/cloudServers.list.ts @@ -4,7 +4,9 @@ import { codec_ServerList } from '../codecs/ServerList'; export const op_cloudServers_list = { method: 'GET', path: '/api/v1/clouds/{cloudId}/servers', - provides: [], + entity: 'Server', + rootType: 'ServerList', + provides: ['Server:{id}', 'Server[]'], invalidates: [], responseCodec: codec_ServerList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/cloudSyncs.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/cloudSyncs.list.ts index 6bc1d5e35..56ee01cf6 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/cloudSyncs.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/cloudSyncs.list.ts @@ -4,7 +4,9 @@ import { codec_CloudSyncList } from '../codecs/CloudSyncList'; export const op_cloudSyncs_list = { method: 'GET', path: '/api/v1/projects/{id}/cloud-syncs', - provides: [], + entity: 'Sync', + rootType: 'CloudSyncList', + provides: ['Sync:{id}', 'Sync[]'], invalidates: [], responseCodec: codec_CloudSyncList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/cloudTargets.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/cloudTargets.list.ts index 21bdf5f3c..5471d7c64 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/cloudTargets.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/cloudTargets.list.ts @@ -4,7 +4,9 @@ import { codec_CloudTargetList } from '../codecs/CloudTargetList'; export const op_cloudTargets_list = { method: 'GET', path: '/api/v1/projects/{id}/clouds/{cloudId}/targets', - provides: [], + entity: 'CloudprofilesTarget', + rootType: 'CloudTargetList', + provides: ['CloudprofilesTarget:{id}', 'CloudprofilesTarget[]'], invalidates: [], responseCodec: codec_CloudTargetList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/clouds.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/clouds.list.ts index 70d28be35..9bf632686 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/clouds.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/clouds.list.ts @@ -4,7 +4,9 @@ import { codec_PlanningCloudList } from '../codecs/PlanningCloudList'; export const op_clouds_list = { method: 'GET', path: '/api/v1/projects/{id}/clouds', - provides: [], + entity: 'Profile', + rootType: 'PlanningCloudList', + provides: ['Profile:{id}', 'Profile[]'], invalidates: [], responseCodec: codec_PlanningCloudList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.apply.ts b/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.apply.ts index b25dc0acc..1f0d280e6 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.apply.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.apply.ts @@ -8,7 +8,7 @@ export const op_clusterOperations_apply = { entity: 'CloudClusterOperation', rootType: 'CloudClusterOperation', provides: ['CloudClusterOperation:{id}'], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterOperation[]', 'CloudClusterPage', 'RuntimeAttachmentPage'], + invalidates: ['CloudCluster:{res.resourceId}', 'CloudClusterOperation[]', 'CloudCluster[]', 'RuntimeAttachmentPage:{res.resourceId}'], bodyCodec: codec_ApplyInputBody, responseCodec: codec_CloudClusterOperation, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.cancel.ts b/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.cancel.ts index de7a4fcd2..bcbb31a48 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.cancel.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.cancel.ts @@ -7,6 +7,6 @@ export const op_clusterOperations_cancel = { entity: 'CloudClusterOperation', rootType: 'CloudClusterOperation', provides: ['CloudClusterOperation:{id}'], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterOperation[]', 'CloudClusterPage', 'RuntimeAttachmentPage'], + invalidates: ['CloudCluster:{res.resourceId}', 'CloudClusterOperation[]', 'CloudCluster[]', 'RuntimeAttachmentPage:{res.resourceId}'], responseCodec: codec_CloudClusterOperation, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.retry.ts b/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.retry.ts index 141e6dc39..6f5744997 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.retry.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/clusterOperations.retry.ts @@ -7,6 +7,6 @@ export const op_clusterOperations_retry = { entity: 'CloudClusterOperation', rootType: 'CloudClusterOperation', provides: ['CloudClusterOperation:{id}'], - invalidates: ['CloudCluster', 'CloudClusterOperation', 'CloudClusterOperationPage', 'CloudClusterOperation[]', 'CloudClusterPage', 'RuntimeAttachmentPage'], + invalidates: ['CloudCluster:{res.resourceId}', 'CloudClusterOperation[]', 'CloudCluster[]', 'RuntimeAttachmentPage:{res.resourceId}'], responseCodec: codec_CloudClusterOperation, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/defaultCloud.get.ts b/apps/dashboard/src/client/forge/loomplane/ops/defaultCloud.get.ts new file mode 100644 index 000000000..b8059c25d --- /dev/null +++ b/apps/dashboard/src/client/forge/loomplane/ops/defaultCloud.get.ts @@ -0,0 +1,12 @@ +import type { OperationMeta } from '../ops'; +import { codec_DefaultCloud } from '../codecs/DefaultCloud'; + +export const op_defaultCloud_get = { + method: 'GET', + path: '/api/v1/projects/{id}/default-cloud', + entity: 'DefaultCloud', + rootType: 'DefaultCloud', + provides: ['DefaultCloud:{projectId}'], + invalidates: [], + responseCodec: codec_DefaultCloud, +} as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/environmentClouds.preview.ts b/apps/dashboard/src/client/forge/loomplane/ops/defaultCloud.preview.ts similarity index 52% rename from apps/dashboard/src/client/forge/loomplane/ops/environmentClouds.preview.ts rename to apps/dashboard/src/client/forge/loomplane/ops/defaultCloud.preview.ts index c23933235..405ad1475 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/environmentClouds.preview.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/defaultCloud.preview.ts @@ -1,14 +1,14 @@ import type { OperationMeta } from '../ops'; -import { codec_EnvironmentCloudInputBody } from '../codecs/EnvironmentCloudInputBody'; +import { codec_DefaultCloudInputBody } from '../codecs/DefaultCloudInputBody'; import { codec_Preview } from '../codecs/Preview'; -export const op_environmentClouds_preview = { +export const op_defaultCloud_preview = { method: 'POST', - path: '/api/v1/projects/{id}/environments/{environmentId}/cloud/preview', + path: '/api/v1/projects/{id}/default-cloud/preview', entity: 'Preview', rootType: 'Preview', provides: ['Preview:{id}'], invalidates: ['Preview[]'], - bodyCodec: codec_EnvironmentCloudInputBody, + bodyCodec: codec_DefaultCloudInputBody, responseCodec: codec_Preview, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/dnsZones.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/dnsZones.list.ts index 847e6350f..14e688d8f 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/dnsZones.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/dnsZones.list.ts @@ -4,7 +4,9 @@ import { codec_ZoneList } from '../codecs/ZoneList'; export const op_dnsZones_list = { method: 'GET', path: '/api/v1/dns-zones', - provides: [], + entity: 'Zone', + rootType: 'ZoneList', + provides: ['Zone:{id}', 'Zone[]'], invalidates: [], responseCodec: codec_ZoneList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/domainRegistrations.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/domainRegistrations.list.ts index d251cfd10..541be6b04 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/domainRegistrations.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/domainRegistrations.list.ts @@ -4,7 +4,9 @@ import { codec_RegistrationList } from '../codecs/RegistrationList'; export const op_domainRegistrations_list = { method: 'GET', path: '/api/v1/domain-registrations', - provides: [], + entity: 'Registration', + rootType: 'RegistrationList', + provides: ['Registration:{id}', 'Registration[]'], invalidates: [], responseCodec: codec_RegistrationList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/domainRoutes.history.ts b/apps/dashboard/src/client/forge/loomplane/ops/domainRoutes.history.ts index bfc7f71e2..24efbda50 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/domainRoutes.history.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/domainRoutes.history.ts @@ -4,7 +4,9 @@ import { codec_DomainOperationList } from '../codecs/DomainOperationList'; export const op_domainRoutes_history = { method: 'GET', path: '/api/v1/projects/{projectId}/domain-routes/{routeId}/operations', - provides: [], + entity: 'RouteOperation', + rootType: 'DomainOperationList', + provides: ['RouteOperation:{id}', 'RouteOperation[]'], invalidates: [], responseCodec: codec_DomainOperationList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/domainRoutes.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/domainRoutes.list.ts index b68f9345c..6ec3285ec 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/domainRoutes.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/domainRoutes.list.ts @@ -4,7 +4,9 @@ import { codec_DomainRouteList } from '../codecs/DomainRouteList'; export const op_domainRoutes_list = { method: 'GET', path: '/api/v1/projects/{projectId}/domain-routes', - provides: [], + entity: 'CloudinfraRoute', + rootType: 'DomainRouteList', + provides: ['CloudinfraRoute:{id}', 'CloudinfraRoute[]'], invalidates: [], responseCodec: codec_DomainRouteList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/domains.overview.ts b/apps/dashboard/src/client/forge/loomplane/ops/domains.overview.ts index 4009eac32..f9ffd3838 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/domains.overview.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/domains.overview.ts @@ -4,8 +4,9 @@ import { codec_DomainOverview } from '../codecs/DomainOverview'; export const op_domains_overview = { method: 'GET', path: '/api/v1/domains', + entity: 'Registration', rootType: 'DomainOverview', - provides: [], + provides: ['Registration:{id}', 'Registration[]'], invalidates: [], responseCodec: codec_DomainOverview, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/environmentClouds.get.ts b/apps/dashboard/src/client/forge/loomplane/ops/environmentClouds.get.ts deleted file mode 100644 index 7ca3812a8..000000000 --- a/apps/dashboard/src/client/forge/loomplane/ops/environmentClouds.get.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { OperationMeta } from '../ops'; -import { codec_EnvironmentCloud } from '../codecs/EnvironmentCloud'; - -export const op_environmentClouds_get = { - method: 'GET', - path: '/api/v1/projects/{id}/environments/{environmentId}/cloud', - provides: [], - invalidates: [], - responseCodec: codec_EnvironmentCloud, -} as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/infrastructureOperations.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/infrastructureOperations.list.ts index f1e2734a9..929a04b37 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/infrastructureOperations.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/infrastructureOperations.list.ts @@ -4,7 +4,9 @@ import { codec_OperationList } from '../codecs/OperationList'; export const op_infrastructureOperations_list = { method: 'GET', path: '/api/v1/clouds/{cloudId}/infrastructure-operations', - provides: [], + entity: 'Operation', + rootType: 'OperationList', + provides: ['Operation:{id}', 'Operation[]'], invalidates: [], responseCodec: codec_OperationList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/organizationCloudSyncs.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/organizationCloudSyncs.list.ts index f081a136d..47f6a2dcf 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/organizationCloudSyncs.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/organizationCloudSyncs.list.ts @@ -4,7 +4,9 @@ import { codec_CloudSyncList } from '../codecs/CloudSyncList'; export const op_organizationCloudSyncs_list = { method: 'GET', path: '/api/v1/clouds/syncs', - provides: [], + entity: 'Sync', + rootType: 'CloudSyncList', + provides: ['Sync:{id}', 'Sync[]'], invalidates: [], responseCodec: codec_CloudSyncList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/organizationCloudTargets.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/organizationCloudTargets.list.ts index 20a49a1f6..a0c217eac 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/organizationCloudTargets.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/organizationCloudTargets.list.ts @@ -4,7 +4,9 @@ import { codec_CloudTargetList } from '../codecs/CloudTargetList'; export const op_organizationCloudTargets_list = { method: 'GET', path: '/api/v1/clouds/{cloudId}/targets', - provides: [], + entity: 'CloudprofilesTarget', + rootType: 'CloudTargetList', + provides: ['CloudprofilesTarget:{id}', 'CloudprofilesTarget[]'], invalidates: [], responseCodec: codec_CloudTargetList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/organizationClouds.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/organizationClouds.list.ts index bd59cfdb3..f1d854e1f 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/organizationClouds.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/organizationClouds.list.ts @@ -4,7 +4,9 @@ import { codec_PlanningCloudList } from '../codecs/PlanningCloudList'; export const op_organizationClouds_list = { method: 'GET', path: '/api/v1/clouds', - provides: [], + entity: 'Profile', + rootType: 'PlanningCloudList', + provides: ['Profile:{id}', 'Profile[]'], invalidates: [], responseCodec: codec_PlanningCloudList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/providerResources.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/providerResources.list.ts index a242b2fbb..d463a5c5b 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/providerResources.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/providerResources.list.ts @@ -4,6 +4,7 @@ import { codec_ProviderResourceList } from '../codecs/ProviderResourceList'; export const op_providerResources_list = { method: 'GET', path: '/api/v1/provider-resources', + rootType: 'ProviderResourceList', provides: [], invalidates: [], responseCodec: codec_ProviderResourceList, diff --git a/apps/dashboard/src/client/forge/loomplane/ops/realtime.events.ts b/apps/dashboard/src/client/forge/loomplane/ops/realtime.events.ts deleted file mode 100644 index 1ae953baf..000000000 --- a/apps/dashboard/src/client/forge/loomplane/ops/realtime.events.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { OperationMeta } from '../ops'; - -export const op_realtime_events = { - method: 'GET', - path: '/api/v1/realtime/events', - provides: [], - invalidates: [], -} as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/realtime.ws.ts b/apps/dashboard/src/client/forge/loomplane/ops/realtime.ws.ts deleted file mode 100644 index 5c72db6fb..000000000 --- a/apps/dashboard/src/client/forge/loomplane/ops/realtime.ws.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { OperationMeta } from '../ops'; - -export const op_realtime_ws = { - method: 'GET', - path: '/api/v1/realtime/ws', - provides: [], - invalidates: [], -} as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/releaseReports.list.ts b/apps/dashboard/src/client/forge/loomplane/ops/releaseReports.list.ts index deb33cba6..a61274ea3 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/releaseReports.list.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/releaseReports.list.ts @@ -4,7 +4,9 @@ import { codec_ReleaseReportList } from '../codecs/ReleaseReportList'; export const op_releaseReports_list = { method: 'GET', path: '/api/v1/projects/{id}/release-reports', - provides: [], + entity: 'ReleaseReport', + rootType: 'ReleaseReportList', + provides: ['ReleaseReport:{id}', 'ReleaseReport[]'], invalidates: [], responseCodec: codec_ReleaseReportList, } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/ops/sources.delete.ts b/apps/dashboard/src/client/forge/loomplane/ops/sources.delete.ts index 2cc560b29..cb99729ac 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/sources.delete.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/sources.delete.ts @@ -3,7 +3,7 @@ import type { OperationMeta } from '../ops'; export const op_sources_delete = { method: 'DELETE', path: '/api/v1/projects/{id}/sources/{alias}', - entity: 'Source', + entity: 'DiscoverySource', provides: [], - invalidates: ['Source[]'], + invalidates: ['DiscoverySource[]'], } as const satisfies OperationMeta; diff --git a/apps/dashboard/src/client/forge/loomplane/rest.ts b/apps/dashboard/src/client/forge/loomplane/rest.ts index bf6eb835f..b3cc77f9f 100644 --- a/apps/dashboard/src/client/forge/loomplane/rest.ts +++ b/apps/dashboard/src/client/forge/loomplane/rest.ts @@ -34,7 +34,7 @@ export class RESTClient extends Client { let __path = `/api/v1/activity`; const queryParams: Record = {}; if (days !== undefined) { - queryParams['days'] = days; + queryParams["days"] = days; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -98,10 +98,10 @@ export class RESTClient extends Client { let __path = `/api/v1/agent/conversations/${encodeURIComponent(String(id))}`; const queryParams: Record = {}; if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -126,16 +126,16 @@ export class RESTClient extends Client { let __path = `/api/v1/agent/conversations`; const queryParams: Record = {}; if (projectId !== undefined) { - queryParams['project_id'] = projectId; + queryParams["project_id"] = projectId; } if (everyone !== undefined) { - queryParams['everyone'] = everyone; + queryParams["everyone"] = everyone; } if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -255,13 +255,13 @@ export class RESTClient extends Client { let __path = `/api/v1/agent/reports`; const queryParams: Record = {}; if (status !== undefined) { - queryParams['status'] = status; + queryParams["status"] = status; } if (projectId !== undefined) { - queryParams['project_id'] = projectId; + queryParams["project_id"] = projectId; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -359,16 +359,16 @@ export class RESTClient extends Client { let __path = `/api/v1/agent/requests`; const queryParams: Record = {}; if (status !== undefined) { - queryParams['status'] = status; + queryParams["status"] = status; } if (projectId !== undefined) { - queryParams['project_id'] = projectId; + queryParams["project_id"] = projectId; } if (forParam !== undefined) { - queryParams['for'] = forParam; + queryParams["for"] = forParam; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -459,31 +459,6 @@ export class RESTClient extends Client { return this.request(config); }, - /** - * Follow a task's events as they happen - * Each agent.event carries one event, with its seq as the SSE id. Reconnect with Last-Event-ID (or after) set to the last seq you have, and the stream picks up at the next one. agent.end is the last frame: the task's final status. - */ - stream: async (id: string, after?: number | undefined, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { - let __path = `/api/v1/agent/tasks/${encodeURIComponent(String(id))}/stream`; - const queryParams: Record = {}; - if (after !== undefined) { - queryParams['after'] = after; - } - const queryString = new URLSearchParams(queryParams).toString(); - if (queryString) { - __path += '?' + queryString; - } - const config: RequestConfig = { - method: 'GET', - url: __path, - signal: options?.signal, - retry: options?.retry, - allowEmptyBody: true, - }; - - await this.request(config); - }, - }; public readonly agentWatcher = { @@ -667,7 +642,7 @@ export class RESTClient extends Client { card: async (id?: string, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/api/v1/ai/models/registry/card`; const queryParams: Record = {}; - queryParams['id'] = id; + queryParams["id"] = id; const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { __path += '?' + queryString; @@ -708,7 +683,7 @@ export class RESTClient extends Client { entry: async (id?: string, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/api/v1/ai/models/registry/entry`; const queryParams: Record = {}; - queryParams['id'] = id; + queryParams["id"] = id; const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { __path += '?' + queryString; @@ -767,13 +742,13 @@ export class RESTClient extends Client { registry: async (q?: string, task?: string, size?: string, license?: string, commercial?: boolean, fits?: boolean, tested?: boolean, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/api/v1/ai/models/registry`; const queryParams: Record = {}; - queryParams['q'] = q; - queryParams['task'] = task; - queryParams['size'] = size; - queryParams['license'] = license; - queryParams['commercial'] = commercial; - queryParams['fits'] = fits; - queryParams['tested'] = tested; + queryParams["q"] = q; + queryParams["task"] = task; + queryParams["size"] = size; + queryParams["license"] = license; + queryParams["commercial"] = commercial; + queryParams["fits"] = fits; + queryParams["tested"] = tested; const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { __path += '?' + queryString; @@ -1061,7 +1036,7 @@ export class RESTClient extends Client { let __path = `/api/v1/api-keys/${encodeURIComponent(String(id))}`; const queryParams: Record = {}; if (compromised !== undefined) { - queryParams['compromised'] = compromised; + queryParams["compromised"] = compromised; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -1123,7 +1098,7 @@ export class RESTClient extends Client { list: async (id: string, environment?: string, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/bindings`; const queryParams: Record = {}; - queryParams['environment'] = environment; + queryParams["environment"] = environment; const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { __path += '?' + queryString; @@ -1603,13 +1578,13 @@ export class RESTClient extends Client { let __path = `/api/v1/clouds/${encodeURIComponent(String(cloudId))}/clusters/${encodeURIComponent(String(clusterId))}/attachments`; const queryParams: Record = {}; if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (region !== undefined) { - queryParams['region'] = region; + queryParams["region"] = region; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -1633,13 +1608,13 @@ export class RESTClient extends Client { let __path = `/api/v1/clouds/${encodeURIComponent(String(cloudId))}/clusters/${encodeURIComponent(String(clusterId))}/capacity`; const queryParams: Record = {}; if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (region !== undefined) { - queryParams['region'] = region; + queryParams["region"] = region; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -1663,13 +1638,13 @@ export class RESTClient extends Client { let __path = `/api/v1/clouds/${encodeURIComponent(String(cloudId))}/clusters/${encodeURIComponent(String(clusterId))}`; const queryParams: Record = {}; if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (region !== undefined) { - queryParams['region'] = region; + queryParams["region"] = region; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -1693,13 +1668,13 @@ export class RESTClient extends Client { let __path = `/api/v1/clouds/${encodeURIComponent(String(cloudId))}/clusters`; const queryParams: Record = {}; if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (region !== undefined) { - queryParams['region'] = region; + queryParams["region"] = region; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -1723,13 +1698,13 @@ export class RESTClient extends Client { let __path = `/api/v1/clouds/${encodeURIComponent(String(cloudId))}/cluster-options/${encodeURIComponent(String(connectionId))}`; const queryParams: Record = {}; if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (region !== undefined) { - queryParams['region'] = region; + queryParams["region"] = region; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -2252,13 +2227,13 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/cloud-syncs`; const queryParams: Record = {}; if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (cloud !== undefined) { - queryParams['cloud'] = cloud; + queryParams["cloud"] = cloud; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -2559,13 +2534,13 @@ export class RESTClient extends Client { let __path = `/api/v1/clouds/${encodeURIComponent(String(cloudId))}/cluster-operations/${encodeURIComponent(String(operationId))}`; const queryParams: Record = {}; if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (region !== undefined) { - queryParams['region'] = region; + queryParams["region"] = region; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -2589,13 +2564,13 @@ export class RESTClient extends Client { let __path = `/api/v1/clouds/${encodeURIComponent(String(cloudId))}/cluster-operations`; const queryParams: Record = {}; if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (region !== undefined) { - queryParams['region'] = region; + queryParams["region"] = region; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -2656,13 +2631,13 @@ export class RESTClient extends Client { let __path = `/api/v1/connections/${encodeURIComponent(String(connectionId))}/clusters`; const queryParams: Record = {}; if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (region !== undefined) { - queryParams['region'] = region; + queryParams["region"] = region; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -3040,6 +3015,43 @@ export class RESTClient extends Client { }; + public readonly defaultCloud = { + /** + * defaultCloud.get + */ + get: async (id: string, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { + let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/default-cloud`; + const config: RequestConfig = { + method: 'GET', + url: __path, + signal: options?.signal, + retry: options?.retry, + responseCodec: CODECS["DefaultCloud"], + }; + + return this.request(config); + }, + + /** + * defaultCloud.preview + */ + preview: async (id: string, body: types.DefaultCloudInputBody, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { + let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/default-cloud/preview`; + const config: RequestConfig = { + method: 'POST', + url: __path, + body, + bodyCodec: CODECS["DefaultCloudInputBody"], + signal: options?.signal, + retry: options?.retry, + responseCodec: CODECS["Preview"], + }; + + return this.request(config); + }, + + }; + public readonly deployed = { /** * The commit of each of the project's repositories deployed in the environment; one with nothing deployed there isn't listed, and a plan can't hold it @@ -3228,10 +3240,10 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/deployments`; const queryParams: Record = {}; if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -3254,10 +3266,10 @@ export class RESTClient extends Client { let __path = `/api/v1/deployments/${encodeURIComponent(String(id))}/logs`; const queryParams: Record = {}; if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -3335,7 +3347,7 @@ export class RESTClient extends Client { discover: async (connectionId?: string, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/api/v1/dns-zones/discover`; const queryParams: Record = {}; - queryParams['connection_id'] = connectionId; + queryParams["connection_id"] = connectionId; const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { __path += '?' + queryString; @@ -3569,7 +3581,7 @@ export class RESTClient extends Client { extensions: async (connectionId?: string, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/api/v1/domain-registration/extensions`; const queryParams: Record = {}; - queryParams['connection_id'] = connectionId; + queryParams["connection_id"] = connectionId; const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { __path += '?' + queryString; @@ -3591,8 +3603,8 @@ export class RESTClient extends Client { search: async (connectionId?: string, q?: string, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/api/v1/domain-registration/search`; const queryParams: Record = {}; - queryParams['connection_id'] = connectionId; - queryParams['q'] = q; + queryParams["connection_id"] = connectionId; + queryParams["q"] = q; const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { __path += '?' + queryString; @@ -3973,43 +3985,6 @@ export class RESTClient extends Client { }; - public readonly environmentClouds = { - /** - * environmentClouds.get - */ - get: async (id: string, environmentId: string, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { - let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/environments/${encodeURIComponent(String(environmentId))}/cloud`; - const config: RequestConfig = { - method: 'GET', - url: __path, - signal: options?.signal, - retry: options?.retry, - responseCodec: CODECS["EnvironmentCloud"], - }; - - return this.request(config); - }, - - /** - * environmentClouds.preview - */ - preview: async (id: string, environmentId: string, body: types.EnvironmentCloudInputBody, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { - let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/environments/${encodeURIComponent(String(environmentId))}/cloud/preview`; - const config: RequestConfig = { - method: 'POST', - url: __path, - body, - bodyCodec: CODECS["EnvironmentCloudInputBody"], - signal: options?.signal, - retry: options?.retry, - responseCodec: CODECS["Preview"], - }; - - return this.request(config); - }, - - }; - public readonly environmentConnections = { /** * Choose the connection the environment deploys to a cloud with, or clear the choice @@ -4073,7 +4048,7 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/environments/${encodeURIComponent(String(envId))}`; const queryParams: Record = {}; if (keep !== undefined) { - queryParams['keep'] = keep; + queryParams["keep"] = keep; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -4260,10 +4235,10 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(projectId))}/fleet/instances/${encodeURIComponent(String(id))}/events`; const queryParams: Record = {}; if (after !== undefined) { - queryParams['after'] = after; + queryParams["after"] = after; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -4340,16 +4315,16 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(projectId))}/fleet/instances`; const queryParams: Record = {}; if (after !== undefined) { - queryParams['after'] = after; + queryParams["after"] = after; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (status !== undefined) { - queryParams['status'] = status; + queryParams["status"] = status; } if (externalRef !== undefined) { - queryParams['external_ref'] = externalRef; + queryParams["external_ref"] = externalRef; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -4395,10 +4370,10 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(projectId))}/fleet/instances/${encodeURIComponent(String(id))}/metrics`; const queryParams: Record = {}; if (start !== undefined) { - queryParams['start'] = start; + queryParams["start"] = start; } if (end !== undefined) { - queryParams['end'] = end; + queryParams["end"] = end; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -4709,13 +4684,13 @@ export class RESTClient extends Client { let __path = `/api/v1/gpu-targets`; const queryParams: Record = {}; if (minMemoryGib !== undefined) { - queryParams['min_memory_gib'] = minMemoryGib; + queryParams["min_memory_gib"] = minMemoryGib; } if (count !== undefined) { - queryParams['count'] = count; + queryParams["count"] = count; } if (kind !== undefined) { - queryParams['kind'] = kind; + queryParams["kind"] = kind; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -5087,16 +5062,16 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/native-recovery-copies`; const queryParams: Record = {}; if (environmentId !== undefined) { - queryParams['environment_id'] = environmentId; + queryParams["environment_id"] = environmentId; } if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (resource !== undefined) { - queryParams['resource'] = resource; + queryParams["resource"] = resource; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -5171,10 +5146,10 @@ export class RESTClient extends Client { let __path = `/api/v1/native-recovery-retirements/${encodeURIComponent(String(id))}/history`; const queryParams: Record = {}; if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -5197,16 +5172,16 @@ export class RESTClient extends Client { let __path = `/api/v1/native-recovery-sources/${encodeURIComponent(String(id))}/retirements`; const queryParams: Record = {}; if (environmentId !== undefined) { - queryParams['environment_id'] = environmentId; + queryParams["environment_id"] = environmentId; } if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (resource !== undefined) { - queryParams['resource'] = resource; + queryParams["resource"] = resource; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -5247,16 +5222,16 @@ export class RESTClient extends Client { let __path = `/api/v1/native-recovery-sources/${encodeURIComponent(String(id))}`; const queryParams: Record = {}; if (environmentId !== undefined) { - queryParams['environment_id'] = environmentId; + queryParams["environment_id"] = environmentId; } if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (resource !== undefined) { - queryParams['resource'] = resource; + queryParams["resource"] = resource; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -5279,16 +5254,16 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/native-recovery-sources`; const queryParams: Record = {}; if (environmentId !== undefined) { - queryParams['environment_id'] = environmentId; + queryParams["environment_id"] = environmentId; } if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (resource !== undefined) { - queryParams['resource'] = resource; + queryParams["resource"] = resource; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -5325,8 +5300,8 @@ export class RESTClient extends Client { previewRetention: async (id: string, olderThanDays?: number, keepLast?: number, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/api/v1/native-recovery-sources/${encodeURIComponent(String(id))}/retention-preview`; const queryParams: Record = {}; - queryParams['older_than_days'] = olderThanDays; - queryParams['keep_last'] = keepLast; + queryParams["older_than_days"] = olderThanDays; + queryParams["keep_last"] = keepLast; const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { __path += '?' + queryString; @@ -5381,10 +5356,10 @@ export class RESTClient extends Client { let __path = `/api/v1/native-recovery-sources/${encodeURIComponent(String(id))}/retention-policy/history`; const queryParams: Record = {}; if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -6037,13 +6012,13 @@ export class RESTClient extends Client { let __path = `/api/v1/clouds/syncs`; const queryParams: Record = {}; if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } if (cloud !== undefined) { - queryParams['cloud'] = cloud; + queryParams["cloud"] = cloud; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -6487,13 +6462,13 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/plans`; const queryParams: Record = {}; if (environment !== undefined) { - queryParams['environment'] = environment; + queryParams["environment"] = environment; } if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -6572,7 +6547,7 @@ export class RESTClient extends Client { let __path = `/api/v1/platform/agent/flags`; const queryParams: Record = {}; if (status !== undefined) { - queryParams['status'] = status; + queryParams["status"] = status; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -7459,54 +7434,22 @@ export class RESTClient extends Client { }; public readonly realtime = { - /** - */ - events: async (orgId?: string | undefined, projectIds?: string | undefined, deploymentIds?: string | undefined, cursor?: string | undefined, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { - let __path = `/api/v1/realtime/events`; - const queryParams: Record = {}; - if (orgId !== undefined) { - queryParams['org_id'] = orgId; - } - if (projectIds !== undefined) { - queryParams['project_ids'] = projectIds; - } - if (deploymentIds !== undefined) { - queryParams['deployment_ids'] = deploymentIds; - } - if (cursor !== undefined) { - queryParams['cursor'] = cursor; - } - const queryString = new URLSearchParams(queryParams).toString(); - if (queryString) { - __path += '?' + queryString; - } - const config: RequestConfig = { - method: 'GET', - url: __path, - signal: options?.signal, - retry: options?.retry, - allowEmptyBody: true, - }; - - await this.request(config); - }, - /** */ snapshot: async (orgId?: string | undefined, projectIds?: string | undefined, deploymentIds?: string | undefined, cursor?: string | undefined, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/api/v1/realtime/snapshot`; const queryParams: Record = {}; if (orgId !== undefined) { - queryParams['org_id'] = orgId; + queryParams["org_id"] = orgId; } if (projectIds !== undefined) { - queryParams['project_ids'] = projectIds; + queryParams["project_ids"] = projectIds; } if (deploymentIds !== undefined) { - queryParams['deployment_ids'] = deploymentIds; + queryParams["deployment_ids"] = deploymentIds; } if (cursor !== undefined) { - queryParams['cursor'] = cursor; + queryParams["cursor"] = cursor; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -7523,38 +7466,6 @@ export class RESTClient extends Client { return this.request(config); }, - /** - */ - ws: async (orgId?: string | undefined, projectIds?: string | undefined, deploymentIds?: string | undefined, cursor?: string | undefined, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { - let __path = `/api/v1/realtime/ws`; - const queryParams: Record = {}; - if (orgId !== undefined) { - queryParams['org_id'] = orgId; - } - if (projectIds !== undefined) { - queryParams['project_ids'] = projectIds; - } - if (deploymentIds !== undefined) { - queryParams['deployment_ids'] = deploymentIds; - } - if (cursor !== undefined) { - queryParams['cursor'] = cursor; - } - const queryString = new URLSearchParams(queryParams).toString(); - if (queryString) { - __path += '?' + queryString; - } - const config: RequestConfig = { - method: 'GET', - url: __path, - signal: options?.signal, - retry: options?.retry, - allowEmptyBody: true, - }; - - await this.request(config); - }, - }; public readonly registries = { @@ -7637,7 +7548,7 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/release-reports`; const queryParams: Record = {}; if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -7748,10 +7659,10 @@ export class RESTClient extends Client { let __path = `/api/v1/service-backups/${encodeURIComponent(String(id))}/retention-policy/history`; const queryParams: Record = {}; if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -7813,7 +7724,7 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/environments/${encodeURIComponent(String(environment))}/rollback-target`; const queryParams: Record = {}; if (deploymentId !== undefined) { - queryParams['deployment_id'] = deploymentId; + queryParams["deployment_id"] = deploymentId; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -7885,8 +7796,8 @@ export class RESTClient extends Client { previewRetention: async (id: string, olderThanDays?: number, keepLast?: number, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/api/v1/service-backups/${encodeURIComponent(String(id))}/retention-preview`; const queryParams: Record = {}; - queryParams['older_than_days'] = olderThanDays; - queryParams['keep_last'] = keepLast; + queryParams["older_than_days"] = olderThanDays; + queryParams["keep_last"] = keepLast; const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { __path += '?' + queryString; @@ -8023,10 +7934,10 @@ export class RESTClient extends Client { let __path = `/api/v1/service-backup-retirements/${encodeURIComponent(String(id))}/history`; const queryParams: Record = {}; if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -8049,13 +7960,13 @@ export class RESTClient extends Client { let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/service-backup-retirements`; const queryParams: Record = {}; if (backupId !== undefined) { - queryParams['backup_id'] = backupId; + queryParams["backup_id"] = backupId; } if (before !== undefined) { - queryParams['before'] = before; + queryParams["before"] = before; } if (limit !== undefined) { - queryParams['limit'] = limit; + queryParams["limit"] = limit; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -8411,7 +8322,7 @@ export class RESTClient extends Client { let __path = `/api/v1/usage/traffic`; const queryParams: Record = {}; if (range !== undefined) { - queryParams['range'] = range; + queryParams["range"] = range; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { @@ -8487,9 +8398,9 @@ export class RESTClient extends Client { resolve: async (id: string, environment?: string, service?: string | undefined, options?: { signal?: AbortSignal; retry?: { maxAttempts?: number } }): Promise => { let __path = `/api/v1/projects/${encodeURIComponent(String(id))}/variables/resolved`; const queryParams: Record = {}; - queryParams['environment'] = environment; + queryParams["environment"] = environment; if (service !== undefined) { - queryParams['service'] = service; + queryParams["service"] = service; } const queryString = new URLSearchParams(queryParams).toString(); if (queryString) { diff --git a/apps/dashboard/src/client/forge/loomplane/sse.ts b/apps/dashboard/src/client/forge/loomplane/sse.ts index 47560596e..6e3d98025 100644 --- a/apps/dashboard/src/client/forge/loomplane/sse.ts +++ b/apps/dashboard/src/client/forge/loomplane/sse.ts @@ -117,7 +117,7 @@ export class AgentTasksStreamSSEClient extends EventEmitter { return new Promise((resolve, reject) => { this.setState(ConnectionState.CONNECTING); - let url = this.config.baseURL + '/api/v1/agent/tasks/:id/stream'; + let url = this.config.baseURL + "/api/v1/agent/tasks/:id/stream"; // In browser, add auth as query params since EventSource doesn't support custom headers if (isBrowser) { @@ -182,37 +182,37 @@ export class AgentTasksStreamSSEClient extends EventEmitter { reject(error); }; - this.eventSource.addEventListener('agent.end', (event: MessageEvent) => { + this.eventSource.addEventListener("agent.end", (event: MessageEvent) => { try { const data: types.RealtimeAgentEnd = decode(JSON.parse(event.data), "RealtimeAgentEnd"); - this.emit('agent.end', data); + this.emit("agent.end", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('agent.event', (event: MessageEvent) => { + this.eventSource.addEventListener("agent.event", (event: MessageEvent) => { try { const data: types.RealtimeAgentEvent = decode(JSON.parse(event.data), "RealtimeAgentEvent"); - this.emit('agent.event', data); + this.emit("agent.event", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('forge.resumed', (event: MessageEvent) => { + this.eventSource.addEventListener("forge.resumed", (event: MessageEvent) => { try { const data: unknown = JSON.parse(event.data); - this.emit('forge.resumed', data); + this.emit("forge.resumed", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('forge.gap', (event: MessageEvent) => { + this.eventSource.addEventListener("forge.gap", (event: MessageEvent) => { try { const data: unknown = JSON.parse(event.data); - this.emit('forge.gap', data); + this.emit("forge.gap", data); } catch (error) { this.emit('error', error); } @@ -235,7 +235,7 @@ export class AgentTasksStreamSSEClient extends EventEmitter { * @param handler - Function to call when agent.end event is received */ onAgentEnd(handler: (data: types.RealtimeAgentEnd) => void): void { - this.on('agent.end', handler); + this.on("agent.end", handler); } /** @@ -243,7 +243,7 @@ export class AgentTasksStreamSSEClient extends EventEmitter { * @param handler - The handler to remove */ offAgentEnd(handler: (data: types.RealtimeAgentEnd) => void): void { - this.off('agent.end', handler); + this.off("agent.end", handler); } /** @@ -251,7 +251,7 @@ export class AgentTasksStreamSSEClient extends EventEmitter { * @param handler - Function to call when agent.event event is received */ onAgentEvent(handler: (data: types.RealtimeAgentEvent) => void): void { - this.on('agent.event', handler); + this.on("agent.event", handler); } /** @@ -259,7 +259,7 @@ export class AgentTasksStreamSSEClient extends EventEmitter { * @param handler - The handler to remove */ offAgentEvent(handler: (data: types.RealtimeAgentEvent) => void): void { - this.off('agent.event', handler); + this.off("agent.event", handler); } /** @@ -347,7 +347,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { return new Promise((resolve, reject) => { this.setState(ConnectionState.CONNECTING); - let url = this.config.baseURL + '/api/v1/realtime/events'; + let url = this.config.baseURL + "/api/v1/realtime/events"; // In browser, add auth as query params since EventSource doesn't support custom headers if (isBrowser) { @@ -412,415 +412,415 @@ export class RealtimeEventsSSEClient extends EventEmitter { reject(error); }; - this.eventSource.addEventListener('agent_report.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("agent_report.deleted", (event: MessageEvent) => { try { const data: types.Report = decode(JSON.parse(event.data), "Report"); - this.emit('agent_report.deleted', data); + this.emit("agent_report.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('agent_report.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("agent_report.updated", (event: MessageEvent) => { try { const data: types.Report = decode(JSON.parse(event.data), "Report"); - this.emit('agent_report.updated', data); + this.emit("agent_report.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('agent_request.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("agent_request.deleted", (event: MessageEvent) => { try { const data: types.RequestEvent = decode(JSON.parse(event.data), "RequestEvent"); - this.emit('agent_request.deleted', data); + this.emit("agent_request.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('agent_request.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("agent_request.updated", (event: MessageEvent) => { try { const data: types.RequestEvent = decode(JSON.parse(event.data), "RequestEvent"); - this.emit('agent_request.updated', data); + this.emit("agent_request.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('agent_task.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("agent_task.deleted", (event: MessageEvent) => { try { const data: types.TaskEvent = decode(JSON.parse(event.data), "TaskEvent"); - this.emit('agent_task.deleted', data); + this.emit("agent_task.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('agent_task.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("agent_task.updated", (event: MessageEvent) => { try { const data: types.TaskEvent = decode(JSON.parse(event.data), "TaskEvent"); - this.emit('agent_task.updated', data); + this.emit("agent_task.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('analysis.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("analysis.deleted", (event: MessageEvent) => { try { const data: types.Analysis = decode(JSON.parse(event.data), "Analysis"); - this.emit('analysis.deleted', data); + this.emit("analysis.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('analysis.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("analysis.updated", (event: MessageEvent) => { try { const data: types.Analysis = decode(JSON.parse(event.data), "Analysis"); - this.emit('analysis.updated', data); + this.emit("analysis.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('binding.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("binding.deleted", (event: MessageEvent) => { try { const data: types.Binding = decode(JSON.parse(event.data), "Binding"); - this.emit('binding.deleted', data); + this.emit("binding.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('binding.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("binding.updated", (event: MessageEvent) => { try { const data: types.Binding = decode(JSON.parse(event.data), "Binding"); - this.emit('binding.updated', data); + this.emit("binding.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('build.collection', (event: MessageEvent) => { + this.eventSource.addEventListener("build.collection", (event: MessageEvent) => { try { const data: types.Collection = decode(JSON.parse(event.data), "Collection"); - this.emit('build.collection', data); + this.emit("build.collection", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('build.log', (event: MessageEvent) => { + this.eventSource.addEventListener("build.log", (event: MessageEvent) => { try { const data: types.Log = decode(JSON.parse(event.data), "Log"); - this.emit('build.log', data); + this.emit("build.log", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('canary_verdict.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("canary_verdict.deleted", (event: MessageEvent) => { try { const data: types.CanaryVerdict = decode(JSON.parse(event.data), "CanaryVerdict"); - this.emit('canary_verdict.deleted', data); + this.emit("canary_verdict.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('canary_verdict.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("canary_verdict.updated", (event: MessageEvent) => { try { const data: types.CanaryVerdict = decode(JSON.parse(event.data), "CanaryVerdict"); - this.emit('canary_verdict.updated', data); + this.emit("canary_verdict.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('cloud.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("cloud.deleted", (event: MessageEvent) => { try { const data: types.Profile = decode(JSON.parse(event.data), "Profile"); - this.emit('cloud.deleted', data); + this.emit("cloud.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('cloud.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("cloud.updated", (event: MessageEvent) => { try { const data: types.Profile = decode(JSON.parse(event.data), "Profile"); - this.emit('cloud.updated', data); + this.emit("cloud.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('cloud_capacity.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("cloud_capacity.updated", (event: MessageEvent) => { try { const data: types.CapacityChange = decode(JSON.parse(event.data), "CapacityChange"); - this.emit('cloud_capacity.updated', data); + this.emit("cloud_capacity.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('cloud_cluster.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("cloud_cluster.updated", (event: MessageEvent) => { try { const data: types.ClusterChange = decode(JSON.parse(event.data), "ClusterChange"); - this.emit('cloud_cluster.updated', data); + this.emit("cloud_cluster.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('cloud_sync.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("cloud_sync.updated", (event: MessageEvent) => { try { const data: types.CloudSyncEvent = decode(JSON.parse(event.data), "CloudSyncEvent"); - this.emit('cloud_sync.updated', data); + this.emit("cloud_sync.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('cloud_target.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("cloud_target.deleted", (event: MessageEvent) => { try { const data: types.Target = decode(JSON.parse(event.data), "Target"); - this.emit('cloud_target.deleted', data); + this.emit("cloud_target.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('cloud_target.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("cloud_target.updated", (event: MessageEvent) => { try { const data: types.Target = decode(JSON.parse(event.data), "Target"); - this.emit('cloud_target.updated', data); + this.emit("cloud_target.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('connection.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("connection.deleted", (event: MessageEvent) => { try { const data: types.Connection = decode(JSON.parse(event.data), "Connection"); - this.emit('connection.deleted', data); + this.emit("connection.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('connection.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("connection.updated", (event: MessageEvent) => { try { const data: types.Connection = decode(JSON.parse(event.data), "Connection"); - this.emit('connection.updated', data); + this.emit("connection.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('deployment.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("deployment.deleted", (event: MessageEvent) => { try { const data: types.Deployment = decode(JSON.parse(event.data), "Deployment"); - this.emit('deployment.deleted', data); + this.emit("deployment.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('deployment.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("deployment.updated", (event: MessageEvent) => { try { const data: types.Deployment = decode(JSON.parse(event.data), "Deployment"); - this.emit('deployment.updated', data); + this.emit("deployment.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('environment.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("environment.deleted", (event: MessageEvent) => { try { const data: types.Environment = decode(JSON.parse(event.data), "Environment"); - this.emit('environment.deleted', data); + this.emit("environment.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('environment.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("environment.updated", (event: MessageEvent) => { try { const data: types.Environment = decode(JSON.parse(event.data), "Environment"); - this.emit('environment.updated', data); + this.emit("environment.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('environment_cloud.updated', (event: MessageEvent) => { - try { - const data: types.EnvironmentCloudEvent = decode(JSON.parse(event.data), "EnvironmentCloudEvent"); - this.emit('environment_cloud.updated', data); - } catch (error) { - this.emit('error', error); - } - }); - - this.eventSource.addEventListener('forge.gap', (event: MessageEvent) => { + this.eventSource.addEventListener("forge.gap", (event: MessageEvent) => { try { const data: types.RealtimeForgeGap = decode(JSON.parse(event.data), "RealtimeForgeGap"); - this.emit('forge.gap', data); + this.emit("forge.gap", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('forge.resumed', (event: MessageEvent) => { + this.eventSource.addEventListener("forge.resumed", (event: MessageEvent) => { try { const data: types.RealtimeForgeResumed = decode(JSON.parse(event.data), "RealtimeForgeResumed"); - this.emit('forge.resumed', data); + this.emit("forge.resumed", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('manifest.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("manifest.deleted", (event: MessageEvent) => { try { const data: types.Revision = decode(JSON.parse(event.data), "Revision"); - this.emit('manifest.deleted', data); + this.emit("manifest.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('manifest.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("manifest.updated", (event: MessageEvent) => { try { const data: types.Revision = decode(JSON.parse(event.data), "Revision"); - this.emit('manifest.updated', data); + this.emit("manifest.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('node.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("node.updated", (event: MessageEvent) => { try { const data: types.Node = decode(JSON.parse(event.data), "Node"); - this.emit('node.updated', data); + this.emit("node.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('notification.created', (event: MessageEvent) => { + this.eventSource.addEventListener("notification.created", (event: MessageEvent) => { try { const data: types.NotificationCreated = decode(JSON.parse(event.data), "NotificationCreated"); - this.emit('notification.created', data); + this.emit("notification.created", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('plan.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("plan.deleted", (event: MessageEvent) => { try { const data: types.Plan = decode(JSON.parse(event.data), "Plan"); - this.emit('plan.deleted', data); + this.emit("plan.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('plan.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("plan.updated", (event: MessageEvent) => { try { const data: types.Plan = decode(JSON.parse(event.data), "Plan"); - this.emit('plan.updated', data); + this.emit("plan.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('project.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("project.deleted", (event: MessageEvent) => { try { const data: types.Project = decode(JSON.parse(event.data), "Project"); - this.emit('project.deleted', data); + this.emit("project.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('project.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("project.updated", (event: MessageEvent) => { try { const data: types.Project = decode(JSON.parse(event.data), "Project"); - this.emit('project.updated', data); + this.emit("project.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('realtime.snapshot', (event: MessageEvent) => { + this.eventSource.addEventListener("project_cloud.updated", (event: MessageEvent) => { + try { + const data: types.ProjectCloudEvent = decode(JSON.parse(event.data), "ProjectCloudEvent"); + this.emit("project_cloud.updated", data); + } catch (error) { + this.emit('error', error); + } + }); + + this.eventSource.addEventListener("realtime.snapshot", (event: MessageEvent) => { try { const data: types.RealtimeRealtimeSnapshot = decode(JSON.parse(event.data), "RealtimeRealtimeSnapshot"); - this.emit('realtime.snapshot', data); + this.emit("realtime.snapshot", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('realtime.status', (event: MessageEvent) => { + this.eventSource.addEventListener("realtime.status", (event: MessageEvent) => { try { const data: types.RealtimeRealtimeStatus = decode(JSON.parse(event.data), "RealtimeRealtimeStatus"); - this.emit('realtime.status', data); + this.emit("realtime.status", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('release_report.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("release_report.deleted", (event: MessageEvent) => { try { const data: types.ReleaseReportEvent = decode(JSON.parse(event.data), "ReleaseReportEvent"); - this.emit('release_report.deleted', data); + this.emit("release_report.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('release_report.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("release_report.updated", (event: MessageEvent) => { try { const data: types.ReleaseReportEvent = decode(JSON.parse(event.data), "ReleaseReportEvent"); - this.emit('release_report.updated', data); + this.emit("release_report.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('release_watch.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("release_watch.deleted", (event: MessageEvent) => { try { const data: types.Watch = decode(JSON.parse(event.data), "Watch"); - this.emit('release_watch.deleted', data); + this.emit("release_watch.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('release_watch.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("release_watch.updated", (event: MessageEvent) => { try { const data: types.Watch = decode(JSON.parse(event.data), "Watch"); - this.emit('release_watch.updated', data); + this.emit("release_watch.updated", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('source.deleted', (event: MessageEvent) => { + this.eventSource.addEventListener("source.deleted", (event: MessageEvent) => { try { const data: types.Source = decode(JSON.parse(event.data), "Source"); - this.emit('source.deleted', data); + this.emit("source.deleted", data); } catch (error) { this.emit('error', error); } }); - this.eventSource.addEventListener('source.updated', (event: MessageEvent) => { + this.eventSource.addEventListener("source.updated", (event: MessageEvent) => { try { const data: types.Source = decode(JSON.parse(event.data), "Source"); - this.emit('source.updated', data); + this.emit("source.updated", data); } catch (error) { this.emit('error', error); } @@ -843,7 +843,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when agent_report.deleted event is received */ onAgentReportDeleted(handler: (data: types.Report) => void): void { - this.on('agent_report.deleted', handler); + this.on("agent_report.deleted", handler); } /** @@ -851,7 +851,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offAgentReportDeleted(handler: (data: types.Report) => void): void { - this.off('agent_report.deleted', handler); + this.off("agent_report.deleted", handler); } /** @@ -859,7 +859,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when agent_report.updated event is received */ onAgentReportUpdated(handler: (data: types.Report) => void): void { - this.on('agent_report.updated', handler); + this.on("agent_report.updated", handler); } /** @@ -867,7 +867,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offAgentReportUpdated(handler: (data: types.Report) => void): void { - this.off('agent_report.updated', handler); + this.off("agent_report.updated", handler); } /** @@ -875,7 +875,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when agent_request.deleted event is received */ onAgentRequestDeleted(handler: (data: types.RequestEvent) => void): void { - this.on('agent_request.deleted', handler); + this.on("agent_request.deleted", handler); } /** @@ -883,7 +883,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offAgentRequestDeleted(handler: (data: types.RequestEvent) => void): void { - this.off('agent_request.deleted', handler); + this.off("agent_request.deleted", handler); } /** @@ -891,7 +891,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when agent_request.updated event is received */ onAgentRequestUpdated(handler: (data: types.RequestEvent) => void): void { - this.on('agent_request.updated', handler); + this.on("agent_request.updated", handler); } /** @@ -899,7 +899,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offAgentRequestUpdated(handler: (data: types.RequestEvent) => void): void { - this.off('agent_request.updated', handler); + this.off("agent_request.updated", handler); } /** @@ -907,7 +907,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when agent_task.deleted event is received */ onAgentTaskDeleted(handler: (data: types.TaskEvent) => void): void { - this.on('agent_task.deleted', handler); + this.on("agent_task.deleted", handler); } /** @@ -915,7 +915,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offAgentTaskDeleted(handler: (data: types.TaskEvent) => void): void { - this.off('agent_task.deleted', handler); + this.off("agent_task.deleted", handler); } /** @@ -923,7 +923,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when agent_task.updated event is received */ onAgentTaskUpdated(handler: (data: types.TaskEvent) => void): void { - this.on('agent_task.updated', handler); + this.on("agent_task.updated", handler); } /** @@ -931,7 +931,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offAgentTaskUpdated(handler: (data: types.TaskEvent) => void): void { - this.off('agent_task.updated', handler); + this.off("agent_task.updated", handler); } /** @@ -939,7 +939,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when analysis.deleted event is received */ onAnalysisDeleted(handler: (data: types.Analysis) => void): void { - this.on('analysis.deleted', handler); + this.on("analysis.deleted", handler); } /** @@ -947,7 +947,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offAnalysisDeleted(handler: (data: types.Analysis) => void): void { - this.off('analysis.deleted', handler); + this.off("analysis.deleted", handler); } /** @@ -955,7 +955,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when analysis.updated event is received */ onAnalysisUpdated(handler: (data: types.Analysis) => void): void { - this.on('analysis.updated', handler); + this.on("analysis.updated", handler); } /** @@ -963,7 +963,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offAnalysisUpdated(handler: (data: types.Analysis) => void): void { - this.off('analysis.updated', handler); + this.off("analysis.updated", handler); } /** @@ -971,7 +971,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when binding.deleted event is received */ onBindingDeleted(handler: (data: types.Binding) => void): void { - this.on('binding.deleted', handler); + this.on("binding.deleted", handler); } /** @@ -979,7 +979,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offBindingDeleted(handler: (data: types.Binding) => void): void { - this.off('binding.deleted', handler); + this.off("binding.deleted", handler); } /** @@ -987,7 +987,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when binding.updated event is received */ onBindingUpdated(handler: (data: types.Binding) => void): void { - this.on('binding.updated', handler); + this.on("binding.updated", handler); } /** @@ -995,7 +995,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offBindingUpdated(handler: (data: types.Binding) => void): void { - this.off('binding.updated', handler); + this.off("binding.updated", handler); } /** @@ -1003,7 +1003,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when build.collection event is received */ onBuildCollection(handler: (data: types.Collection) => void): void { - this.on('build.collection', handler); + this.on("build.collection", handler); } /** @@ -1011,7 +1011,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offBuildCollection(handler: (data: types.Collection) => void): void { - this.off('build.collection', handler); + this.off("build.collection", handler); } /** @@ -1019,7 +1019,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when build.log event is received */ onBuildLog(handler: (data: types.Log) => void): void { - this.on('build.log', handler); + this.on("build.log", handler); } /** @@ -1027,7 +1027,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offBuildLog(handler: (data: types.Log) => void): void { - this.off('build.log', handler); + this.off("build.log", handler); } /** @@ -1035,7 +1035,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when canary_verdict.deleted event is received */ onCanaryVerdictDeleted(handler: (data: types.CanaryVerdict) => void): void { - this.on('canary_verdict.deleted', handler); + this.on("canary_verdict.deleted", handler); } /** @@ -1043,7 +1043,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offCanaryVerdictDeleted(handler: (data: types.CanaryVerdict) => void): void { - this.off('canary_verdict.deleted', handler); + this.off("canary_verdict.deleted", handler); } /** @@ -1051,7 +1051,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when canary_verdict.updated event is received */ onCanaryVerdictUpdated(handler: (data: types.CanaryVerdict) => void): void { - this.on('canary_verdict.updated', handler); + this.on("canary_verdict.updated", handler); } /** @@ -1059,7 +1059,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offCanaryVerdictUpdated(handler: (data: types.CanaryVerdict) => void): void { - this.off('canary_verdict.updated', handler); + this.off("canary_verdict.updated", handler); } /** @@ -1067,7 +1067,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when cloud.deleted event is received */ onCloudDeleted(handler: (data: types.Profile) => void): void { - this.on('cloud.deleted', handler); + this.on("cloud.deleted", handler); } /** @@ -1075,7 +1075,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offCloudDeleted(handler: (data: types.Profile) => void): void { - this.off('cloud.deleted', handler); + this.off("cloud.deleted", handler); } /** @@ -1083,7 +1083,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when cloud.updated event is received */ onCloudUpdated(handler: (data: types.Profile) => void): void { - this.on('cloud.updated', handler); + this.on("cloud.updated", handler); } /** @@ -1091,7 +1091,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offCloudUpdated(handler: (data: types.Profile) => void): void { - this.off('cloud.updated', handler); + this.off("cloud.updated", handler); } /** @@ -1099,7 +1099,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when cloud_capacity.updated event is received */ onCloudCapacityUpdated(handler: (data: types.CapacityChange) => void): void { - this.on('cloud_capacity.updated', handler); + this.on("cloud_capacity.updated", handler); } /** @@ -1107,7 +1107,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offCloudCapacityUpdated(handler: (data: types.CapacityChange) => void): void { - this.off('cloud_capacity.updated', handler); + this.off("cloud_capacity.updated", handler); } /** @@ -1115,7 +1115,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when cloud_cluster.updated event is received */ onCloudClusterUpdated(handler: (data: types.ClusterChange) => void): void { - this.on('cloud_cluster.updated', handler); + this.on("cloud_cluster.updated", handler); } /** @@ -1123,7 +1123,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offCloudClusterUpdated(handler: (data: types.ClusterChange) => void): void { - this.off('cloud_cluster.updated', handler); + this.off("cloud_cluster.updated", handler); } /** @@ -1131,7 +1131,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when cloud_sync.updated event is received */ onCloudSyncUpdated(handler: (data: types.CloudSyncEvent) => void): void { - this.on('cloud_sync.updated', handler); + this.on("cloud_sync.updated", handler); } /** @@ -1139,7 +1139,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offCloudSyncUpdated(handler: (data: types.CloudSyncEvent) => void): void { - this.off('cloud_sync.updated', handler); + this.off("cloud_sync.updated", handler); } /** @@ -1147,7 +1147,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when cloud_target.deleted event is received */ onCloudTargetDeleted(handler: (data: types.Target) => void): void { - this.on('cloud_target.deleted', handler); + this.on("cloud_target.deleted", handler); } /** @@ -1155,7 +1155,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offCloudTargetDeleted(handler: (data: types.Target) => void): void { - this.off('cloud_target.deleted', handler); + this.off("cloud_target.deleted", handler); } /** @@ -1163,7 +1163,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when cloud_target.updated event is received */ onCloudTargetUpdated(handler: (data: types.Target) => void): void { - this.on('cloud_target.updated', handler); + this.on("cloud_target.updated", handler); } /** @@ -1171,7 +1171,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offCloudTargetUpdated(handler: (data: types.Target) => void): void { - this.off('cloud_target.updated', handler); + this.off("cloud_target.updated", handler); } /** @@ -1179,7 +1179,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when connection.deleted event is received */ onConnectionDeleted(handler: (data: types.Connection) => void): void { - this.on('connection.deleted', handler); + this.on("connection.deleted", handler); } /** @@ -1187,7 +1187,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offConnectionDeleted(handler: (data: types.Connection) => void): void { - this.off('connection.deleted', handler); + this.off("connection.deleted", handler); } /** @@ -1195,7 +1195,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when connection.updated event is received */ onConnectionUpdated(handler: (data: types.Connection) => void): void { - this.on('connection.updated', handler); + this.on("connection.updated", handler); } /** @@ -1203,7 +1203,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offConnectionUpdated(handler: (data: types.Connection) => void): void { - this.off('connection.updated', handler); + this.off("connection.updated", handler); } /** @@ -1211,7 +1211,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when deployment.deleted event is received */ onDeploymentDeleted(handler: (data: types.Deployment) => void): void { - this.on('deployment.deleted', handler); + this.on("deployment.deleted", handler); } /** @@ -1219,7 +1219,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offDeploymentDeleted(handler: (data: types.Deployment) => void): void { - this.off('deployment.deleted', handler); + this.off("deployment.deleted", handler); } /** @@ -1227,7 +1227,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when deployment.updated event is received */ onDeploymentUpdated(handler: (data: types.Deployment) => void): void { - this.on('deployment.updated', handler); + this.on("deployment.updated", handler); } /** @@ -1235,7 +1235,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offDeploymentUpdated(handler: (data: types.Deployment) => void): void { - this.off('deployment.updated', handler); + this.off("deployment.updated", handler); } /** @@ -1243,7 +1243,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when environment.deleted event is received */ onEnvironmentDeleted(handler: (data: types.Environment) => void): void { - this.on('environment.deleted', handler); + this.on("environment.deleted", handler); } /** @@ -1251,7 +1251,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offEnvironmentDeleted(handler: (data: types.Environment) => void): void { - this.off('environment.deleted', handler); + this.off("environment.deleted", handler); } /** @@ -1259,7 +1259,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when environment.updated event is received */ onEnvironmentUpdated(handler: (data: types.Environment) => void): void { - this.on('environment.updated', handler); + this.on("environment.updated", handler); } /** @@ -1267,23 +1267,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offEnvironmentUpdated(handler: (data: types.Environment) => void): void { - this.off('environment.updated', handler); - } - - /** - * Register a handler for environment_cloud.updated events. - * @param handler - Function to call when environment_cloud.updated event is received - */ - onEnvironmentCloudUpdated(handler: (data: types.EnvironmentCloudEvent) => void): void { - this.on('environment_cloud.updated', handler); - } - - /** - * Remove a handler for environment_cloud.updated events. - * @param handler - The handler to remove - */ - offEnvironmentCloudUpdated(handler: (data: types.EnvironmentCloudEvent) => void): void { - this.off('environment_cloud.updated', handler); + this.off("environment.updated", handler); } /** @@ -1291,7 +1275,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when forge.gap event is received */ onForgeGap(handler: (data: types.RealtimeForgeGap) => void): void { - this.on('forge.gap', handler); + this.on("forge.gap", handler); } /** @@ -1299,7 +1283,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offForgeGap(handler: (data: types.RealtimeForgeGap) => void): void { - this.off('forge.gap', handler); + this.off("forge.gap", handler); } /** @@ -1307,7 +1291,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when forge.resumed event is received */ onForgeResumed(handler: (data: types.RealtimeForgeResumed) => void): void { - this.on('forge.resumed', handler); + this.on("forge.resumed", handler); } /** @@ -1315,7 +1299,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offForgeResumed(handler: (data: types.RealtimeForgeResumed) => void): void { - this.off('forge.resumed', handler); + this.off("forge.resumed", handler); } /** @@ -1323,7 +1307,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when manifest.deleted event is received */ onManifestDeleted(handler: (data: types.Revision) => void): void { - this.on('manifest.deleted', handler); + this.on("manifest.deleted", handler); } /** @@ -1331,7 +1315,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offManifestDeleted(handler: (data: types.Revision) => void): void { - this.off('manifest.deleted', handler); + this.off("manifest.deleted", handler); } /** @@ -1339,7 +1323,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when manifest.updated event is received */ onManifestUpdated(handler: (data: types.Revision) => void): void { - this.on('manifest.updated', handler); + this.on("manifest.updated", handler); } /** @@ -1347,7 +1331,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offManifestUpdated(handler: (data: types.Revision) => void): void { - this.off('manifest.updated', handler); + this.off("manifest.updated", handler); } /** @@ -1355,7 +1339,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when node.updated event is received */ onNodeUpdated(handler: (data: types.Node) => void): void { - this.on('node.updated', handler); + this.on("node.updated", handler); } /** @@ -1363,7 +1347,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offNodeUpdated(handler: (data: types.Node) => void): void { - this.off('node.updated', handler); + this.off("node.updated", handler); } /** @@ -1371,7 +1355,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when notification.created event is received */ onNotificationCreated(handler: (data: types.NotificationCreated) => void): void { - this.on('notification.created', handler); + this.on("notification.created", handler); } /** @@ -1379,7 +1363,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offNotificationCreated(handler: (data: types.NotificationCreated) => void): void { - this.off('notification.created', handler); + this.off("notification.created", handler); } /** @@ -1387,7 +1371,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when plan.deleted event is received */ onPlanDeleted(handler: (data: types.Plan) => void): void { - this.on('plan.deleted', handler); + this.on("plan.deleted", handler); } /** @@ -1395,7 +1379,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offPlanDeleted(handler: (data: types.Plan) => void): void { - this.off('plan.deleted', handler); + this.off("plan.deleted", handler); } /** @@ -1403,7 +1387,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when plan.updated event is received */ onPlanUpdated(handler: (data: types.Plan) => void): void { - this.on('plan.updated', handler); + this.on("plan.updated", handler); } /** @@ -1411,7 +1395,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offPlanUpdated(handler: (data: types.Plan) => void): void { - this.off('plan.updated', handler); + this.off("plan.updated", handler); } /** @@ -1419,7 +1403,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when project.deleted event is received */ onProjectDeleted(handler: (data: types.Project) => void): void { - this.on('project.deleted', handler); + this.on("project.deleted", handler); } /** @@ -1427,7 +1411,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offProjectDeleted(handler: (data: types.Project) => void): void { - this.off('project.deleted', handler); + this.off("project.deleted", handler); } /** @@ -1435,7 +1419,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when project.updated event is received */ onProjectUpdated(handler: (data: types.Project) => void): void { - this.on('project.updated', handler); + this.on("project.updated", handler); } /** @@ -1443,7 +1427,23 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offProjectUpdated(handler: (data: types.Project) => void): void { - this.off('project.updated', handler); + this.off("project.updated", handler); + } + + /** + * Register a handler for project_cloud.updated events. + * @param handler - Function to call when project_cloud.updated event is received + */ + onProjectCloudUpdated(handler: (data: types.ProjectCloudEvent) => void): void { + this.on("project_cloud.updated", handler); + } + + /** + * Remove a handler for project_cloud.updated events. + * @param handler - The handler to remove + */ + offProjectCloudUpdated(handler: (data: types.ProjectCloudEvent) => void): void { + this.off("project_cloud.updated", handler); } /** @@ -1451,7 +1451,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when realtime.snapshot event is received */ onRealtimeSnapshot(handler: (data: types.RealtimeRealtimeSnapshot) => void): void { - this.on('realtime.snapshot', handler); + this.on("realtime.snapshot", handler); } /** @@ -1459,7 +1459,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offRealtimeSnapshot(handler: (data: types.RealtimeRealtimeSnapshot) => void): void { - this.off('realtime.snapshot', handler); + this.off("realtime.snapshot", handler); } /** @@ -1467,7 +1467,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when realtime.status event is received */ onRealtimeStatus(handler: (data: types.RealtimeRealtimeStatus) => void): void { - this.on('realtime.status', handler); + this.on("realtime.status", handler); } /** @@ -1475,7 +1475,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offRealtimeStatus(handler: (data: types.RealtimeRealtimeStatus) => void): void { - this.off('realtime.status', handler); + this.off("realtime.status", handler); } /** @@ -1483,7 +1483,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when release_report.deleted event is received */ onReleaseReportDeleted(handler: (data: types.ReleaseReportEvent) => void): void { - this.on('release_report.deleted', handler); + this.on("release_report.deleted", handler); } /** @@ -1491,7 +1491,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offReleaseReportDeleted(handler: (data: types.ReleaseReportEvent) => void): void { - this.off('release_report.deleted', handler); + this.off("release_report.deleted", handler); } /** @@ -1499,7 +1499,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when release_report.updated event is received */ onReleaseReportUpdated(handler: (data: types.ReleaseReportEvent) => void): void { - this.on('release_report.updated', handler); + this.on("release_report.updated", handler); } /** @@ -1507,7 +1507,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offReleaseReportUpdated(handler: (data: types.ReleaseReportEvent) => void): void { - this.off('release_report.updated', handler); + this.off("release_report.updated", handler); } /** @@ -1515,7 +1515,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when release_watch.deleted event is received */ onReleaseWatchDeleted(handler: (data: types.Watch) => void): void { - this.on('release_watch.deleted', handler); + this.on("release_watch.deleted", handler); } /** @@ -1523,7 +1523,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offReleaseWatchDeleted(handler: (data: types.Watch) => void): void { - this.off('release_watch.deleted', handler); + this.off("release_watch.deleted", handler); } /** @@ -1531,7 +1531,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when release_watch.updated event is received */ onReleaseWatchUpdated(handler: (data: types.Watch) => void): void { - this.on('release_watch.updated', handler); + this.on("release_watch.updated", handler); } /** @@ -1539,7 +1539,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offReleaseWatchUpdated(handler: (data: types.Watch) => void): void { - this.off('release_watch.updated', handler); + this.off("release_watch.updated", handler); } /** @@ -1547,7 +1547,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when source.deleted event is received */ onSourceDeleted(handler: (data: types.Source) => void): void { - this.on('source.deleted', handler); + this.on("source.deleted", handler); } /** @@ -1555,7 +1555,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offSourceDeleted(handler: (data: types.Source) => void): void { - this.off('source.deleted', handler); + this.off("source.deleted", handler); } /** @@ -1563,7 +1563,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - Function to call when source.updated event is received */ onSourceUpdated(handler: (data: types.Source) => void): void { - this.on('source.updated', handler); + this.on("source.updated", handler); } /** @@ -1571,7 +1571,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offSourceUpdated(handler: (data: types.Source) => void): void { - this.off('source.updated', handler); + this.off("source.updated", handler); } /** diff --git a/apps/dashboard/src/client/forge/loomplane/stream-bindings.ts b/apps/dashboard/src/client/forge/loomplane/stream-bindings.ts index 3006b35a8..d002ca3ba 100644 --- a/apps/dashboard/src/client/forge/loomplane/stream-bindings.ts +++ b/apps/dashboard/src/client/forge/loomplane/stream-bindings.ts @@ -41,19 +41,19 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/events', message: 'source.updated', - entity: 'Source', + entity: 'DiscoverySource', intent: 'upsert', - invalidates: ['Source[]'], - decode: (payload: unknown) => decode(payload, CODECS['Source']), + invalidates: ['DiscoverySource[]'], + decode: (payload: unknown) => decode(payload, CODECS['DiscoverySource']), }, { kind: 'entity', channel: '/api/v1/realtime/events', message: 'source.deleted', - entity: 'Source', + entity: 'DiscoverySource', intent: 'evict', - invalidates: ['Source[]'], - decode: (payload: unknown) => decode(payload, CODECS['Source']), + invalidates: ['DiscoverySource[]'], + decode: (payload: unknown) => decode(payload, CODECS['DiscoverySource']), }, { kind: 'entity', @@ -149,19 +149,19 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/events', message: 'deployment.updated', - entity: 'Deployment', + entity: 'DeploymentsDeployment', intent: 'upsert', - invalidates: ['Deployment[]', 'Instance[]'], - decode: (payload: unknown) => decode(payload, CODECS['Deployment']), + invalidates: ['DeploymentsDeployment[]', 'Instance[]'], + decode: (payload: unknown) => decode(payload, CODECS['DeploymentsDeployment']), }, { kind: 'entity', channel: '/api/v1/realtime/events', message: 'deployment.deleted', - entity: 'Deployment', + entity: 'DeploymentsDeployment', intent: 'evict', - invalidates: ['Deployment[]'], - decode: (payload: unknown) => decode(payload, CODECS['Deployment']), + invalidates: ['DeploymentsDeployment[]'], + decode: (payload: unknown) => decode(payload, CODECS['DeploymentsDeployment']), }, { kind: 'entity', @@ -169,7 +169,7 @@ export const streams = [ message: 'canary_verdict.updated', entity: 'CanaryVerdict', intent: 'upsert', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -178,7 +178,7 @@ export const streams = [ message: 'canary_verdict.deleted', entity: 'CanaryVerdict', intent: 'evict', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -221,28 +221,28 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/events', message: 'cloud_target.updated', - entity: 'Target', + entity: 'CloudprofilesTarget', intent: 'upsert', - invalidates: ['Target[]'], - decode: (payload: unknown) => decode(payload, CODECS['Target']), + invalidates: ['CloudprofilesTarget[]'], + decode: (payload: unknown) => decode(payload, CODECS['CloudprofilesTarget']), }, { kind: 'entity', channel: '/api/v1/realtime/events', message: 'cloud_target.deleted', - entity: 'Target', + entity: 'CloudprofilesTarget', intent: 'evict', - invalidates: ['Target[]'], - decode: (payload: unknown) => decode(payload, CODECS['Target']), + invalidates: ['CloudprofilesTarget[]'], + decode: (payload: unknown) => decode(payload, CODECS['CloudprofilesTarget']), }, { kind: 'entity', channel: '/api/v1/realtime/events', - message: 'environment_cloud.updated', - entity: 'EnvironmentCloudEvent', + message: 'project_cloud.updated', + entity: 'ProjectCloudEvent', intent: 'patch', - invalidates: ['EnvironmentCloud'], - decode: (payload: unknown) => decode(payload, CODECS['EnvironmentCloudEvent']), + invalidates: ['DefaultCloud:{projectId}'], + decode: (payload: unknown) => decode(payload, CODECS['ProjectCloudEvent']), }, { kind: 'entity', @@ -250,7 +250,7 @@ export const streams = [ message: 'cloud_sync.updated', entity: 'CloudSyncEvent', intent: 'patch', - invalidates: ['Sync', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'DefaultCloud:{projectId}'], decode: (payload: unknown) => decode(payload, CODECS['CloudSyncEvent']), }, { @@ -259,7 +259,7 @@ export const streams = [ message: 'cloud_cluster.updated', entity: 'ClusterChange', intent: 'patch', - invalidates: ['CloudCluster', 'CloudClusterPage', 'CloudClusterOperation', 'CloudClusterOperationPage', 'Target', 'Target[]', 'Connection', 'Connection[]', 'Profile', 'Profile[]'], + invalidates: ['CloudCluster:{resourceId}', 'CloudCluster[]', 'CloudClusterOperation:{operationId}', 'CloudClusterOperation[]', 'CloudprofilesTarget[]', 'Connection[]', 'Profile:{cloudId}'], decode: (payload: unknown) => decode(payload, CODECS['ClusterChange']), }, { @@ -268,7 +268,7 @@ export const streams = [ message: 'cloud_capacity.updated', entity: 'CapacityChange', intent: 'patch', - invalidates: ['CapacityPolicyView:{cloud_id}', 'CapacityUsage:{cloud_id}', 'Expansion[]'], + invalidates: ['CapacityPolicyView:{cloudId}', 'CapacityUsage:{cloudId}', 'Expansion[]'], decode: (payload: unknown) => decode(payload, CODECS['CapacityChange']), }, { @@ -277,7 +277,7 @@ export const streams = [ message: 'notification.created', entity: 'NotificationCreated', intent: 'upsert', - invalidates: ['NotificationList'], + invalidates: ['Notification[]'], decode: (payload: unknown) => decode(payload, CODECS['NotificationCreated']), }, { @@ -294,8 +294,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'agent_task.updated', entity: 'TaskEvent', - intent: 'upsert', - invalidates: ['AgentTask', 'AgentTask[]'], + intent: 'patch', + invalidates: ['Task:{id}'], decode: (payload: unknown) => decode(payload, CODECS['TaskEvent']), }, { @@ -303,8 +303,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'agent_task.deleted', entity: 'TaskEvent', - intent: 'evict', - invalidates: ['TaskEvent[]'], + intent: 'patch', + invalidates: ['Task:{id}'], decode: (payload: unknown) => decode(payload, CODECS['TaskEvent']), }, { @@ -313,7 +313,7 @@ export const streams = [ message: 'agent_report.updated', entity: 'Report', intent: 'upsert', - invalidates: ['AgentReport', 'AgentReport[]'], + invalidates: ['Report[]'], decode: (payload: unknown) => decode(payload, CODECS['Report']), }, { @@ -330,8 +330,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'agent_request.updated', entity: 'RequestEvent', - intent: 'upsert', - invalidates: ['AgentRequest', 'AgentRequest[]'], + intent: 'patch', + invalidates: ['Request:{id}', 'Request[]'], decode: (payload: unknown) => decode(payload, CODECS['RequestEvent']), }, { @@ -339,8 +339,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'agent_request.deleted', entity: 'RequestEvent', - intent: 'evict', - invalidates: ['RequestEvent[]'], + intent: 'patch', + invalidates: ['Request:{id}', 'Request[]'], decode: (payload: unknown) => decode(payload, CODECS['RequestEvent']), }, { @@ -348,8 +348,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'release_report.updated', entity: 'ReleaseReportEvent', - intent: 'upsert', - invalidates: ['ReleaseReport', 'ReleaseReport[]'], + intent: 'patch', + invalidates: ['ReleaseReport:{id}', 'ReleaseReport[]'], decode: (payload: unknown) => decode(payload, CODECS['ReleaseReportEvent']), }, { @@ -357,8 +357,8 @@ export const streams = [ channel: '/api/v1/realtime/events', message: 'release_report.deleted', entity: 'ReleaseReportEvent', - intent: 'evict', - invalidates: ['ReleaseReport', 'ReleaseReport[]'], + intent: 'patch', + invalidates: ['ReleaseReport:{id}', 'ReleaseReport[]'], decode: (payload: unknown) => decode(payload, CODECS['ReleaseReportEvent']), }, { @@ -419,19 +419,19 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/ws', message: 'source.updated', - entity: 'Source', + entity: 'DiscoverySource', intent: 'upsert', - invalidates: ['Source[]'], - decode: (payload: unknown) => decode(payload, CODECS['Source']), + invalidates: ['DiscoverySource[]'], + decode: (payload: unknown) => decode(payload, CODECS['DiscoverySource']), }, { kind: 'entity', channel: '/api/v1/realtime/ws', message: 'source.deleted', - entity: 'Source', + entity: 'DiscoverySource', intent: 'evict', - invalidates: ['Source[]'], - decode: (payload: unknown) => decode(payload, CODECS['Source']), + invalidates: ['DiscoverySource[]'], + decode: (payload: unknown) => decode(payload, CODECS['DiscoverySource']), }, { kind: 'entity', @@ -527,19 +527,19 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/ws', message: 'deployment.updated', - entity: 'Deployment', + entity: 'DeploymentsDeployment', intent: 'upsert', - invalidates: ['Deployment[]', 'Instance[]'], - decode: (payload: unknown) => decode(payload, CODECS['Deployment']), + invalidates: ['DeploymentsDeployment[]', 'Instance[]'], + decode: (payload: unknown) => decode(payload, CODECS['DeploymentsDeployment']), }, { kind: 'entity', channel: '/api/v1/realtime/ws', message: 'deployment.deleted', - entity: 'Deployment', + entity: 'DeploymentsDeployment', intent: 'evict', - invalidates: ['Deployment[]'], - decode: (payload: unknown) => decode(payload, CODECS['Deployment']), + invalidates: ['DeploymentsDeployment[]'], + decode: (payload: unknown) => decode(payload, CODECS['DeploymentsDeployment']), }, { kind: 'entity', @@ -547,7 +547,7 @@ export const streams = [ message: 'canary_verdict.updated', entity: 'CanaryVerdict', intent: 'upsert', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -556,7 +556,7 @@ export const streams = [ message: 'canary_verdict.deleted', entity: 'CanaryVerdict', intent: 'evict', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -599,28 +599,28 @@ export const streams = [ kind: 'entity', channel: '/api/v1/realtime/ws', message: 'cloud_target.updated', - entity: 'Target', + entity: 'CloudprofilesTarget', intent: 'upsert', - invalidates: ['Target[]'], - decode: (payload: unknown) => decode(payload, CODECS['Target']), + invalidates: ['CloudprofilesTarget[]'], + decode: (payload: unknown) => decode(payload, CODECS['CloudprofilesTarget']), }, { kind: 'entity', channel: '/api/v1/realtime/ws', message: 'cloud_target.deleted', - entity: 'Target', + entity: 'CloudprofilesTarget', intent: 'evict', - invalidates: ['Target[]'], - decode: (payload: unknown) => decode(payload, CODECS['Target']), + invalidates: ['CloudprofilesTarget[]'], + decode: (payload: unknown) => decode(payload, CODECS['CloudprofilesTarget']), }, { kind: 'entity', channel: '/api/v1/realtime/ws', - message: 'environment_cloud.updated', - entity: 'EnvironmentCloudEvent', + message: 'project_cloud.updated', + entity: 'ProjectCloudEvent', intent: 'patch', - invalidates: ['EnvironmentCloud'], - decode: (payload: unknown) => decode(payload, CODECS['EnvironmentCloudEvent']), + invalidates: ['DefaultCloud:{projectId}'], + decode: (payload: unknown) => decode(payload, CODECS['ProjectCloudEvent']), }, { kind: 'entity', @@ -628,7 +628,7 @@ export const streams = [ message: 'cloud_sync.updated', entity: 'CloudSyncEvent', intent: 'patch', - invalidates: ['Sync', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'DefaultCloud:{projectId}'], decode: (payload: unknown) => decode(payload, CODECS['CloudSyncEvent']), }, { @@ -637,7 +637,7 @@ export const streams = [ message: 'cloud_cluster.updated', entity: 'ClusterChange', intent: 'patch', - invalidates: ['CloudCluster', 'CloudClusterPage', 'CloudClusterOperation', 'CloudClusterOperationPage', 'Target', 'Target[]', 'Connection', 'Connection[]', 'Profile', 'Profile[]'], + invalidates: ['CloudCluster:{resourceId}', 'CloudCluster[]', 'CloudClusterOperation:{operationId}', 'CloudClusterOperation[]', 'CloudprofilesTarget[]', 'Connection[]', 'Profile:{cloudId}'], decode: (payload: unknown) => decode(payload, CODECS['ClusterChange']), }, { @@ -646,7 +646,7 @@ export const streams = [ message: 'cloud_capacity.updated', entity: 'CapacityChange', intent: 'patch', - invalidates: ['CapacityPolicyView:{cloud_id}', 'CapacityUsage:{cloud_id}', 'Expansion[]'], + invalidates: ['CapacityPolicyView:{cloudId}', 'CapacityUsage:{cloudId}', 'Expansion[]'], decode: (payload: unknown) => decode(payload, CODECS['CapacityChange']), }, { @@ -655,7 +655,7 @@ export const streams = [ message: 'notification.created', entity: 'NotificationCreated', intent: 'upsert', - invalidates: ['NotificationList'], + invalidates: ['Notification[]'], decode: (payload: unknown) => decode(payload, CODECS['NotificationCreated']), }, { @@ -672,8 +672,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'agent_task.updated', entity: 'TaskEvent', - intent: 'upsert', - invalidates: ['AgentTask', 'AgentTask[]'], + intent: 'patch', + invalidates: ['Task:{id}'], decode: (payload: unknown) => decode(payload, CODECS['TaskEvent']), }, { @@ -681,8 +681,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'agent_task.deleted', entity: 'TaskEvent', - intent: 'evict', - invalidates: ['TaskEvent[]'], + intent: 'patch', + invalidates: ['Task:{id}'], decode: (payload: unknown) => decode(payload, CODECS['TaskEvent']), }, { @@ -691,7 +691,7 @@ export const streams = [ message: 'agent_report.updated', entity: 'Report', intent: 'upsert', - invalidates: ['AgentReport', 'AgentReport[]'], + invalidates: ['Report[]'], decode: (payload: unknown) => decode(payload, CODECS['Report']), }, { @@ -708,8 +708,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'agent_request.updated', entity: 'RequestEvent', - intent: 'upsert', - invalidates: ['AgentRequest', 'AgentRequest[]'], + intent: 'patch', + invalidates: ['Request:{id}', 'Request[]'], decode: (payload: unknown) => decode(payload, CODECS['RequestEvent']), }, { @@ -717,8 +717,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'agent_request.deleted', entity: 'RequestEvent', - intent: 'evict', - invalidates: ['RequestEvent[]'], + intent: 'patch', + invalidates: ['Request:{id}', 'Request[]'], decode: (payload: unknown) => decode(payload, CODECS['RequestEvent']), }, { @@ -726,8 +726,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'release_report.updated', entity: 'ReleaseReportEvent', - intent: 'upsert', - invalidates: ['ReleaseReport', 'ReleaseReport[]'], + intent: 'patch', + invalidates: ['ReleaseReport:{id}', 'ReleaseReport[]'], decode: (payload: unknown) => decode(payload, CODECS['ReleaseReportEvent']), }, { @@ -735,8 +735,8 @@ export const streams = [ channel: '/api/v1/realtime/ws', message: 'release_report.deleted', entity: 'ReleaseReportEvent', - intent: 'evict', - invalidates: ['ReleaseReport', 'ReleaseReport[]'], + intent: 'patch', + invalidates: ['ReleaseReport:{id}', 'ReleaseReport[]'], decode: (payload: unknown) => decode(payload, CODECS['ReleaseReportEvent']), }, { diff --git a/apps/dashboard/src/client/forge/loomplane/types.ts b/apps/dashboard/src/client/forge/loomplane/types.ts index 7263a0dad..2f97386c3 100644 --- a/apps/dashboard/src/client/forge/loomplane/types.ts +++ b/apps/dashboard/src/client/forge/loomplane/types.ts @@ -296,18 +296,6 @@ export interface ArtifactChoice { service: string; } -export interface Assignment { - cloudId: string; - cloudRevision: number; - defaultPlacement?: DefaultPlacement; - environmentId: string; - grantRevision: number; - orgId: string; - projectId: string; - revision: number; - targets: CloudprofilesTarget[]; -} - export interface AttachDefaults { blockedPathPrefixes: string[]; cloudId?: string; @@ -648,7 +636,6 @@ export interface CapacityDemand { } export interface CapacityIntent { - assignmentRevision: number; cloudRevision: number; commitSha: string; demand: CapacityDemand; @@ -821,8 +808,8 @@ export interface ChangeInput { cloudId: string; connectionId?: string; default?: boolean; - environmentId?: string; poolId?: string; + projectDefault?: boolean; provider?: string; region?: string; revision: number; @@ -834,8 +821,8 @@ export interface ChangeInputBody { cloudId: string; connectionId?: string; default?: boolean; - environmentId?: string; poolId?: string; + projectDefault?: boolean; provider?: string; region?: string; revision: number; @@ -1053,7 +1040,6 @@ export interface CloudLocationList { export interface CloudPlacement { accountIdentity: string; allocation?: string; - assignmentRevision: number; cloudId: string; cloudRevision: number; connectionGeneration?: number; @@ -1889,6 +1875,17 @@ export interface DeclineInputBody { reason?: string; } +export interface DefaultCloud { + cloud: ProjectCloud | null; + projectId: string; + revision: number; +} + +export interface DefaultCloudInputBody { + cloudId: string; + revision: number; +} + export interface DefaultPlacement { connectionId: string; provider: string; @@ -2236,6 +2233,8 @@ export interface EditInputBody { version?: string; }; addService?: { + cloud?: string; + cloudTarget?: string; enabledIn?: string; kind?: string; name: string; @@ -2259,6 +2258,7 @@ export interface EditInputBody { }; placement?: { build?: Build; + cloud?: string; cloudSqlNetwork?: CloudSQLApplicationNetwork; cloudTags?: string[]; cloudTarget?: string; @@ -2423,24 +2423,6 @@ export interface EnvironmentChange { summary: PlanSummary; } -export interface EnvironmentCloud { - assignment: Assignment | null; - revision: number; -} - -export interface EnvironmentCloudEvent { - cloudId: string | null; - environmentId: string; - orgId: string; - projectId: string; - revision: number; -} - -export interface EnvironmentCloudInputBody { - cloudId: string; - revision: number; -} - export interface EnvironmentConnections { connections: Record; environment: string; @@ -2451,7 +2433,7 @@ export interface EnvironmentList { } export interface EnvironmentUsage { - assigned: boolean; + default: boolean; environmentId: string; environmentName: string; placements: PlacementUsage[]; @@ -3982,6 +3964,8 @@ export interface NewKeyBody { } export interface NewServiceInput { + cloud?: string; + cloudTarget?: string; enabledIn?: string; kind?: string; name: string; @@ -4654,10 +4638,10 @@ export interface PrepareInputBody { export interface Preview { after?: CloudprofilesTarget; - afterAssignment?: Assignment; + afterCloud?: ProjectCloud; afterDefault?: DefaultPlacement; before?: CloudprofilesTarget; - beforeAssignment?: Assignment; + beforeCloud?: ProjectCloud; beforeDefault?: DefaultPlacement; blockers: string[]; createdAt: string; @@ -4708,6 +4692,24 @@ export interface Project { updatedAt: string; } +export interface ProjectCloud { + cloudId: string; + cloudRevision: number; + default: boolean; + defaultPlacement?: DefaultPlacement; + grantRevision: number; + name: string; + orgId: string; + projectId: string; + targets: CloudprofilesTarget[]; +} + +export interface ProjectCloudEvent { + cloudId: string | null; + orgId: string; + projectId: string; +} + export interface ProjectDomain { hostnames: HostnameUse[]; mode: string; @@ -4724,6 +4726,7 @@ export interface ProjectDomainList { export interface ProjectGrant { cloudId: string; + default: boolean; orgId: string; projectId: string; revision: number; diff --git a/apps/dashboard/src/client/forge/loomplane/websocket.ts b/apps/dashboard/src/client/forge/loomplane/websocket.ts index fa9b0a708..da1a57cc1 100644 --- a/apps/dashboard/src/client/forge/loomplane/websocket.ts +++ b/apps/dashboard/src/client/forge/loomplane/websocket.ts @@ -137,7 +137,7 @@ export class RealtimeWsReceiveWSClient extends EventEmitter { this.setState(ConnectionState.CONNECTING); this.closed = false; - const wsURL = this.config.baseURL.replace(/^http/, 'ws') + '/api/v1/realtime/ws'; + const wsURL = this.config.baseURL.replace(/^http/, 'ws') + "/api/v1/realtime/ws"; // Setup connection timeout this.connectionTimeoutId = setTimeout(() => { diff --git a/apps/dashboard/src/client/streams.test.ts b/apps/dashboard/src/client/streams.test.ts new file mode 100644 index 000000000..696cb0219 --- /dev/null +++ b/apps/dashboard/src/client/streams.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "vitest" + +import { streams } from "@/client/forge/loomplane/stream-bindings" +import { agentTaskStream, REALTIME_EVENTS, REALTIME_WS } from "@/client/streams" +import spec from "../../specs/loomplane.openapi.json?raw" + +const openapi = JSON.parse(spec) as { paths: Record } + +describe("stream paths", () => { + it("are the channels the generated bindings listen on", () => { + const channels = new Set(streams.map((b) => b.channel)) + expect(channels).toContain(REALTIME_WS) + expect(channels).toContain(REALTIME_EVENTS) + }) + + it("name the agent task stream the API serves", () => { + expect(openapi.paths).toHaveProperty(["/api/v1/agent/tasks/{id}/stream"]) + expect(agentTaskStream("t/1")).toBe("/api/v1/agent/tasks/t%2F1/stream") + }) +}) diff --git a/apps/dashboard/src/client/streams.ts b/apps/dashboard/src/client/streams.ts new file mode 100644 index 000000000..ec56c6307 --- /dev/null +++ b/apps/dashboard/src/client/streams.ts @@ -0,0 +1,19 @@ +/** + * The stream endpoints the dashboard opens itself. Forge keeps WebSocket and + * SSE routes out of the REST operation manifest, so their paths live here, + * and streams.test.ts checks each one against the generated specs. + * + * Hand-written, and outside forge/ on purpose: `forge client check` reports + * any file under forge/ it didn't write. + */ + +/** The organization's live channel over WebSocket. */ +export const REALTIME_WS = "/api/v1/realtime/ws" + +/** The same channel over Server-Sent Events, the WebSocket's fallback. */ +export const REALTIME_EVENTS = "/api/v1/realtime/events" + +/** agentTaskStream is the SSE path that follows one agent task's events. */ +export function agentTaskStream(taskId: string): string { + return `/api/v1/agent/tasks/${encodeURIComponent(taskId)}/stream` +} diff --git a/apps/dashboard/src/client/tags.ts b/apps/dashboard/src/client/tags.ts new file mode 100644 index 000000000..4b35e6afe --- /dev/null +++ b/apps/dashboard/src/client/tags.ts @@ -0,0 +1,14 @@ +// Cache tags the hand-written bindings add to generated ones. Each typename +// comes from the generated contract rather than being spelled out, because +// the server names a type after its package when two share a name: a +// deployment is `DeploymentsDeployment`, and the day that changes these +// follow it instead of silently matching nothing. +import { op_deployments_get } from "@/client/forge/loomplane/ops/deployments.get" + +const deployment = op_deployments_get.entity + +/** Every deployment list; a deployment.updated event invalidates it. */ +export const deploymentLists = `${deployment}[]` + +/** One deployment, by the `{id}` path parameter. */ +export const deploymentItem = `${deployment}:{id}` diff --git a/apps/dashboard/src/components/add-service-dialog.test.tsx b/apps/dashboard/src/components/add-service-dialog.test.tsx index 209bd2907..9aecdc051 100644 --- a/apps/dashboard/src/components/add-service-dialog.test.tsx +++ b/apps/dashboard/src/components/add-service-dialog.test.tsx @@ -255,3 +255,71 @@ it("names a service from its path, and won't take a name in use", async () => { screen.getByRole("button", { name: "Add and plan staging" }) ).toBeDisabled() }) + +it("adds a service on a target of another Cloud instead of a provider", async () => { + const user = userEvent.setup() + const base = globalThis.fetch + const target = (id: string, name: string, cloud: string) => ({ + id, + name, + display_name: name.toUpperCase(), + cloud_id: cloud, + provider: "ecs-fargate", + connection_id: "conn", + revision: 1, + }) + vi.stubGlobal( + "fetch", + async (input: RequestInfo | URL, init?: RequestInit) => { + const path = new URL(String(input), "http://localhost").pathname + if (path === "/api/v1/projects/p/default-cloud") + return Response.json({ + project_id: "p", + revision: 1, + cloud: { + cloud_id: "main", + name: "Main", + default: true, + targets: [target("t1", "eu-run", "main")], + }, + }) + if (path === "/api/v1/projects/p/clouds") + return Response.json({ + clouds: [ + { id: "main", name: "Main" }, + { id: "lab", name: "GPU Lab" }, + ], + }) + if (path === "/api/v1/projects/p/clouds/lab/targets") + return Response.json({ targets: [target("t2", "a100", "lab")] }) + return base(input, init) + } + ) + show() + const found = await screen.findByRole("list", { + name: "Services analysis found", + }) + await user.click(within(found).getByRole("button", { name: /worker/ })) + await user.click(screen.getByRole("combobox", { name: "Runs on" })) + const lab = await screen.findByRole("group", { name: "GPU Lab" }) + expect(screen.getByRole("group", { name: "Main" })).toHaveTextContent( + "EU-RUN" + ) + await user.click(within(lab).getByRole("option", { name: "A100" })) + expect(screen.getByRole("combobox", { name: "Runs on" })).toHaveTextContent( + "a100 in GPU Lab" + ) + await user.click( + await screen.findByRole("button", { name: "Add and plan staging" }) + ) + await waitFor(() => expect(writes.length).toBeGreaterThan(0)) + expect(writes[0].body).toEqual({ + add_service: { + name: "worker", + source: "go:cmd/worker", + cloud: "GPU Lab", + cloud_target: "a100", + needs: ["db"], + }, + }) +}) diff --git a/apps/dashboard/src/components/add-service-dialog.tsx b/apps/dashboard/src/components/add-service-dialog.tsx index 42b201a51..536e27c27 100644 --- a/apps/dashboard/src/components/add-service-dialog.tsx +++ b/apps/dashboard/src/components/add-service-dialog.tsx @@ -37,6 +37,7 @@ import type { Manifest, Project, ServiceSuggestion, + Target, } from "@/client/forge/loomplane/types" import { useInvalidate, useQuery } from "@/client/hooks" import { CatalogDependencyPicker } from "@/components/catalog-dependency-picker" @@ -58,10 +59,17 @@ import { Label } from "@/components/ui/label" import { Select, SelectContent, + SelectGroup, SelectItem, + SelectLabel, SelectTrigger, SelectValue, } from "@/components/ui/select" +import { + cloudPick, + OtherCloudTargets, + usePlacementContext, +} from "@/components/deployment-targets" import { Skeleton } from "@/components/ui/skeleton" import { Spinner } from "@/components/ui/spinner" import { @@ -527,6 +535,13 @@ function Configure({ const [serviceKind, setServiceKind] = useState(suggestion?.service.kind ?? "") const [provider, setProvider] = useState(suggestion?.service.provider ?? "") const [target, setTarget] = useState(suggestion?.service.target ?? "") + // A Cloud target, in the Cloud named or the project's default (""), + // replaces a provider and connection. + const [onCloud, setOnCloud] = useState<{ + cloud: string + target: string + } | null>(null) + const clouds = usePlacementContext(project.id) const [port, setPort] = useState("") const [needs, setNeeds] = useState(suggestion?.service.needs ?? []) const [neededBy, setNeededBy] = useState([]) @@ -558,6 +573,27 @@ function Configure({ const chosenPlacement = placements.find((p) => p.key === placement) ?? placements[0] const runners = runnersOf(providers.data?.providers ?? [], serviceKind) + // A Cloud target fits when its provider runs this kind of service, or + // any kind when analysis will decide. + const runsHere = (t: Target): boolean => { + const p = clouds.catalog.find((c) => c.name === t.provider) + return ( + !p || + (p.available && + (serviceKind + ? !!p.runs?.some((r) => r.workload === serviceKind) + : (p.runs ?? []).length > 0)) + ) + } + const defaultTargets = clouds.cloudTargets.filter(runsHere) + const cloudIndex = onCloud?.cloud + ? clouds.otherClouds.findIndex((c) => c.name === onCloud.cloud) + : -1 + const runsOnValue = onCloud + ? onCloud.cloud + ? `cloud@${cloudIndex}:${onCloud.target}` + : `cloud:${onCloud.target}` + : provider || "default" const ownTargets = (connections.data?.connections ?? []).filter( (c) => c.status === "ready" && @@ -613,10 +649,17 @@ function Configure({ source: source.trim(), ...(repo ? { repo } : {}), ...(serviceKind ? { kind: serviceKind } : {}), - ...(provider ? { provider } : {}), - ...(target && (provider === "server" || provider === "kubernetes") - ? { target } - : {}), + ...(onCloud + ? { + cloudTarget: onCloud.target, + ...(onCloud.cloud ? { cloud: onCloud.cloud } : {}), + } + : { + ...(provider ? { provider } : {}), + ...(target && (provider === "server" || provider === "kubernetes") + ? { target } + : {}), + }), ...(port.trim() ? { port: portNumber } : {}), ...(needs.length ? { needs } : {}), ...scope, @@ -799,14 +842,29 @@ function Configure({ - {(provider === "server" || provider === "kubernetes") && ( + {!onCloud && (provider === "server" || provider === "kubernetes") && ( { setError("") setReviewing(name) }} > - Review service edit + Review {mode === "tags" && ( @@ -309,10 +332,8 @@ export function ServiceAdoption({ : `Assign ${reviewing} to ${pending}`} - Save this manifest edit for {environment.name}. Your running - service stays on its applied account until the next reviewed - deployment or Cloud sync. Other environments keep their - effective placement. + Every environment runs {reviewing} there from its next + deployment. What runs now stays where it is until then. {typeof pending === "object" && ( @@ -322,12 +343,15 @@ export function ServiceAdoption({ className="max-h-64 overflow-auto rounded-lg bg-muted p-3 text-xs" aria-label="Manifest adoption preview" > - {JSON.stringify(next, null, 2)} + {JSON.stringify( + { [reviewing]: next.services?.[reviewing] }, + null, + 2 + )}

- Revision {manifest.data.revision}. Conflicting direct placement - and inherited defaults are removed from this service; other - entries retain their provider and region. + Saves loomplane.yaml revision {manifest.data.revision + 1}. Any + placement an environment set for {reviewing} is cleared.

{error && ( diff --git a/apps/dashboard/src/components/cloud-targets/sync-history.tsx b/apps/dashboard/src/components/cloud-targets/sync-history.tsx index ed69bd3c1..2f74fe9db 100644 --- a/apps/dashboard/src/components/cloud-targets/sync-history.tsx +++ b/apps/dashboard/src/components/cloud-targets/sync-history.tsx @@ -5,7 +5,7 @@ import { Field as FormField, FieldLabel } from "@/components/ui/field" import { useEffect, useState } from "react" import * as api from "@/client/forge/loomplane/hooks" import type { Sync } from "@/client/forge/loomplane/types" -import { useMutation, useQuery } from "@/client/hooks" +import { useMutation, useQuery, useRefetchWhile } from "@/client/hooks" import { messageOf } from "@/client/errors" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" @@ -23,7 +23,8 @@ export function SyncHistory({ onChanged, }: { projectId: string - environmentId: string + /** environmentId narrows the list to one environment; omit it for all. */ + environmentId?: string refresh: number onChanged: () => Promise }) { @@ -50,7 +51,8 @@ function SyncList({ onChanged, }: { projectId: string - environmentId: string + /** environmentId narrows the list to one environment; omit it for all. */ + environmentId?: string refresh: number onChanged: () => Promise }) { @@ -72,18 +74,12 @@ function SyncList({ const rows = all.filter( (s): s is Sync => !!s && - (s.environments ?? []).some((e) => e.environmentId === environmentId) + (!environmentId || + (s.environments ?? []).some((e) => e.environmentId === environmentId)) ) const moving = all.some((s) => s && activeSync(s)) - useEffect(() => { - const timer = window.setInterval( - () => { - void refetchSyncs().catch(() => undefined) - }, - moving ? 3000 : 15000 - ) - return () => window.clearInterval(timer) - }, [moving, refetchSyncs]) + // cloud_sync.updated refreshes the list; poll only while it's down. + useRefetchWhile(moving, refetchSyncs, 3000) return (

Sync history

@@ -97,8 +93,10 @@ function SyncList({ Loading sync history... ) : !rows.length ? ( ) : (
diff --git a/apps/dashboard/src/components/cloud-targets/workspace.tsx b/apps/dashboard/src/components/cloud-targets/workspace.tsx index 21ad8cc0f..da0bd55f0 100644 --- a/apps/dashboard/src/components/cloud-targets/workspace.tsx +++ b/apps/dashboard/src/components/cloud-targets/workspace.tsx @@ -1,24 +1,14 @@ -import { CloudSelect as Select } from "@/components/cloud-targets/cloud-select" import { Card } from "@/components/ui/card" import { Item, ItemGroup } from "@/components/ui/item" -import { - CloudLoading, - listItemClass, -} from "@/components/cloud-targets/infrastructure-ui" +import { listItemClass } from "@/components/cloud-targets/infrastructure-ui" import { Alert, AlertDescription } from "@/components/ui/alert" -import { - SelectTrigger, - SelectValue, - SelectContent, - SelectItem, -} from "@/components/ui/select" import { Field as FormField, FieldLabel } from "@/components/ui/field" -import { type ReactNode, useEffect, useState } from "react" -import { PlusIcon } from "lucide-react" +import { type ReactNode, useState } from "react" +import { ChevronRightIcon, PlusIcon } from "lucide-react" import * as api from "@/client/forge/loomplane/hooks" import type { Connection, - Environment, + DefaultPlacement, Profile, Target, } from "@/client/forge/loomplane/types" @@ -50,6 +40,7 @@ import { CloudGlyph } from "@/components/cloud-glyph" import { CloudsIcon } from "@/components/icons" import { cloudLabel } from "@/lib/clouds" import { cn } from "@/lib/utils" +import { StatusPill } from "@/components/runs" import { AccountSummary, cloudOf } from "./target-mix" import { TargetEditor } from "./target-editor" @@ -82,297 +73,224 @@ export function EmptyClouds({ ) } +/** + * CloudWorkspace is a project's Clouds: every Cloud granted to it, with the + * default first. Every environment deploys through the default Cloud, so + * nothing here is per environment; an environment differs only where + * loomplane.yaml, or the deploy screen, says so. + */ export function CloudWorkspace({ projectId, - environment: wanted, cloudId, }: { projectId: string - /** The environment to open on by name, such as one a Cloud's page links to. */ - environment?: string /** The Cloud to open on, such as the one a Cloud's own page is about. */ cloudId?: string -}) { - const environments = useQuery(api.useEnvironmentsList, { - path: { id: projectId }, - }) - const { session } = useOrganization() - const preference = `loomplane.clouds.environment.${session.orgId}.${projectId}` - // A pick made here wins over the linked environment, which wins over the - // last one picked on this device. - const [chosen, setChosen] = useState("") - const [stored] = useState(() => window.localStorage.getItem(preference) ?? "") - const list = environments.data?.environments ?? [] - const environment = - list.find((e) => e.id === chosen) ?? - list.find((e) => e.name === wanted) ?? - list.find((e) => e.id === stored) ?? - list[0] - return environments.status === "error" ? ( - - ) : !environments.data ? ( - - ) : !environment ? ( - - ) : ( - - - Environment - - - - } - /> - ) -} -function EnvironmentWorkspace({ - projectId, - cloudId, - environment, - environments, - scopeControls, -}: { - projectId: string - cloudId?: string - environment: Environment - environments: Environment[] - scopeControls: ReactNode }) { const { can } = useOrganization() const manage = can("cloud_account:manage") - const deploy = manage && can("deployment:approve") + const review = manage && can("deployment:approve") const profiles = useQuery(api.useCloudsList, { path: { id: projectId } }) - const assignment = useQuery(api.useEnvironmentCloudsGet, { - path: { id: projectId, environmentId: environment.id }, - }) - const { refetch: refetchAssignment } = assignment - const { refetch: refetchProfiles } = profiles - const [chosen, setChosen] = useState(cloudId ?? "") + const current = useQuery(api.useDefaultCloudGet, { path: { id: projectId } }) + const [open, setOpen] = useState(cloudId) const [editing, setEditing] = useState(null) - const [assigning, setAssigning] = useState(false) - const [unassign, setUnassign] = useState(false) - const [refresh, setRefresh] = useState(0) - const list = (profiles.data?.clouds ?? []).filter((p): p is Profile => !!p) - const profile = - list.find((p) => p.id === chosen) ?? - list.find((p) => p.id === assignment.data?.assignment?.cloudId) ?? - list[0] - const reload = async () => { - await Promise.allSettled([refetchProfiles(), refetchAssignment()]) - setRefresh((n) => n + 1) - } - // Lists have no generated cache tags. Bounded reads also cover reconnects and - // changes made in another tab while retaining the server's persisted status. - useEffect(() => { - const timer = window.setInterval(() => { - void refetchProfiles().catch(() => undefined) - void refetchAssignment().catch(() => undefined) - }, 15000) - return () => window.clearInterval(timer) - }, [refetchProfiles, refetchAssignment]) + const [making, setMaking] = useState(null) + if (profiles.status === "error" || current.status === "error") + return ( + + Promise.allSettled([profiles.refetch(), current.refetch()]) + } + /> + ) + if (!profiles.data || !current.data) return + const defaultId = current.data.cloud?.cloudId + const list = (profiles.data.clouds ?? []) + .filter((p): p is Profile => !!p) + .sort((a, b) => + a.id === defaultId + ? -1 + : b.id === defaultId + ? 1 + : a.name.localeCompare(b.name) + ) + const expanded = open ?? defaultId ?? list[0]?.id return ( - <> - {(profiles.status === "error" || - assignment.status === "error" || - !profiles.data || - !assignment.data) && ( -
- {scopeControls} -
- )} - {profiles.status === "error" || assignment.status === "error" ? ( - - ) : !profiles.data || !assignment.data ? ( - +
+
+
+

Clouds

+

+ Every environment deploys through the default Cloud. A service can + run on another Cloud's target: pick it below, or set{" "} + cloud beside{" "} + cloud_target in + loomplane.yaml. +

+
+ {manage && ( + + )} +
+ {!list.length ? ( + + {manage && ( + + )} + ) : ( - <> -
- {scopeControls} - - - Cloud - - - - {manage && ( - <> - - {profile && ( - - )} - - )} -
- {environment.name} currently uses{" "} - {list.find((p) => p.id === assignment.data?.assignment?.cloudId) - ?.name ?? - (assignment.data.assignment - ? assignment.data.assignment.cloudId - : "direct service placement")} - . - {profile && - assignment.data.assignment?.cloudId !== profile.id && ( - <> - {" "} - - - )} - {assignment.data.assignment && ( - - )} -
-
- {!profile ? ( - - {manage && ( - - )} - - ) : ( - + {!defaultId && ( + + + This project has no default Cloud, so services can't name a + target yet. Make one of these its default. + + + )} + {list.map((profile) => ( + - )} - {assigning && ( - setAssigning(false)} - onApplied={() => { - setAssigning(false) - void reload() - }} + isDefault={profile.id === defaultId} + fallback={ + profile.id === defaultId + ? current.data?.cloud?.defaultPlacement + : undefined + } + expanded={profile.id === expanded} + onToggle={() => + setOpen(profile.id === expanded ? "" : profile.id) + } + onMakeDefault={review ? () => setMaking(profile.id) : undefined} + onManage={manage ? () => setEditing(profile) : undefined} /> - )} - - + ))} +
+ )} + {making !== null && ( + setMaking(null)} + onApplied={() => setMaking(null)} + /> )} + {}} + /> {editing && ( setEditing(null)} onSaved={(id) => { - setChosen(id) + if (id) setOpen(id) setEditing(null) - void reload() }} /> )} - +
+ ) +} + +/** + * CloudCard is one Cloud granted to the project: a one-line summary that + * opens to its targets, and for the default Cloud, where each service runs. + */ +function CloudCard({ + projectId, + profile, + isDefault, + fallback, + expanded, + onToggle, + onMakeDefault, + onManage, +}: { + projectId: string + profile: Profile + isDefault: boolean + fallback?: DefaultPlacement | null + expanded: boolean + onToggle: () => void + onMakeDefault?: () => void + onManage?: () => void +}) { + const targets = useQuery(api.useCloudTargetsList, { + path: { id: projectId, cloudId: profile.id }, + }) + const count = (targets.data?.targets ?? []).filter(Boolean).length + return ( + +
+ +
+ {!isDefault && onMakeDefault && ( + + )} + {onManage && ( + + )} +
+
+ {expanded && ( +
+ + !!t + )} + cloud={isDefault ? undefined : profile.name} + fallback={fallback} + /> +
+ )} +
) } + export function CloudForm({ projectId, profile, @@ -425,8 +343,8 @@ export function CloudForm({ {profile ? "Manage Cloud" : "New Cloud"} {profile - ? "Rename this Cloud or delete it after removing its assignments and references." - : "Create a named set of deployment targets for this project."} + ? "Rename this Cloud, or delete it once no project uses it." + : "A named set of deployment targets. A project's first Cloud becomes its default."} @@ -471,26 +389,15 @@ export function CloudForm({ function Targets({ projectId, profile, - environment, - environments, - assigned, - refresh, - reload, }: { projectId: string profile: Profile - environment: Environment - environments: Environment[] - assigned: boolean - refresh: number - reload: () => Promise }) { const { can } = useOrganization() const manage = can("cloud_account:manage") const targets = useQuery(api.useCloudTargetsList, { path: { id: projectId, cloudId: profile.id }, }) - const { refetch: refetchTargets } = targets const connections = useQuery(api.useConnectionsList) const [query, setQuery] = useState("") const [editing, setEditing] = useState(null) @@ -501,13 +408,6 @@ function Targets({ .toLowerCase() .includes(query.toLowerCase()) ) - useEffect(() => { - void refetchTargets().catch(() => undefined) - const timer = window.setInterval(() => { - void refetchTargets().catch(() => undefined) - }, 15000) - return () => window.clearInterval(timer) - }, [refresh, refetchTargets]) return (
@@ -533,7 +433,7 @@ function Targets({ error={targets.error ?? connections.error} fallback="Targets couldn't be loaded." retry={() => - Promise.allSettled([refetchTargets(), connections.refetch()]) + Promise.allSettled([targets.refetch(), connections.refetch()]) } /> ) : !targets.data || !connections.data ? ( @@ -568,22 +468,6 @@ function Targets({ onEdit={setEditing} /> )} - {assigned && ( - - )} - {assigned && ( - - )} {editing && ( setEditing(null)} - onSaved={() => { - setEditing(null) - void refetchTargets() - void reload() - }} + onSaved={() => setEditing(null)} /> )}
) } -function AppliedPlacement({ - projectId, - environment, - refresh, -}: { - projectId: string - environment: Environment - refresh: number -}) { - const bindings = useQuery(api.useBindingsList, { - path: { id: projectId }, - query: { environment: environment.name }, - }) - const { refetch: refetchBindings } = bindings - const accounts = useQuery(api.useConnectionsList) - useEffect(() => { - void refetchBindings().catch(() => undefined) - const timer = window.setInterval(() => { - void refetchBindings().catch(() => undefined) - }, 5000) - return () => window.clearInterval(timer) - }, [refresh, refetchBindings]) - if (bindings.status === "error") - return ( - - ) - if (!bindings.data) - return Loading applied accounts... - const services = bindings.data.bindings.filter((b) => b.subject === "service") - return ( -
-

- Applied accounts in {environment.name} -

- {!services.length ? ( - - ) : ( -
- {services.map((b) => ( -
- {b.name} - - {b.provider} ·{" "} - {accounts.data?.connections.find((c) => c.id === b.connectionId) - ?.name ?? b.connectionId}{" "} - · {b.commitSha?.slice(0, 8)} - - {b.url && ( - - Open service - - )} -
- ))} -
- )} -
- ) -} - /** * TargetTable lists a Cloud's targets with the account each points at, under * a summary of the accounts and providers they span. diff --git a/apps/dashboard/src/components/deploy-dialog.tsx b/apps/dashboard/src/components/deploy-dialog.tsx index 9274292da..0730fd176 100644 --- a/apps/dashboard/src/components/deploy-dialog.tsx +++ b/apps/dashboard/src/components/deploy-dialog.tsx @@ -409,10 +409,7 @@ function DeployScreen({ query: { environment }, }) const scope = useDeploymentScope(project.id, environment) - const ctx = usePlacementContext( - project.id, - environments.find((e) => e.name === environment)?.id - ) + const ctx = usePlacementContext(project.id) const manifest = current.data?.manifest const graph = view.data?.graph const rows = diff --git a/apps/dashboard/src/components/deploy.tsx b/apps/dashboard/src/components/deploy.tsx index a266944c0..d34e0f308 100644 --- a/apps/dashboard/src/components/deploy.tsx +++ b/apps/dashboard/src/components/deploy.tsx @@ -344,10 +344,7 @@ function WhereServicesRun({ project }: { project: Project }) { const environment = list.some((e) => e.name === picked) ? picked : (list[0]?.name ?? "") - const ctx = usePlacementContext( - project.id, - list.find((e) => e.name === environment)?.id - ) + const ctx = usePlacementContext(project.id) const manifest = current.data?.manifest const rows = manifest && view.data?.graph diff --git a/apps/dashboard/src/components/deployment-targets.test.tsx b/apps/dashboard/src/components/deployment-targets.test.tsx index c0384d43c..c7d97b126 100644 --- a/apps/dashboard/src/components/deployment-targets.test.tsx +++ b/apps/dashboard/src/components/deployment-targets.test.tsx @@ -639,3 +639,89 @@ it("offers a finding's fix for the deployment page to show", async () => { ) await vi.waitFor(() => expect(writes).toEqual([{ ignore: "redis" }])) }) + +it("lists every Cloud's targets and puts a service on another Cloud's", async () => { + const manifest: Manifest = { + version: 1, + services: { web: { source: "node:web", cloud_target: "frontend" } }, + } + const saves: Record[] = [] + const target = (id: string, name: string, cloud: string) => ({ + id, + name, + display_name: name.toUpperCase(), + cloud_id: cloud, + provider: "vercel", + connection_id: "conn", + revision: 1, + }) + vi.stubGlobal( + "fetch", + async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input) + if (init?.method === "PUT") { + saves.push(JSON.parse(String(init.body))) + return json({ id: "rev", revision: 2, manifest }) + } + if (url.endsWith("/providers")) + return json({ + providers: [ + { + name: "vercel", + title: "Vercel", + cloud: "vercel", + available: true, + runs: [{ workload: "http-service" }], + }, + ], + }) + if (url.endsWith("/default-cloud")) + return json({ + project_id: "p", + revision: 1, + cloud: { + cloud_id: "main", + name: "Main", + default: true, + targets: [target("t1", "frontend", "main")], + }, + }) + if (url.endsWith("/projects/p/clouds")) + return json({ + clouds: [ + { id: "main", name: "Main" }, + { id: "lab", name: "GPU Lab" }, + ], + }) + if (url.endsWith("/clouds/lab/targets")) + return json({ targets: [target("t2", "a100", "lab")] }) + return json({}) + } + ) + panel(manifest, service(manifest, "web")) + await userEvent.click( + await screen.findByRole("combobox", { name: "Target for web" }) + ) + // Each Cloud's targets sit under its own name. + const lab = await screen.findByRole("group", { name: "GPU Lab" }) + expect(screen.getByRole("group", { name: "Main" })).toHaveTextContent( + "FRONTEND" + ) + await userEvent.click(within(lab).getByRole("option", { name: "A100" })) + expect( + screen.getByRole("combobox", { name: "Target for web" }) + ).toHaveTextContent("a100 in GPU Lab") + await userEvent.click(screen.getByRole("button", { name: "Save placement" })) + await vi.waitFor(() => expect(saves).toHaveLength(1)) + expect(saves[0]).toMatchObject({ + manifest: { + services: { + web: { + environments: { + production: { cloud: "GPU Lab", cloud_target: "a100" }, + }, + }, + }, + }, + }) +}) diff --git a/apps/dashboard/src/components/deployment-targets.tsx b/apps/dashboard/src/components/deployment-targets.tsx index 0a68d1c02..9e649bac9 100644 --- a/apps/dashboard/src/components/deployment-targets.tsx +++ b/apps/dashboard/src/components/deployment-targets.tsx @@ -7,8 +7,10 @@ import { toast } from "sonner" import { messageOf } from "@/client/errors" import { + useCloudTargetsList, + useCloudsList, useConnectionsList, - useEnvironmentCloudsGet, + useDefaultCloudGet, useEnvironmentConnectionsChoose, useEnvironmentConnectionsGet, useManifestsCurrent, @@ -20,6 +22,7 @@ import type { Connection, Environment, Manifest, + Profile, Provider, Target, } from "@/client/forge/loomplane/types" @@ -147,8 +150,8 @@ export function usePlacementSave(projectId: string) { } } -// placedManifest applies one edit in memory. A Cloud target choice rewrites -// the service across environments first, as adopting one on its own does. +// placedManifest applies one edit in memory. A Cloud target choice made here +// is for this environment only; the others keep where they run. function placedManifest( m: Manifest, environments: Environment[], @@ -159,10 +162,10 @@ function placedManifest( return applyPlacement(m, e.row, e.environment, e.changes) const adopted = adoptServiceTarget( m, - environments, - e.environment, e.row.name, - choice + choice, + { environment: e.environment, environments }, + e.changes.cloud ) const rest = { ...e.changes } for (const key of cloudOwnedFields) delete rest[key] @@ -171,24 +174,82 @@ function placedManifest( /** * usePlacementContext loads what a "Runs on" cell names: the provider - * catalog, the environment's Cloud targets and the organization's accounts. + * catalog, the project's default Cloud and its targets, and the + * organization's accounts. Every environment shares the default Cloud. */ -export function usePlacementContext(projectId: string, environmentId?: string) { +export function usePlacementContext(projectId: string) { const providers = useQuery(useProvidersList) const connections = useQuery(useConnectionsList) - const cloud = useQuery(useEnvironmentCloudsGet, { - path: { id: projectId, environmentId: environmentId ?? "" }, - }) + const cloud = useQuery(useDefaultCloudGet, { path: { id: projectId } }) + const clouds = useQuery(useCloudsList, { path: { id: projectId } }) + const id = cloud.data?.cloud?.cloudId return { providers, catalog: providers.data?.providers ?? [], connections: connections.data?.connections ?? [], - cloudTargets: (cloud.data?.assignment?.targets ?? []).filter( + /** otherClouds are the project's Clouds besides its default. */ + otherClouds: (clouds.data?.clouds ?? []).filter( + (c): c is Profile => !!c && c.id !== id + ), + /** cloudName names the default Cloud; undefined when there is none. */ + cloudName: id + ? (clouds.data?.clouds?.find((c) => c?.id === id)?.name ?? + "Default Cloud") + : undefined, + cloudTargets: (cloud.data?.cloud?.targets ?? []).filter( (t): t is Target => !!t ), } } +/** + * cloudPick turns a "Runs on" value for a Cloud target into the fields it + * sets: `cloud:` is the default Cloud's, `cloud@:` the + * i-th other Cloud's. Choosing a target replaces any direct placement. + */ +export function cloudPick(value: string, others: Profile[]): PlacementFields { + const named = /^cloud@(\d+):(.+)$/.exec(value) + return { + cloud: named ? (others[Number(named[1])]?.name ?? "") : "", + cloudTarget: named ? named[2] : value.slice("cloud:".length), + } +} + +/** + * OtherCloudTargets is one Cloud besides the default in the "Runs on" list: + * its targets that can run this workload, under the Cloud's name. Nothing + * shows while they load or when none fit. + */ +export function OtherCloudTargets({ + projectId, + cloud, + index, + runsHere, +}: { + projectId: string + cloud: Profile + index: number + runsHere: (t: Target) => boolean +}) { + const targets = useQuery(useCloudTargetsList, { + path: { id: projectId, cloudId: cloud.id }, + }) + const usable = (targets.data?.targets ?? []).filter( + (t): t is Target => !!t && runsHere(t) + ) + if (!usable.length) return null + return ( + + {cloud.name} + {usable.map((t) => ( + + {t.displayName || t.name} + + ))} + + ) +} + /** RunsOnCell is a table cell naming where a row runs, and where it moves. */ export function RunsOnCell({ runs, @@ -316,11 +377,8 @@ function PlacementForm({ onClose: () => void onPendingChange?: (pending: boolean) => void }) { - const environmentId = environments.find((e) => e.name === environment)?.id - const { providers, cloudTargets } = usePlacementContext( - projectId, - environmentId - ) + const { providers, cloudTargets, cloudName, otherClouds } = + usePlacementContext(projectId) return ( <> @@ -352,10 +410,11 @@ function PlacementForm({ revision={revision} row={row} environment={environment} - environmentId={environmentId} environments={environments} catalog={providers.data.providers} cloudTargets={cloudTargets} + cloudName={cloudName} + otherClouds={otherClouds} mode={mode} pending={pending} onUse={onUse} @@ -376,10 +435,11 @@ function PlacementChoices({ revision, row, environment, - environmentId, environments, catalog, cloudTargets, + cloudName, + otherClouds, mode, pending, onUse, @@ -392,10 +452,11 @@ function PlacementChoices({ revision: number row: PlacementRow environment: string - environmentId?: string environments: Environment[] catalog: Provider[] cloudTargets: Target[] + cloudName?: string + otherClouds: Profile[] mode: "pending" | "save" pending?: PendingPlacement onUse?: (change: PendingPlacement) => void @@ -403,7 +464,7 @@ function PlacementChoices({ onClose: () => void onPendingChange?: (pending: boolean) => void }) { - const { can, session } = useOrganization() + const { can } = useOrganization() const placement = usePlacementSave(projectId) const connections = useQuery(useConnectionsList) const settings = placementSettings(manifest, row, environment) @@ -420,24 +481,31 @@ function PlacementChoices({ const cloudChosen = !!value.cloudTarget || !!value.cloudTags?.length // Only services can run on a Cloud target. Offer those whose provider can // run this workload; a target whose provider the catalog doesn't know stays. + const runsHere = (t: Target): boolean => { + const p = catalog.find((c) => c.name === t.provider) + return !p || (p.available && !!p.runs?.some((r) => r.workload === row.kind)) + } const cloudChoices = - row.section === "services" - ? cloudTargets.filter((t) => { - const p = catalog.find((c) => c.name === t.provider) - return ( - !p || (p.available && p.runs?.some((r) => r.workload === row.kind)) - ) - }) - : [] + row.section === "services" ? cloudTargets.filter(runsHere) : [] + const elsewhere = row.section === "services" ? otherClouds : [] + // Another Cloud's target is addressed by the Cloud's place in the list: + // a Cloud's name can hold any character. + const namedIndex = value.cloud + ? elsewhere.findIndex((c) => c.name === value.cloud) + : -1 const cloudValue = value.cloudTarget - ? `cloud:${value.cloudTarget}` + ? value.cloud + ? `cloud@${namedIndex}:${value.cloudTarget}` + : `cloud:${value.cloudTarget}` : value.cloudTags?.length ? "cloud-tags" : undefined const cloudLabelText = value.cloudTarget - ? cloudTargets.find((t) => t.name === value.cloudTarget)?.displayName || - value.cloudTarget - : `Tagged ${value.cloudTags?.join(", ")}` + ? value.cloud + ? `${value.cloudTarget} in ${value.cloud}` + : cloudTargets.find((t) => t.name === value.cloudTarget)?.displayName || + value.cloudTarget + : `Tagged ${value.cloudTags?.join(", ")}${value.cloud ? ` in ${value.cloud}` : ""}` const dirty = Object.keys(changes).length > 0 || !!account const disabled = !can("project:update") || placement.pending // A panel that saves at once holds back plans until it's saved or closed. @@ -501,17 +569,11 @@ function PlacementChoices({ onPendingChange?.(false) } } - const manageCloud = () => { - window.localStorage.setItem( - `loomplane.clouds.project.${session.orgId}`, - projectId - ) - if (environmentId) - window.localStorage.setItem( - `loomplane.clouds.environment.${session.orgId}.${projectId}`, - environmentId - ) - } + const projectClouds = { + to: "/projects/$id", + params: { id: projectId }, + search: { tab: "cloud" }, + } as const return (
v && - (v.startsWith("cloud:") + (v.startsWith("cloud:") || v.startsWith("cloud@") ? change({ - cloudTarget: v.slice("cloud:".length), + ...cloudPick(v, elsewhere), cloudTags: [], provider: "", region: "", @@ -558,7 +620,7 @@ function PlacementChoices({ change({ provider: v, ...(cloudChosen - ? { cloudTarget: "", cloudTags: [] } + ? { cloud: "", cloudTarget: "", cloudTags: [] } : {}), region: "", ...(value.cloudSqlNetwork @@ -578,7 +640,9 @@ function PlacementChoices({ aria-label={`Target for ${row.name}`} disabled={ disabled || - (targets.length === 0 && cloudChoices.length === 0) + (targets.length === 0 && + cloudChoices.length === 0 && + elsewhere.length === 0) } > @@ -600,7 +664,7 @@ function PlacementChoices({ ) : null} {cloudChoices.length > 0 && ( - Cloud targets + {cloudName ?? "Cloud targets"} {cloudChoices.map((t) => ( {t.displayName || t.name} @@ -608,6 +672,15 @@ function PlacementChoices({ ))} )} + {elsewhere.map((c, i) => ( + + ))} {targets.length > 0 && ( {cloudChoices.length > 0 && ( @@ -715,24 +788,23 @@ function PlacementChoices({ )} {row.section === "services" && cloudTargets.length === 0 && (

- No Cloud is assigned to {environment}, so no Cloud targets are - listed.{" "} + {cloudName + ? `${cloudName} has no targets this project may use yet.` + : "This project has no Cloud yet."}{" "} - Assign a Cloud + {cloudName ? "Add a target" : "Add a Cloud"}

)} {cloudChosen && ( - Manage Cloud target + Manage {cloudName ?? "Cloud"} targets )} {targets.length === 0 && cloudChoices.length === 0 && ( diff --git a/apps/dashboard/src/components/release-reports-card.tsx b/apps/dashboard/src/components/release-reports-card.tsx index 306e0176a..9147b7bfb 100644 --- a/apps/dashboard/src/components/release-reports-card.tsx +++ b/apps/dashboard/src/components/release-reports-card.tsx @@ -9,12 +9,7 @@ import { QueryError } from "@/components/query-error" import { StatusPill, type Tone } from "@/components/runs" import { Skeleton } from "@/components/ui/skeleton" import { useAgent, useFeatures } from "@/lib/features" -import { - stateLabel, - stateTone, - useReleaseReportEvents, - type StateTone, -} from "@/lib/release-reports" +import { stateLabel, stateTone, type StateTone } from "@/lib/release-reports" import { ago } from "@/lib/relative-time" import { Link } from "@/lib/router" import { useNow } from "@/lib/use-runs" @@ -36,7 +31,6 @@ export function ReleaseReportsCard({ projectId }: { projectId: string }) { } function Reports({ projectId }: { projectId: string }) { - useReleaseReportEvents() const now = useNow(30_000) const list = useQuery(useReleaseReportsList, { path: { id: projectId }, diff --git a/apps/dashboard/src/lib/agent-stream.ts b/apps/dashboard/src/lib/agent-stream.ts index 1ec2af40c..463bb82dc 100644 --- a/apps/dashboard/src/lib/agent-stream.ts +++ b/apps/dashboard/src/lib/agent-stream.ts @@ -5,8 +5,8 @@ // the history left off (useChat's resume). import type { ChatTransport } from "ai" -import { op_agentTasks_stream } from "@/client/forge/loomplane/ops/agentTasks.stream" import type { Sent } from "@/client/forge/loomplane/types" +import { agentTaskStream } from "@/client/streams" import { type AgentChunk, type AgentEvent, @@ -230,10 +230,7 @@ export class AgentChatTransport implements ChatTransport { return } - const path = op_agentTasks_stream.path.replace( - "{id}", - encodeURIComponent(turn.taskId) - ) + const path = agentTaskStream(turn.taskId) const url = new URL(path, window.location.origin) url.searchParams.set("after", String(last)) source = new EventSource(url, { withCredentials: true }) diff --git a/apps/dashboard/src/lib/cloud-tags.test.ts b/apps/dashboard/src/lib/cloud-tags.test.ts index 0dac3ec2e..6c57d2bab 100644 --- a/apps/dashboard/src/lib/cloud-tags.test.ts +++ b/apps/dashboard/src/lib/cloud-tags.test.ts @@ -87,16 +87,27 @@ it("selects one environment's target by tags and pins the others", () => { }, }, } - const next = adoptServiceTarget(m, environments, "production", "web", { - tags: ["eu", "web"], - }) + const next = adoptServiceTarget( + m, + "web", + { + tags: ["eu", "web"], + }, + { + environment: "production", + environments: environments, + } + ) const web = next.services!.web expect(web.cloud_target).toBeUndefined() expect(web.environments.production).toEqual({ cloud_tags: ["eu", "web"] }) expect(web.environments.staging).toEqual({ cloud_tags: ["preview"] }) // Switching back to a name drops the tags in that environment only. - const named = adoptServiceTarget(next, environments, "staging", "web", "edge") + const named = adoptServiceTarget(next, "web", "edge", { + environment: "staging", + environments: environments, + }) expect(named.services!.web.environments.staging).toEqual({ cloud_target: "edge", }) diff --git a/apps/dashboard/src/lib/cloud-targets.test.ts b/apps/dashboard/src/lib/cloud-targets.test.ts index 688400326..2a9b4259c 100644 --- a/apps/dashboard/src/lib/cloud-targets.test.ts +++ b/apps/dashboard/src/lib/cloud-targets.test.ts @@ -24,13 +24,10 @@ it("adopts one environment while retaining effective defaults, unrelated entries { id: "p", name: "production" }, { id: "s", name: "staging" }, ] as Environment[] - const result = adoptServiceTarget( - original, - environments, - "production", - "web", - "frontend" - ) + const result = adoptServiceTarget(original, "web", "frontend", { + environment: "production", + environments: environments, + }) const settings = (m: Manifest, env: string) => placementSettings( m, @@ -68,13 +65,10 @@ it("preserves placement in saved overrides before an environment is registered", web: { source: "web", environments: { future: { port: 9000 } } }, }, } - const result = adoptServiceTarget( - manifest, - [{ name: "production" }] as Environment[], - "production", - "web", - "frontend" - ) + const result = adoptServiceTarget(manifest, "web", "frontend", { + environment: "production", + environments: [{ name: "production" }] as Environment[], + }) expect( placementSettings( result, @@ -107,13 +101,14 @@ it("retains inherited endpoints when another environment adopts a target", () => }, }, } - const result = adoptServiceTarget( - manifest, - [{ name: "production" }, { name: "staging" }] as Environment[], - "production", - "web", - "frontend" - ) + const result = adoptServiceTarget(manifest, "web", "frontend", { + environment: "production", + environments: [ + { name: "production" }, + { name: "staging" }, + ] as Environment[], + }) + expect(result.services!.web.environments.staging.endpoint).toEqual({ hostname: "staging.example", host_port: 8080, @@ -144,3 +139,136 @@ it("retains inherited endpoints when another environment adopts a target", () => ).endpoint ) }) + +it("puts a service on a target in every environment, clearing environment placement", () => { + const original: Manifest = { + version: 1, + defaults: { provider: "vercel", region: "iad1" }, + services: { + web: { + source: "apps/web", + target: "conn_a", + environments: { + staging: { provider: "cloud-run", region: "us-central1", port: 8080 }, + preview: { cloud_tags: ["small"] }, + }, + }, + api: { source: "cmd/api" }, + }, + } + const result = adoptServiceTarget(original, "web", "frontend") + const settings = (env: string) => + placementSettings( + result, + { + section: "services", + name: "web", + kind: "", + entry: result.services!.web, + }, + env + ) + for (const env of ["production", "staging", "preview"]) + expect(settings(env)).toMatchObject({ + provider: "", + cloudTarget: "frontend", + }) + // What an environment set besides placement stays. + expect(result.services!.web.environments).toEqual({ + staging: { region: "us-central1", port: 8080 }, + }) + // Other entries keep the default they inherited. + expect(result.services!.api).toMatchObject({ + provider: "vercel", + region: "iad1", + }) + expect(original.services!.web.target).toBe("conn_a") +}) + +it("selects a target by tags in every environment", () => { + const result = adoptServiceTarget( + { + version: 1, + services: { + web: { + source: "web", + cloud_target: "old", + environments: { staging: { cloud_target: "edge" } }, + }, + }, + }, + "web", + { tags: ["eu", "web"] } + ) + expect(result.services!.web).toEqual({ + source: "web", + cloud_tags: ["eu", "web"], + }) +}) + +it("reads a service's Cloud the way the planner does", () => { + const m: Manifest = { + version: 1, + services: { + trainer: { + source: "trainer", + cloud: "GPU Lab", + cloud_target: "a100", + environments: { + preview: { cloud_target: "eu-run" }, + staging: { cloud: "GPU Lab EU" }, + }, + }, + }, + } + const settings = (env: string) => + placementSettings( + m, + { + section: "services", + name: "trainer", + kind: "", + entry: m.services!.trainer, + }, + env + ) + expect(settings("production")).toMatchObject({ + cloud: "GPU Lab", + cloudTarget: "a100", + }) + // A target named without a Cloud is in the default Cloud. + expect(settings("preview").cloud).toBeUndefined() + expect(settings("preview").cloudTarget).toBe("eu-run") + expect(settings("staging")).toMatchObject({ + cloud: "GPU Lab EU", + cloudTarget: "a100", + }) +}) + +it("puts a service on another Cloud's target, everywhere or in one environment", () => { + const m: Manifest = { + version: 1, + services: { trainer: { source: "trainer", cloud_target: "eu-run" } }, + } + expect( + adoptServiceTarget(m, "trainer", "a100", undefined, "GPU Lab").services! + .trainer + ).toEqual({ source: "trainer", cloud: "GPU Lab", cloud_target: "a100" }) + const environments = [ + { name: "production" }, + { name: "preview" }, + ] as Environment[] + const one = adoptServiceTarget( + m, + "trainer", + "a100", + { environment: "production", environments }, + "GPU Lab" + ).services!.trainer + expect(one.environments.production).toEqual({ + cloud: "GPU Lab", + cloud_target: "a100", + }) + // The other environment keeps the default Cloud's target. + expect(one.environments.preview).toEqual({ cloud_target: "eu-run" }) +}) diff --git a/apps/dashboard/src/lib/cloud-targets.ts b/apps/dashboard/src/lib/cloud-targets.ts index 54f052f0c..550f6842a 100644 --- a/apps/dashboard/src/lib/cloud-targets.ts +++ b/apps/dashboard/src/lib/cloud-targets.ts @@ -43,19 +43,72 @@ export function matchCloudTags(targets: Target[], tags: string[]): TagMatch { return { kind: "many", targets: found } } -/** Adopt only the selected environment and preserve effective placement elsewhere. */ +/** + * adoptServiceTarget puts a service on a Cloud target, or on the one its + * tags select, through the project's default Cloud. + * + * Without `only`, it does so in every environment: the service's direct + * placement goes, and so does any placement an environment set for it, so + * every environment resolves the same way. + * + * With `only`, just that environment moves. A service's base placement can't + * be unset by an override, so every other environment's effective placement + * is written into its own override first and the base is cleared. + */ export function adoptServiceTarget( manifest: Manifest, - environments: Environment[], - environment: string, service: string, - choice: CloudChoice + choice: CloudChoice, + only?: { environment: string; environments: Environment[] }, + /** cloud names a Cloud other than the project's default. */ + cloud?: string ): Manifest { + if (only) + return adoptInEnvironment( + manifest, + only.environments, + only.environment, + service, + choice, + cloud + ) const next = structuredClone(manifest) - if (!next.services?.[service]) + const entry = next.services?.[service] + if (!entry) throw new Error("This service no longer exists. Refresh the manifest.") - // A default provider would also apply to a named target. Materialize it before - // removing that inheritance, including resources and gateways. + // A default provider would also apply to a named target. Give every other + // entry its own before the default goes. + materializeDefaults(manifest, next) + for (const key of placementKeys) delete entry[key] + if (cloud) entry.cloud = cloud + if (typeof choice === "string") entry.cloud_target = choice + else entry.cloud_tags = [...choice.tags] + for (const [name, override] of Object.entries(entry.environments ?? {})) { + const rest: Record = { + ...(override as Record), + } + for (const key of placementKeys) delete rest[key] + if (Object.keys(rest).length) entry.environments![name] = rest + else delete entry.environments![name] + } + if (entry.environments && !Object.keys(entry.environments).length) + delete entry.environments + return next +} + +// placementKeys are the fields that say where a service runs, in both the +// wire and the client spelling a manifest may carry. +const placementKeys = [ + "cloud", + "provider", + "target", + "cloud_target", + "cloudTarget", + "cloud_tags", + "cloudTags", +] as const + +function materializeDefaults(manifest: Manifest, next: Manifest) { for (const section of ["services", "resources", "gateways"] as const) { for (const [name, entry] of Object.entries(next[section] ?? {})) { const effective = placementSettings( @@ -72,6 +125,20 @@ export function adoptServiceTarget( delete next.defaults.provider delete next.defaults.region } +} + +function adoptInEnvironment( + manifest: Manifest, + environments: Environment[], + environment: string, + service: string, + choice: CloudChoice, + cloud?: string +): Manifest { + const next = structuredClone(manifest) + if (!next.services?.[service]) + throw new Error("This service no longer exists. Refresh the manifest.") + materializeDefaults(manifest, next) const entry = next.services![service] const previous = manifest.services![service] entry.environments = { ...entry.environments } @@ -91,6 +158,9 @@ export function adoptServiceTarget( delete override.target delete override.cloudTarget delete override.cloudTags + // An environment's target is in the Cloud it names, or the default. + if (cloud) override.cloud = cloud + else delete override.cloud if (typeof choice === "string") { override.cloud_target = choice delete override.cloud_tags @@ -123,6 +193,7 @@ export function adoptServiceTarget( } if (settings.cloudTarget) override.cloud_target = settings.cloudTarget if (settings.cloudTags) override.cloud_tags = settings.cloudTags + if (settings.cloud) override.cloud = settings.cloud } // An environment with nothing to pin needs no override of its own. if (Object.keys(override).length || previous.environments?.[name]) @@ -130,6 +201,7 @@ export function adoptServiceTarget( } delete entry.provider delete entry.target + delete entry.cloud delete entry.cloud_target delete entry.cloudTarget delete entry.cloud_tags @@ -142,7 +214,7 @@ export function cloudDeletionError( kind: "Cloud" | "target" ): string { return statusOf(error) === 409 - ? `This ${kind} is protected while environments, deployments, syncs or recent previews reference it. Preview references expire after 24 hours.` + ? `This ${kind} is protected while projects, deployments, syncs or recent previews use it. Preview references expire after 24 hours.` : messageOf( error, `The ${kind} couldn't be deleted. Remove its references first.` diff --git a/apps/dashboard/src/lib/placement.ts b/apps/dashboard/src/lib/placement.ts index bad71204f..707efe560 100644 --- a/apps/dashboard/src/lib/placement.ts +++ b/apps/dashboard/src/lib/placement.ts @@ -12,6 +12,8 @@ import type { } from "@/client/forge/loomplane/types" export type PlacementFields = { + /** cloud names the Cloud cloudTarget or cloudTags resolve in; none is the default. */ + cloud?: string cloudSqlNetwork?: CloudSQLApplicationNetwork cloud_sql_network?: CloudSQLApplicationNetwork & { consumer_project?: string } cloudTarget?: string @@ -285,11 +287,17 @@ export function placementSettings( const overrideTags = o ? tagsOf(o) : [] if (overrideTarget) [cloudTarget, cloudTags] = [overrideTarget, []] if (overrideTags.length) [cloudTarget, cloudTags] = ["", overrideTags] + // An environment that names a target also says which Cloud: none is the + // project's default, as the planner reads it. + let cloud = s.cloud ?? "" + if (overrideTarget || overrideTags.length) cloud = o?.cloud ?? "" + else if (o?.cloud) cloud = o.cloud const defaultTags = d?.cloudTags ?? (d as { cloud_tags?: string[] })?.cloud_tags if (!cloudTarget && !cloudTags.length && !provider && !target) cloudTags = [...(defaultTags ?? [])] return { + ...(cloud ? { cloud } : {}), ...(cloudTarget ? { cloudTarget } : {}), ...(cloudTags.length ? { cloudTags } : {}), provider, @@ -369,6 +377,7 @@ export function cloudChoice( // Fields a Cloud target choice replaces: adoption rewrites them itself. export const cloudOwnedFields = [ + "cloud", "cloudTarget", "cloudTags", "provider", @@ -474,6 +483,13 @@ export function runsOn( ): RunsOn { const provider = (name: string) => catalog.find((p) => p.name === name) if (!value.enabled) return { name: `Off in ${environment}`, where: "" } + // cloudTargets are the default Cloud's; another Cloud's target is named, + // not looked up there. + if (value.cloud && (value.cloudTarget || value.cloudTags?.length)) + return { + name: value.cloudTarget || `Target tagged ${value.cloudTags!.join(", ")}`, + where: value.cloud, + } if (value.cloudTarget) { const t = cloudTargets.find((x) => x.name === value.cloudTarget) const p = t ? provider(t.provider) : undefined diff --git a/apps/dashboard/src/lib/realtime.test.ts b/apps/dashboard/src/lib/realtime.test.ts index e922b60d2..0f9dc75f2 100644 --- a/apps/dashboard/src/lib/realtime.test.ts +++ b/apps/dashboard/src/lib/realtime.test.ts @@ -8,6 +8,7 @@ import { useProjectsList, useProjectsGraph, useDeploymentsForPlan, + useReleaseReportsList, } from "@/client/forge/loomplane/hooks" import { LoomplaneRealtime } from "@/lib/realtime" @@ -104,10 +105,16 @@ it("refreshes the graph projection when analysis completes", async () => { live.stop() }) -it("tells the release report listeners when a report changes", () => { +it("refetches the release report list when a report changes", async () => { + let reads = 0 const cache = new QueryCache({ entities, - transport: { execute: async () => ({}) }, + transport: { + execute: async () => { + reads++ + return { reports: [] } + }, + }, }) const connection = new Connection() const live = new LoomplaneRealtime({ @@ -116,40 +123,24 @@ it("tells the release report listeners when a report changes", () => { connect: () => connection, }) live.start() - const changed = vi.fn() - const stop = live.onReleaseReport(changed) - const report = { - id: "rrep_1", - org_id: "org_one", - project_id: "proj_one", - state: "reviewing", - } + const list = useReleaseReportsList( + { path: { id: "proj_one" } }, + { client: cache } + ) + await list.fetch() + const release = list.subscribe(() => {}) connection.message({ event: "release_report.updated", cursor: "org_one:1", - data: report, - }) - expect(changed).toHaveBeenCalledTimes(1) - // Another workspace's event never reaches the page. - connection.message({ - event: "release_report.updated", - cursor: "org_one:2", - data: { ...report, org_id: "org_two" }, - }) - expect(changed).toHaveBeenCalledTimes(1) - connection.message({ - event: "release_report.deleted", - cursor: "org_one:3", - data: report, - }) - expect(changed).toHaveBeenCalledTimes(2) - stop() - connection.message({ - event: "release_report.updated", - cursor: "org_one:4", - data: report, + data: { + id: "rrep_1", + org_id: "org_one", + project_id: "proj_one", + state: "reviewing", + }, }) - expect(changed).toHaveBeenCalledTimes(2) + await vi.waitFor(() => expect(reads).toBe(2)) + release() live.stop() }) diff --git a/apps/dashboard/src/lib/realtime.ts b/apps/dashboard/src/lib/realtime.ts index 90d4799fd..bbbaa9b7f 100644 --- a/apps/dashboard/src/lib/realtime.ts +++ b/apps/dashboard/src/lib/realtime.ts @@ -15,12 +15,11 @@ import { useInfrastructureGet as infrastructureQuery, } from "@/client/forge/loomplane/hooks" import { op_deployments_forPlan } from "@/client/forge/loomplane/ops/deployments.forPlan" -import { op_realtime_events } from "@/client/forge/loomplane/ops/realtime.events" -import { op_realtime_ws } from "@/client/forge/loomplane/ops/realtime.ws" import { streams } from "@/client/forge/loomplane/stream-bindings" import type { Collection, Log, Snapshot } from "@/client/forge/loomplane/types" import { RealtimeWsReceiveWSClient } from "@/client/forge/loomplane/websocket" import { statusOf } from "@/client/errors" +import { REALTIME_EVENTS, REALTIME_WS } from "@/client/streams" import type { LiveState } from "@/lib/realtime-state" type Scope = { orgId: string; deploymentIds: string[]; cursor: string } @@ -30,7 +29,7 @@ type Options = { orgId: string connect?: (mode: "ws" | "sse", scope: Scope) => StreamConnection } -const channel = op_realtime_ws.path +const channel = REALTIME_WS const bindings: readonly StreamBinding[] = streams.filter( (b) => b.channel === channel ) @@ -61,7 +60,7 @@ function connectNative(mode: "ws" | "sse", scope: Scope): StreamConnection { close: () => client.close(true), } } - const url = new URL(op_realtime_events.path, window.location.origin) + const url = new URL(REALTIME_EVENTS, window.location.origin) url.searchParams.set("org_id", scope.orgId) if (scope.deploymentIds.length) url.searchParams.set("deployment_ids", scope.deploymentIds.join(",")) @@ -83,7 +82,7 @@ function connectNative(mode: "ws" | "sse", scope: Scope): StreamConnection { }, { events: [ - ...channelMessages(streams, op_realtime_events.path), + ...channelMessages(streams, REALTIME_EVENTS), "realtime.snapshot", "realtime.status", ], @@ -109,7 +108,6 @@ export class LoomplaneRealtime { } private listeners = new Set<() => void>() private frames = new Set<(event: string, data: Log | Collection) => void>() - private reportListeners = new Set<() => void>() private stopped = true private generation = 0 private syncingGeneration = -1 @@ -124,23 +122,6 @@ export class LoomplaneRealtime { this.frames.add(fn) return () => this.frames.delete(fn) } - /** - * onReleaseReport calls fn when a release report changes or goes. The - * report list reads through a query that tags nothing, so the entity - * binding can't refresh it; the page refetches on this instead. A - * snapshot after a reconnect calls it too, for what was missed. - */ - onReleaseReport = (fn: () => void) => { - this.reportListeners.add(fn) - return () => this.reportListeners.delete(fn) - } - private reportChanged(event: string | undefined) { - if ( - event === "release_report.updated" || - event === "release_report.deleted" - ) - this.reportListeners.forEach((fn) => fn()) - } private update(patch: Partial) { this.snapshot = { ...this.snapshot, ...patch } this.listeners.forEach((fn) => fn()) @@ -325,7 +306,6 @@ export class LoomplaneRealtime { return if (cursor) this.cursor = cursor this.output(frame.event ?? "", frame.data) - this.reportChanged(frame.event) this.refreshDeploymentLookup(frame.event, frame.data) if ( frame.event === "analysis.updated" || @@ -369,7 +349,6 @@ export class LoomplaneRealtime { if (record.orgId !== this.options.orgId) continue this.refreshDeploymentLookup(record.event, record.data) this.output(record.event, record.data) - this.reportChanged(record.event) const frame = { event: record.event, data: record.data, channel } if (deliver) deliver(frame) else { diff --git a/apps/dashboard/src/lib/release-reports.ts b/apps/dashboard/src/lib/release-reports.ts index c475be210..5fb3e94ea 100644 --- a/apps/dashboard/src/lib/release-reports.ts +++ b/apps/dashboard/src/lib/release-reports.ts @@ -1,15 +1,7 @@ // What a release readiness report says, in words people read. The gates and // their details come from the server as they are: Loomplane computes them, // so the page shows them and adds nothing of its own. -import { useEffect } from "react" - -import { - useReleaseReportsGet, - useReleaseReportsList, -} from "@/client/forge/loomplane/hooks" import type { ReleaseReport } from "@/client/forge/loomplane/types" -import { useInvalidate } from "@/client/hooks" -import { useRealtime } from "@/lib/realtime-provider" /** The seven gates, with the same words as GateNames in internal/releaseprep. */ export const gateNames: Record = { @@ -95,23 +87,3 @@ export function mayCancelReport( (r.requestedBy === who.userId && who.can("agent:use")) ) } - -/** - * useReleaseReportEvents refetches the release report list and the open - * report when the server says a report changed. The list read tags nothing, - * so the realtime entity binding can't reach it. - */ -export function useReleaseReportEvents(): void { - const realtime = useRealtime() - const invalidate = useInvalidate() - useEffect(() => { - if (!realtime) return - const stop = realtime.onReleaseReport(() => { - invalidate(useReleaseReportsList) - invalidate(useReleaseReportsGet) - }) - return () => { - stop() - } - }, [realtime, invalidate]) -} diff --git a/apps/dashboard/src/pages/cloud-detail.test.tsx b/apps/dashboard/src/pages/cloud-detail.test.tsx index be1e991d6..3c660cba0 100644 --- a/apps/dashboard/src/pages/cloud-detail.test.tsx +++ b/apps/dashboard/src/pages/cloud-detail.test.tsx @@ -86,7 +86,7 @@ const usage = { project_name: "Web app", environment_id: "prod", environment_name: "production", - assigned: true, + default: true, placements: [ { target_id: "frontend", services: ["site", "docs"] }, { target_id: "api", services: ["api"] }, @@ -350,7 +350,7 @@ it("shows where services go and how many run on each target", async () => { expect(reads).toContain("/api/v1/clouds/syncs?cloud=c&limit=30") }) -it("sends environment changes to the environment's own project", async () => { +it("sends Cloud changes to the environment's own project", async () => { fixture({ granted: true }) show() const envs = await screen.findByRole("region", { @@ -359,7 +359,7 @@ it("sends environment changes to the environment's own project", async () => { await waitFor(() => expect(envs).toHaveTextContent("production")) expect( within(envs).getByRole("link", { name: "Open in project" }) - ).toHaveAttribute("href", "/projects/web?tab=cloud&environment=production") + ).toHaveAttribute("href", "/projects/web?tab=cloud") expect( screen.queryByRole("button", { name: "Use in an environment" }) ).not.toBeInTheDocument() diff --git a/apps/dashboard/src/pages/cloud-detail.tsx b/apps/dashboard/src/pages/cloud-detail.tsx index af02ad859..d5b78c570 100644 --- a/apps/dashboard/src/pages/cloud-detail.tsx +++ b/apps/dashboard/src/pages/cloud-detail.tsx @@ -432,7 +432,7 @@ function CloudPage({ } const viewing = projectList.find((p) => p.id === project) const creator = projectList.find((p) => p.id === cloud.projectId) - const environments = usage.data?.environments.filter((e) => e.assigned).length + const environments = usage.data?.environments.filter((e) => e.default).length const state = headState(syncs.list, environments) const owner = !cloud.projectId ? "Workspace" : (creator?.name ?? "A project") diff --git a/apps/dashboard/src/pages/clouds.test.tsx b/apps/dashboard/src/pages/clouds.test.tsx index ac20f5366..9045b1979 100644 --- a/apps/dashboard/src/pages/clouds.test.tsx +++ b/apps/dashboard/src/pages/clouds.test.tsx @@ -138,7 +138,22 @@ function fixture( ], } if (path.endsWith("/clouds")) body = { clouds: profiles } - if (path.endsWith("/cloud")) body = { assignment: null, revision: 0 } + if (path.endsWith("/default-cloud")) + body = profiles.length + ? { + project_id: "p", + revision: 1, + cloud: { + cloud_id: profiles[0].id, + org_id: "org", + project_id: "p", + cloud_revision: 1, + grant_revision: 1, + default: true, + targets: [target], + }, + } + : { project_id: "p", cloud: null, revision: 0 } if (path.endsWith("/targets")) body = { targets: options.spread @@ -222,9 +237,9 @@ it("shows a Cloud spread over several accounts of one provider", async () => { expect(screen.getByText("2 accounts")).toBeInTheDocument() expect(screen.getByText("ams3")).toBeInTheDocument() }) -it("distinguishes filtered targets, clears the filter and discards old environment scope", async () => { +it("filters targets and clears the filter", async () => { const user = userEvent.setup() - const { reads } = fixture() + fixture() show() await screen.findByText("Frontend") await user.type( @@ -234,16 +249,6 @@ it("distinguishes filtered targets, clears the filter and discards old environme expect(screen.getByText("No matching targets")).toBeInTheDocument() await user.click(screen.getByRole("button", { name: "Clear filter" })) expect(screen.getByText("Frontend")).toBeInTheDocument() - await user.click(screen.getByRole("combobox", { name: "Environment" })) - await user.click(await screen.findByRole("option", { name: /staging/ })) - await waitFor(() => - expect(reads.some((r) => r.includes("/environments/stage/cloud"))).toBe( - true - ) - ) - expect(screen.getByRole("textbox", { name: "Filter targets" })).toHaveValue( - "" - ) }) it("asks for no project, since the tab is already in one", async () => { fixture() @@ -253,47 +258,49 @@ it("asks for no project, since the tab is already in one", async () => { screen.queryByRole("combobox", { name: "Project" }) ).not.toBeInTheDocument() }) -it("opens on the environment a link names, then follows a pick", async () => { +it("puts the default Cloud first, open, and reviews making another the default", async () => { const user = userEvent.setup() - const { reads } = fixture() - show() - await waitFor(() => - expect( - screen.getByRole("combobox", { name: "Environment" }) - ).toHaveTextContent("staging") - ) - expect(reads.some((r) => r.includes("/environments/stage/cloud"))).toBe(true) - await user.click(screen.getByRole("combobox", { name: "Environment" })) - await user.click(await screen.findByRole("option", { name: /production/ })) + const { writes, reads } = fixture({ + profiles: [{ ...profile, id: "lab", name: "GPU Lab" }, profile].reverse(), + }) + show() + await screen.findByText("Frontend") + // No environment to pick: every environment uses the default Cloud. + expect( + screen.queryByRole("combobox", { name: "Environment" }) + ).not.toBeInTheDocument() + expect(reads.some((r) => r.includes("/environments/"))).toBe(false) + const cards = screen.getAllByRole("button", { expanded: true }) + expect(cards).toHaveLength(1) + expect(cards[0]).toHaveTextContent("Production") + expect(cards[0]).toHaveTextContent("Default") + await user.click(screen.getByRole("button", { name: "Make default" })) + await screen.findByRole("heading", { name: "Change the default Cloud" }) await waitFor(() => expect( - screen.getByRole("combobox", { name: "Environment" }) - ).toHaveTextContent("production") + writes.find((w) => w.url.endsWith("/default-cloud/preview"))?.body + ).toEqual({ cloud_id: "lab", revision: 1 }) ) }) it("creates a Cloud and refreshes the generated list", async () => { const user = userEvent.setup() const { writes } = fixture({ noClouds: true }) show() - await screen.findByText("Create your first Cloud") + await screen.findByText("No Clouds yet") await user.click(screen.getAllByRole("button", { name: "New Cloud" })[0]) await user.type( screen.getByRole("textbox", { name: "Cloud name" }), "Customer Cloud" ) await user.click(screen.getByRole("button", { name: "Save Cloud" })) - await waitFor(() => - expect(screen.getByRole("combobox", { name: "Cloud" })).toHaveTextContent( - "Customer Cloud" - ) - ) + expect(await screen.findByText("Customer Cloud")).toBeInTheDocument() expect(writes[0].body).toEqual({ name: "Customer Cloud" }) }) it("shows read errors without presenting an empty Cloud result", async () => { fixture({ failure: "list" }) show() await screen.findByText("Cloud read failed.") - expect(screen.queryByText("Create your first Cloud")).not.toBeInTheDocument() + expect(screen.queryByText("No Clouds yet")).not.toBeInTheDocument() }) it("blocks a stale preview until refreshed", async () => { const user = userEvent.setup() @@ -453,29 +460,15 @@ it("saves an adopted service through the optimistic generated manifest API", asy ) const { ServiceAdoption } = await import("@/components/cloud-targets/service-adoption") - const environments = [ - { id: "prod", name: "production" }, - { id: "stage", name: "staging" }, - ] as import("@/client/forge/loomplane/types").Environment[] const targets = [ { id: "target", name: "frontend", displayName: "Frontend" }, ] as import("@/client/forge/loomplane/types").Target[] - show( - undefined} - /> - ) + show() await user.click( await screen.findByRole("combobox", { name: "Cloud target for web" }) ) await user.click(await screen.findByRole("option", { name: /Frontend/ })) - await user.click( - screen.getAllByRole("button", { name: "Review service edit" })[0] - ) + await user.click(screen.getAllByRole("button", { name: "Review" })[0]) expect(screen.getByLabelText("Manifest adoption preview")).toHaveTextContent( '"cloud_target": "frontend"' ) @@ -485,12 +478,7 @@ it("saves an adopted service through the optimistic generated manifest API", asy base_revision: 3, manifest: { services: { - web: { - environments: { - production: { cloud_target: "frontend" }, - staging: { provider: "vercel", region: "iad1" }, - }, - }, + web: { cloud_target: "frontend" }, api: { provider: "vercel" }, }, resources: { db: { provider: "vercel" } }, @@ -520,22 +508,11 @@ it("selects a service's target by tags and previews where they land", async () = ) const { ServiceAdoption } = await import("@/components/cloud-targets/service-adoption") - const environments = [ - { id: "prod", name: "production" }, - ] as import("@/client/forge/loomplane/types").Environment[] const targets = [ { id: "a", name: "frontend", displayName: "Frontend", tags: ["eu", "web"] }, { id: "b", name: "edge", displayName: "Edge", tags: ["us", "web"] }, ] as import("@/client/forge/loomplane/types").Target[] - show( - undefined} - /> - ) + show() await user.click( await screen.findByRole("combobox", { name: "Select web's target by" }) ) @@ -545,7 +522,7 @@ it("selects a service's target by tags and previews where they land", async () = expect(screen.getByText(/Frontend, Edge all carry these tags/)).toBeVisible() await user.type(input, "eu{Enter}") expect(screen.getByText(/Runs on/)).toHaveTextContent("Runs on Frontend.") - await user.click(screen.getByRole("button", { name: "Review service edit" })) + await user.click(screen.getByRole("button", { name: "Review" })) expect( screen.getByRole("heading", { name: "Select web's target by eu, web" }) ).toBeVisible() @@ -555,7 +532,7 @@ it("selects a service's target by tags and previews where they land", async () = base_revision: 3, manifest: { services: { - web: { environments: { production: { cloud_tags: ["eu", "web"] } } }, + web: { cloud_tags: ["eu", "web"] }, }, }, }) @@ -621,18 +598,11 @@ it("requires routing evidence and sends it for the selected environment", async ) }) -it.each([ - ["empty", "No environments yet"], - ["environments", "Environment read failed."], - ["list", "Cloud read failed."], -])("says so when the environment scope is %s", async (state, message) => { - fixture({ - noEnvironments: state === "empty", - failure: state === "empty" ? undefined : state, - }) +it("says so when the Clouds can't be read", async () => { + fixture({ failure: "list" }) show() - await screen.findByText(message) - expect(screen.queryByText("Create your first Cloud")).not.toBeInTheDocument() + await screen.findByText("Cloud read failed.") + expect(screen.queryByText("No Clouds yet")).not.toBeInTheDocument() }) it("keeps blocked previews distinct from environments without deployed services", async () => { @@ -652,8 +622,8 @@ it("keeps blocked previews distinct from environments without deployed services" show( undefined} onApplied={() => undefined} /> @@ -669,8 +639,8 @@ it("keeps blocked previews distinct from environments without deployed services" }) it.each([false, true])( - "shows revision-bound Cloud assignment account changes, removal=%s", - async (remove) => { + "shows what each target name points at either side of a default change, clearing=%s", + async (clear) => { vi.stubGlobal("fetch", async (input: RequestInfo | URL) => { const url = String(input) if (url.endsWith("/connections")) @@ -691,18 +661,26 @@ it.each([false, true])( ...preview, before: undefined, after: undefined, - input: { cloud_id: remove ? "" : "new", revision: 1 }, - before_assignment: { + input: { + cloud_id: clear ? "" : "new", + project_default: true, + revision: 1, + }, + before_cloud: { cloud_id: "old", cloud_revision: 2, + grant_revision: 1, + default: true, targets: [{ ...target, connection_id: "a" }], }, - ...(remove + ...(clear ? {} : { - after_assignment: { + after_cloud: { cloud_id: "new", cloud_revision: 3, + grant_revision: 1, + default: true, targets: [ { ...target, connection_id: "b", provider: "cloud-run" }, ], @@ -713,46 +691,37 @@ it.each([false, true])( show( undefined} onApplied={() => undefined} /> ) - await screen.findByText("Current Cloud: Old Cloud (revision 2)") - expect( - screen.getByText("Current: vercel / Old account") - ).toBeInTheDocument() - expect( - screen.getByText( - remove - ? "Desired Cloud: Direct placement" - : "Desired Cloud: New Cloud (revision 3)" - ) - ).toBeInTheDocument() - expect( - screen.getByText( - remove - ? "Desired: Target removed from this environment" - : "Desired: cloud-run / New account" + const change = await screen.findByRole("region", { + name: "Default Cloud change", + }) + await waitFor(() => + expect(change).toHaveTextContent( + `Every environment moves from Old Cloud to ${clear ? "no default Cloud" : "New Cloud"}.` ) - ).toBeInTheDocument() + ) + expect(change).toHaveTextContent( + clear + ? "vercel / Old account → Not in the new Cloud: services that name it stop planning" + : "vercel / Old account → cloud-run / New account" + ) } ) -it("explains retained preview protection when deleting an unassigned Cloud", async () => { +it("explains retained preview protection when deleting a Cloud", async () => { const user = userEvent.setup() const { writes } = fixture({ failure: "delete" }) show() - await user.click(await screen.findByRole("button", { name: "Manage Cloud" })) + await user.click(await screen.findByRole("button", { name: "Manage" })) await user.click(screen.getByRole("button", { name: "Delete Cloud" })) await user.click(screen.getByRole("button", { name: "Confirm delete Cloud" })) await screen.findByText( - "This Cloud is protected while environments, deployments, syncs or recent previews reference it. Preview references expire after 24 hours." + "This Cloud is protected while projects, deployments, syncs or recent previews use it. Preview references expire after 24 hours." ) expect(writes[0].url).toBe("/api/v1/projects/p/clouds/cloud") expect(screen.getByRole("textbox", { name: "Cloud name" })).toHaveValue( @@ -786,3 +755,45 @@ it("lists Loomplane Cloud in the normal order", async () => { /recommended|default|suggested|featured/i ) }) + +it("puts a service on a target of a Cloud other than the default", async () => { + const user = userEvent.setup() + const writes: Record[] = [] + vi.stubGlobal( + "fetch", + async (_input: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === "PUT") { + writes.push(JSON.parse(String(init.body))) + return Response.json({ id: "next", revision: 4, manifest: {} }) + } + return Response.json({ + id: "saved", + revision: 3, + manifest: { + version: 1, + services: { trainer: { source: "trainer", cloud_target: "eu-run" } }, + }, + }) + } + ) + const { ServiceAdoption } = + await import("@/components/cloud-targets/service-adoption") + const targets = [ + { id: "a", name: "a100", displayName: "A100" }, + ] as import("@/client/forge/loomplane/types").Target[] + show() + await user.click( + await screen.findByRole("combobox", { name: "Cloud target for trainer" }) + ) + await user.click(await screen.findByRole("option", { name: /A100/ })) + await user.click(screen.getByRole("button", { name: "Review" })) + await user.click(screen.getByRole("button", { name: "Save service target" })) + await waitFor(() => expect(writes).toHaveLength(1)) + expect(writes[0]).toMatchObject({ + manifest: { + services: { + trainer: { source: "trainer", cloud: "GPU Lab", cloud_target: "a100" }, + }, + }, + }) +}) diff --git a/apps/dashboard/src/pages/clouds.tsx b/apps/dashboard/src/pages/clouds.tsx index 67e6609d1..f411afa70 100644 --- a/apps/dashboard/src/pages/clouds.tsx +++ b/apps/dashboard/src/pages/clouds.tsx @@ -714,21 +714,14 @@ function NewCloudDialog({ } /** - * CloudsWorkspace is a project's Cloud tab: pick one of its environments and - * a Cloud, edit targets, review assignments and syncs. Environments belong to - * a project, so this is the one place an environment takes a Cloud. + * CloudsWorkspace is a project's Clouds tab: the Clouds granted to it, its + * default Cloud, targets, where each service runs, and syncs. None of it is + * per environment. */ -export function CloudsWorkspace({ - projectId, - environment, -}: { - projectId: string - /** The environment to open on by name, from ?environment=. */ - environment?: string -}) { +export function CloudsWorkspace({ projectId }: { projectId: string }) { const { can } = useOrganization() return can("cloud_account:read") ? ( - + ) : ( - + )} diff --git a/apps/dashboard/src/pages/release-report.tsx b/apps/dashboard/src/pages/release-report.tsx index 16d56608c..29a390c38 100644 --- a/apps/dashboard/src/pages/release-report.tsx +++ b/apps/dashboard/src/pages/release-report.tsx @@ -54,7 +54,6 @@ import { mayCancelReport, stateLabel, stateTone, - useReleaseReportEvents, type StateTone, } from "@/lib/release-reports" import { ago } from "@/lib/relative-time" @@ -102,7 +101,6 @@ function AgentOff() { } function Loaded({ id }: { id: string }) { - useReleaseReportEvents() const report = useQuery(useReleaseReportsGet, { path: { id } }) // Without a live connection the report still catches up while it's active. useRefetchWhile( diff --git a/apps/docs/content/docs/ai/models.mdx b/apps/docs/content/docs/ai/models.mdx index 48ff615ee..c484de334 100644 --- a/apps/docs/content/docs/ai/models.mdx +++ b/apps/docs/content/docs/ai/models.mdx @@ -89,7 +89,7 @@ To add an environment to a model that's already deployed, open its page and choo -Pick where it runs. For a GPU model the list shows your connected servers and clusters with GPUs, how many are free (or how many a cluster has per node) and what they cost, and, when the environment's Cloud has a DigitalOcean account, GPU server sizes Loomplane can create, marked **New server**. A target the model doesn't fit says why and can't be picked. For a CPU model, pick a ready server or cluster. +Pick where it runs. For a GPU model the list shows your connected servers and clusters with GPUs, how many are free (or how many a cluster has per node) and what they cost, and, when the project's Cloud has a DigitalOcean account, GPU server sizes Loomplane can create, marked **New server**. A target the model doesn't fit says why and can't be picked. For a CPU model, pick a ready server or cluster. diff --git a/apps/docs/content/docs/clouds/adopting-and-moving.mdx b/apps/docs/content/docs/clouds/adopting-and-moving.mdx index 612e4f5fd..f72e9951f 100644 --- a/apps/docs/content/docs/clouds/adopting-and-moving.mdx +++ b/apps/docs/content/docs/clouds/adopting-and-moving.mdx @@ -5,7 +5,7 @@ description: Bring running services under a Cloud target, then move them to anot ## Adopt an existing service -Keep your existing manifest until you choose to adopt a Cloud. Create a target with the service's current provider, connection and region, assign that Cloud to its environment, and save a manifest revision that sets `cloud_target` while removing any effective direct `provider` and `target` settings. Check inherited defaults and environment overrides too, because a service can't resolve both forms of placement. +Keep your existing manifest until you choose to adopt a Cloud. Create a target with the service's current provider, connection and region in your project's default Cloud, then save a manifest revision that sets `cloud_target` while removing any effective direct `provider` and `target` settings. The project's Clouds tab does this for you: pick the target beside the service and it writes the change for every environment, clearing placement an environment set on its own. Check inherited defaults too, because a service can't resolve both forms of placement. Review the ordinary deployment plan before you approve it. When the resolved placement and configuration match what already serves, the plan records Cloud metadata without a provider deployment. If it proposes a replacement, check the account, region and effective settings first. @@ -21,7 +21,7 @@ loomctl cloud-targets switch my-project cloud_... target_... \ --provider vercel --connection conn_new --revision 1 ``` -Read the preview. It lists the old and proposed placement, affected environments and services, action counts, external routing requirements and blockers. A Cloud shared by production and staging can affect both, so use separate Clouds when their destinations should change independently. +Read the preview. It lists the old and proposed placement, affected environments and services, action counts, external routing requirements and blockers. A target serves every environment that names it, so production and staging on the same target move together. Give them separate targets, with an environment override in loomplane.yaml, when their destinations should change independently. To accept a review you already saved, use its ID and digest: @@ -49,9 +49,9 @@ loomctl clouds switch-default my-project cloud_... \ --yes --request-id move-default --wait --timeout 30m ``` -The review covers every environment that uses the Cloud, across projects, and moves only the services the old default placed. Services on a target, or with their own `provider`, keep theirs, though one that depends on a moved service is redeployed to pick up the new address. Leave out the provider and connection (or pass `--clear`) to remove the default. Clearing is blocked while serving services still use it. One default switch runs per Cloud at a time, and no environment can be assigned to or from the Cloud until it settles. +The review covers every environment that uses the Cloud, across projects, and moves only the services the old default placed. Services on a target, or with their own `provider`, keep theirs, though one that depends on a moved service is redeployed to pick up the new address. Leave out the provider and connection (or pass `--clear`) to remove the default. Clearing is blocked while serving services still use it. One default switch runs per Cloud at a time, and no project can make the Cloud its default until it settles. -A Cloud reassignment works the same way for default-placed services: they move to the new Cloud's default, and the review blocks if the new Cloud has none your project can use. +Changing a project's default Cloud (`clouds make-default`, see [Cloud targets](/docs/clouds/cloud-targets#change-the-default-cloud)) works the same way for every environment of the project: services on the old default move to the new Cloud, by target name or to its default placement, and the review blocks if the new Cloud lacks a target a running service names. ## Follow and recover a sync diff --git a/apps/docs/content/docs/clouds/cloud-targets.mdx b/apps/docs/content/docs/clouds/cloud-targets.mdx index 9413c3838..065ca7e93 100644 --- a/apps/docs/content/docs/clouds/cloud-targets.mdx +++ b/apps/docs/content/docs/clouds/cloud-targets.mdx @@ -1,9 +1,9 @@ --- title: Cloud targets -description: Group accounts into an organization Cloud, name targets, grant them to projects, and place services by name or tag. +description: Group accounts into an organization Cloud, name targets, grant them to projects, and place services by name or tag in every environment. --- -Create an organization Cloud before you create a project. Add named targets, grant a project access, then assign the Cloud to an environment. A Cloud belongs to one organization. A target selects either a managed provider account or a server pool. Your manifest can then say `frontend` without carrying an account ID. +Create an organization Cloud, add named targets, and grant a project access. A project's first Cloud becomes its default Cloud, and every environment of the project deploys through it. A Cloud belongs to one organization. A target selects either a managed provider account or a server pool. Your manifest can then say `frontend` without carrying an account ID, and the same name works in production, staging and every preview. ```yaml version: 1 @@ -22,14 +22,12 @@ loomctl clouds create --organization --name Production loomctl cloud-targets create cloud_... --organization \ --name frontend --provider vercel --connection conn_... # Once your project exists, grant all targets or select them with --targets. +# A project's first grant makes that Cloud its default. loomctl cloud-grants grant cloud_... project_... --targets target_... -loomctl clouds assignment my-project env_... -loomctl clouds assign my-project env_... --cloud cloud_... --revision 0 -loomctl clouds assign my-project env_... --cloud cloud_... --revision 0 \ - --yes --request-id assign-production --wait --timeout 10m +loomctl clouds default my-project ``` -You can list, create, rename and delete organization Clouds with `--organization` and no project argument. The same flag works on `cloud-targets` and `cloud-syncs`. The project forms still work too, such as `clouds create my-project --name Production`. Assignment always needs a project. +You can list, create, rename and delete organization Clouds with `--organization` and no project argument. The same flag works on `cloud-targets` and `cloud-syncs`. The project forms still work too, such as `clouds create my-project --name Production`. A project's default Cloud always needs a project. ```bash loomctl clouds --organization @@ -41,7 +39,44 @@ loomctl cloud-syncs --organization An empty `--targets` grants the whole Cloud, including its default placement. A target list grants only those. Revoking prevents fresh placement but keeps the authority needed to clean up work you already accepted. Sharing capacity doesn't grant another project's releases, variables, logs or routes. -The first assignment uses revision `0`. Read `clouds assignment` before later changes, because unassigning keeps the generation. An unassigned environment can have a nonzero revision, and you need it to assign again. An environment from another project returns a scoped error, never an empty assignment. +## Change the default Cloud + +Environments don't pick Clouds. To move a project to another Cloud, make that Cloud its default. It's a reviewed change, because services already running move with it: + +```bash +loomctl clouds default my-project # shows the Cloud and its revision +loomctl clouds make-default my-project cloud_... --revision 3 +loomctl clouds make-default my-project cloud_... --revision 3 \ + --yes --request-id move-to-eu --wait --timeout 10m +``` + +`--revision` is the current default's revision from `clouds default`, or `0` when the project has none. The review covers every environment of the project and moves only the services that run on the old default. Pass `none` instead of a Cloud ID to leave the project without a default. Only a Cloud granted to the project can become its default, and revoking a grant ends its default without moving anything. + +Environments still differ where your manifest says so. Give staging its own target with an environment override, as `trainer` does below. + +## Use another Cloud + +A service can run on a target in any Cloud granted to the project. Name the Cloud with `cloud`: + +```yaml +services: + web: + source: node:apps/web + cloud_target: frontend # the project's default Cloud + trainer: + source: python:trainer + cloud: GPU Lab + cloud_target: a100 + environments: + preview: + cloud_target: eu-run # a target without cloud is in the default Cloud + staging: + cloud: GPU Lab EU # same target name, another Cloud +``` + +`cloud` alone uses that Cloud's default placement. An environment that names a target also says which Cloud it's in, so `preview` above goes back to the default Cloud. A name no Cloud granted to the project has fails the plan with `cloud-unknown` at `services.trainer.cloud`. In the dashboard, **Runs on** lists every granted Cloud's targets under the Cloud's name, and each Cloud on the project's Clouds tab can take services. + +Changing the project's default Cloud leaves services that name their Cloud where they are. A change to a Cloud itself, such as switching one of its targets, reaches every service placed on it. ## Pick a target by tags @@ -88,4 +123,4 @@ You can also pass `default_placement` when you create the Cloud, and send `"defa The default reaches a project only when its grant covers the whole Cloud. If an admin granted a chosen set of targets, your services can use those targets but not the default. -You can set a first default at any time. Once an environment uses the Cloud, `default-placement` refuses to replace or clear it (HTTP 409). Change it with a reviewed switch, described in [Adopting and moving services](/docs/clouds/adopting-and-moving#switch-a-default). +You can set a first default at any time. Once the Cloud is a project's default Cloud, or runs a service its default placed, `default-placement` refuses to replace or clear it (HTTP 409). Change it with a reviewed switch, described in [Adopting and moving services](/docs/clouds/adopting-and-moving#switch-a-default). diff --git a/apps/docs/content/docs/guides/add-a-service.mdx b/apps/docs/content/docs/guides/add-a-service.mdx index 190d2d936..7520c04fe 100644 --- a/apps/docs/content/docs/guides/add-a-service.mdx +++ b/apps/docs/content/docs/guides/add-a-service.mdx @@ -11,6 +11,8 @@ The dialog has three ways in: - **Catalog** has the databases, caches, gateways and the rest. Pick where it runs: a checked server or Kubernetes cluster, or a provider that runs it for you, such as Cloud SQL for Postgres. - **Any source path** takes a directory, a Dockerfile or a Procfile process that analysis didn't pick up. The name follows the path until you type one. +A service's **Runs on** lists your Clouds' targets first, the project's default Cloud and then each other Cloud the project may use, each under its name, and then the providers you can use directly. Picking a target writes `cloud_target`, plus `cloud` when it's in a Cloud other than the default (see [Cloud targets](/docs/clouds/cloud-targets#use-another-cloud)). + Then you choose what it needs and which services use it. Each service you tick gets its address in a variable, such as `DATABASE_URL` for Postgres or `BILLING_URL` for a service called `billing`, and the dialog shows the name next to it. You also choose whether it runs in every environment or only in the one you're adding it to. Before anything is saved, the dialog asks the server what the change would be and shows you the lines it adds to `loomplane.yaml`. If the server would refuse it, you see why right there. @@ -53,16 +55,19 @@ Add one with: loomctl services add shop --suggested worker ```bash loomctl services add shop --suggested worker --env staging loomctl services add shop --source services/billing --needs db --needed-by api +loomctl services add shop --suggested trainer --cloud "GPU Lab" --cloud-target a100 loomctl services add shop --kind redis --needed-by api,worker --env staging --only ``` The project can be its name, slug or ID. A name defaults to the suggestion's, the catalog kind's, or the source's last directory, numbered when it's taken. A catalog kind runs on your only ready server or cluster when you don't give `--target`, and when there are several, loomctl lists them so you can choose. +`--cloud-target` puts a service on a Cloud target, in the project's default Cloud unless `--cloud` names another, and replaces the provider a suggestion came with. It can't be combined with `--provider` or `--target`. + `--dry-run` prints the `loomplane.yaml` it would save and changes nothing. `--no-plan` saves it without planning. ## From the API -It's one edit: `POST /api/v1/projects/:id/manifest/edits` with `add_service` or `add_resource`. Both take `enabled_in` and `only` for the environment, and `needed_by` for the services that use it. `add_service` takes `source`, and optionally `repo`, `kind`, `provider`, `region`, `target`, `port`, `public` and `needs`. +It's one edit: `POST /api/v1/projects/:id/manifest/edits` with `add_service` or `add_resource`. Both take `enabled_in` and `only` for the environment, and `needed_by` for the services that use it. `add_service` takes `source`, and optionally `repo`, `kind`, `cloud`, `cloud_target`, `provider`, `region`, `target`, `port`, `public` and `needs`. `cloud_target` and `cloud` can't be set with `provider` or `target`. ```json { diff --git a/apps/docs/content/docs/reference/loomctl.mdx b/apps/docs/content/docs/reference/loomctl.mdx index 59a8150cd..43b0d863f 100644 --- a/apps/docs/content/docs/reference/loomctl.mdx +++ b/apps/docs/content/docs/reference/loomctl.mdx @@ -122,7 +122,7 @@ Preparing needs `deployment:create` and `agent:use` on the project. `loomctl mcp | Command | What it does | |---|---| | `services create NAME --target CONN [--kind K] [--provider P] [--region R] [--env E] [--json]` | Plans a standalone database service. `--kind` is `postgres` (default), `mysql`, `mariadb`, `redis` or `valkey`. `--provider` is `server` (default), `kubernetes`, `rds` or `cloud-sql` | -| `services add PROJECT (--suggested NAME \| --source PATH \| --kind K) [--name N] [--env E] [--only] [--needs A,B] [--needed-by A,B] [--provider P] [--target CONN] [--dry-run] [--no-plan] [--json]` | Adds a service to a project and plans `--env`: one analysis found, one from any source path, or a catalog kind. `--only` runs it in `--env` alone. The name and a catalog kind's target default when there's one obvious choice. See [Add a service](/docs/guides/add-a-service) | +| `services add PROJECT (--suggested NAME \| --source PATH \| --kind K) [--name N] [--env E] [--only] [--needs A,B] [--needed-by A,B] [--cloud-target T [--cloud C] \| --provider P [--target CONN]] [--dry-run] [--no-plan] [--json]` | Adds a service to a project and plans `--env`: one analysis found, one from any source path, or a catalog kind. `--only` runs it in `--env` alone. The name and a catalog kind's target default when there's one obvious choice. See [Add a service](/docs/guides/add-a-service) | | `services suggest PROJECT [--json]` | Lists the services analysis found that the project's manifest doesn't run yet | | `backups PROJECT`, `backups show ID`, `backups create PROJECT --resource NAME`, `backups retry ID` | List, read, create and retry backups. `create` takes `--env` and `--request-id` | | `backups policy PROJECT --resource NAME --every-hours N [--disable]`, `backups policies PROJECT` | Set and list backup schedules | @@ -140,7 +140,7 @@ Recovery commands that wait take `--wait` and `--timeout` (45 minutes by default | Command | What it does | |---|---| | `clouds [PROJECT] [--organization]`, `clouds create`, `show`, `update`, `delete` | Manage Clouds. With `--organization` no project argument is needed | -| `clouds assignment`, `assign`, `switch-default` | Assign a Cloud to an environment and change its default placement | +| `clouds default`, `make-default`, `switch-default` | Show or change the project's default Cloud, and change a Cloud's default placement | | `cloud-targets`, `show`, `create`, `update`, `delete`, `switch` | Manage targets within a Cloud | | `cloud-grants CLOUD`, `grant CLOUD PROJECT [--targets IDS]`, `revoke CLOUD PROJECT` | Project access to a Cloud | | `cloud-syncs`, `show`, `wait`, `retry`, `revert`, `routing`, `apply` | Follow and recover a placement change | diff --git a/apps/docs/content/docs/reference/loomplane-yaml.mdx b/apps/docs/content/docs/reference/loomplane-yaml.mdx index dd1c0e969..78d1b5a13 100644 --- a/apps/docs/content/docs/reference/loomplane-yaml.mdx +++ b/apps/docs/content/docs/reference/loomplane-yaml.mdx @@ -41,7 +41,8 @@ Names (of services, resources, gateways, links and environments in overrides) ma | `provider` | string | Where it runs, by the provider's name | | `region` | string | The provider's region | | `target` | `conn_...` | The checked server or Kubernetes connection to run on | -| `cloud_target` | string | A named target in the environment's assigned Cloud. Can't be set with `cloud_tags` | +| `cloud` | string | The name of the Cloud `cloud_target`, `cloud_tags` or the Cloud's default placement resolve in: any Cloud granted to the project. Leave it out for the project's default Cloud. An environment override that names a target without `cloud` is in the default Cloud. Can't be set with `provider` or `target` | +| `cloud_target` | string | A named target in the service's Cloud: the one `cloud` names, or the project's default. Can't be set with `cloud_tags` | | `cloud_tags` | array | Up to 8 tags. Selects the one target that carries every tag. Can't be set with `cloud_target` | | `endpoint` | object | See [endpoint](#endpoint) | | `health_path` | string | A readiness path, such as `/_/health`. Starts with `/` | diff --git a/database/migrations/20261228000100_project_default_cloud.go b/database/migrations/20261228000100_project_default_cloud.go new file mode 100644 index 000000000..13936dc98 --- /dev/null +++ b/database/migrations/20261228000100_project_default_cloud.go @@ -0,0 +1,542 @@ +package migrations + +import ( + "context" + "fmt" + + "github.com/xraph/grove/migrate" +) + +// A project's default Cloud replaces the per-environment Cloud assignment. +// Clouds belong to the organization and grants already ignore environments; +// the assignment was the one thing tying a Cloud to an environment. Now one +// grant per project is its default, every environment of the project uses +// it, and environments differ only through loomplane.yaml. +// +// Placements stop pinning an assignment revision. Switching the default +// bumps both grants' revisions, which every placement already pins, so a +// plan resolved against the old default is stale without a new pin. +func init() { + App.Add( + func(ctx context.Context, db *migrate.DB) error { + for _, step := range projectDefaultCloudUp { + if _, err := db.Exec(ctx, step.sql); err != nil { + return fmt.Errorf("%s: %w", step.what, err) + } + } + return nil + }, + func(ctx context.Context, db *migrate.DB) error { + for _, step := range projectDefaultCloudDown { + if _, err := db.Exec(ctx, step.sql); err != nil { + return fmt.Errorf("%s: %w", step.what, err) + } + } + return nil + }, + ) +} + +type migrationStep struct{ what, sql string } + +var projectDefaultCloudUp = []migrationStep{ + {"add the default flag to Cloud grants", `ALTER TABLE loomplane_cloud_project_grants ADD COLUMN IF NOT EXISTS is_default boolean NOT NULL DEFAULT false`}, + // The Cloud most of a project's environments use becomes its default, + // ties going to the most recent assignment. Marking it changes nothing + // any plan resolved, so its revision stays where every plan pinned it. + {"pause grant revision checks for the backfill", `ALTER TABLE loomplane_cloud_project_grants DISABLE TRIGGER loomplane_cloud_grant_revision`}, + {"make each project's most used Cloud its default", `DO $$ BEGIN + -- A rerun finds the assignments already gone and has nothing to carry over. + IF to_regclass('loomplane_cloud_assignments') IS NULL THEN RETURN; END IF; + WITH used AS ( + SELECT a.org_id,a.project_id,a.cloud_id,count(*) AS environments,max(a.revision) AS latest + FROM loomplane_cloud_assignments a + JOIN loomplane_cloud_project_grants g ON g.org_id=a.org_id AND g.project_id=a.project_id AND g.cloud_id=a.cloud_id AND NOT g.revoked + WHERE a.cloud_id IS NOT NULL + GROUP BY a.org_id,a.project_id,a.cloud_id + ), picked AS ( + SELECT DISTINCT ON (org_id,project_id) org_id,project_id,cloud_id FROM used + ORDER BY org_id,project_id,environments DESC,latest DESC,cloud_id + ) + UPDATE loomplane_cloud_project_grants g SET is_default=true + FROM picked p WHERE g.org_id=p.org_id AND g.project_id=p.project_id AND g.cloud_id=p.cloud_id + AND NOT EXISTS(SELECT 1 FROM loomplane_cloud_project_grants d WHERE d.org_id=g.org_id AND d.project_id=g.project_id AND d.is_default AND NOT d.revoked); +END $$`}, + {"resume grant revision checks", `ALTER TABLE loomplane_cloud_project_grants ENABLE TRIGGER loomplane_cloud_grant_revision`}, + {"allow one live default Cloud per project", `CREATE UNIQUE INDEX IF NOT EXISTS loomplane_cloud_project_default ON loomplane_cloud_project_grants(org_id,project_id) WHERE is_default AND NOT revoked`}, + // Revoking a grant ends its default, however the revocation is written. + // Asking for a revoked default outright is refused, and a default can't + // change under a shared change still moving services on that Cloud. + {"guard the default flag", `CREATE OR REPLACE FUNCTION loomplane_cloud_default_guard() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='UPDATE' AND NEW.revoked AND NOT OLD.revoked THEN + NEW.is_default := false; + END IF; + IF NEW.is_default AND NEW.revoked THEN + RAISE EXCEPTION 'a revoked grant cannot be the default Cloud' USING ERRCODE='23514'; + END IF; + IF TG_OP='UPDATE' AND NEW.is_default IS NOT DISTINCT FROM OLD.is_default THEN RETURN NEW; END IF; + IF NOT NEW.is_default THEN RETURN NEW; END IF; + IF EXISTS(SELECT 1 FROM loomplane_cloud_syncs WHERE org_id=NEW.org_id AND cloud_id=NEW.cloud_id AND (target_id<>'' OR body->>'default'='true') AND status NOT IN ('succeeded','reverted')) THEN + RAISE EXCEPTION 'Cloud target has unfinished migration work' USING ERRCODE='55P03'; + END IF; + RETURN NEW; +END $$`}, + {"attach the default guard", `CREATE OR REPLACE TRIGGER loomplane_cloud_default BEFORE INSERT OR UPDATE ON loomplane_cloud_project_grants FOR EACH ROW EXECUTE FUNCTION loomplane_cloud_default_guard()`}, + {"announce default Cloud changes", `CREATE OR REPLACE FUNCTION loomplane_project_cloud_event_trigger() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='UPDATE' AND NEW.is_default IS NOT DISTINCT FROM OLD.is_default AND NEW.revoked IS NOT DISTINCT FROM OLD.revoked THEN RETURN NULL; END IF; + IF TG_OP='INSERT' AND NOT NEW.is_default THEN RETURN NULL; END IF; + PERFORM loomplane_append_event(NEW.org_id,NEW.project_id,'project_cloud.updated',NEW.project_id, + jsonb_build_object('org_id',NEW.org_id,'project_id',NEW.project_id, + 'cloud_id',(SELECT cloud_id FROM loomplane_cloud_project_grants WHERE org_id=NEW.org_id AND project_id=NEW.project_id AND is_default AND NOT revoked))); + RETURN NULL; +END $$`}, + {"attach the default Cloud event", `CREATE OR REPLACE TRIGGER loomplane_project_cloud_event AFTER INSERT OR UPDATE ON loomplane_cloud_project_grants FOR EACH ROW EXECUTE FUNCTION loomplane_project_cloud_event_trigger()`}, + // A target stays while a serving placement pins it, or while its Cloud + // is a project's default, whose manifests may name it at the next plan. + {"keep targets that are in use", `CREATE OR REPLACE FUNCTION loomplane_cloud_target_delete_trigger() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + PERFORM 1 FROM loomplane_cloud_profiles WHERE org_id=OLD.org_id AND id=OLD.cloud_id FOR UPDATE; + IF EXISTS(SELECT 1 FROM loomplane_cloud_project_grants WHERE org_id=OLD.org_id AND cloud_id=OLD.cloud_id AND is_default AND NOT revoked) + OR EXISTS(SELECT 1 FROM loomplane_bindings WHERE org_id=OLD.org_id AND subject='service' AND config->'cloud_placement'->>'target_id'=OLD.id) THEN + RAISE EXCEPTION 'target belongs to a Cloud in use' USING ERRCODE='23503'; + END IF; + RETURN OLD; +END $$`}, + // The assignment's foreign key once kept a Cloud in use from being + // deleted. Grants cascade with their Cloud, so a project's default would + // vanish with it; refuse before the cascade runs. + {"keep Clouds that are in use", `CREATE OR REPLACE FUNCTION loomplane_cloud_profile_delete_guard() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS(SELECT 1 FROM loomplane_cloud_project_grants WHERE org_id=OLD.org_id AND cloud_id=OLD.id AND is_default AND NOT revoked) + OR EXISTS(SELECT 1 FROM loomplane_bindings WHERE org_id=OLD.org_id AND subject='service' AND config->'cloud_placement'->>'cloud_id'=OLD.id) THEN + RAISE EXCEPTION 'Cloud is in use' USING ERRCODE='23503'; + END IF; + RETURN OLD; +END $$`}, + {"attach the Cloud delete guard", `CREATE OR REPLACE TRIGGER loomplane_cloud_profile_delete BEFORE DELETE ON loomplane_cloud_profiles FOR EACH ROW EXECUTE FUNCTION loomplane_cloud_profile_delete_guard()`}, + {"check capacity intents without an assignment", `CREATE OR REPLACE FUNCTION public.loomplane_capacity_intent_current(p loomplane_plans, i jsonb) + RETURNS boolean + LANGUAGE sql + STABLE +AS $function$ + SELECT coalesce(i->'demand'->>'org_id'=p.org_id AND i->'demand'->>'project_id'=p.project_id AND i->'demand'->>'environment_id'=p.environment_id AND i->'demand'->>'plan_id'=p.id + AND EXISTS(SELECT 1 FROM loomplane_cloud_targets t + JOIN loomplane_cloud_project_grants g ON g.org_id=t.org_id AND g.cloud_id=t.cloud_id AND g.project_id=p.project_id AND NOT g.revoked + JOIN loomplane_cloud_profiles c ON c.org_id=t.org_id AND c.id=t.cloud_id + JOIN loomplane_cloud_capacity_policies cp ON cp.org_id=t.org_id AND cp.cloud_id=t.cloud_id + JOIN loomplane_cloud_connections pc ON pc.org_id=t.org_id AND pc.id=i->'template'->>'connection_id' AND pc.generation=(i->'provider_pin'->>'connection_generation')::bigint + AND (CASE pc.cloud + WHEN 'digitalocean' THEN coalesce(nullif(pc.details->>'team_uuid',''),pc.details->>'account_uuid') + WHEN 'vercel' THEN coalesce(nullif(pc.details->>'team_id',''),pc.details->>'user_id') + ELSE pc.account END)=i->'provider_pin'->>'account_id' + AND pc.status='ready' + WHERE t.org_id=p.org_id AND t.id=i->'demand'->>'target_id' AND t.cloud_id=i->'demand'->>'cloud_id' AND t.pool_id=i->'demand'->>'pool_id' + AND t.provider='server' AND t.revision=(i->>'target_revision')::bigint AND c.revision=(i->>'cloud_revision')::bigint AND g.revision=(i->>'grant_revision')::bigint + AND (cardinality(g.target_ids)=0 OR t.id=ANY(g.target_ids)) AND cp.enabled + AND EXISTS(SELECT 1 FROM jsonb_array_elements(cp.body->'pools') template + WHERE template->>'pool_id'=t.pool_id AND template-ARRAY['min_servers','max_servers','limits'] = (i->'template')-ARRAY['min_servers','max_servers','limits'])) ,false) $function$`}, + {"check workload scope without an assignment", `CREATE OR REPLACE FUNCTION public.loomplane_cluster_workload_scope_current(p loomplane_plans, d jsonb) + RETURNS boolean + LANGUAGE sql + STABLE +AS $function$ + SELECT coalesce(d->'input'->>'org_id'=p.org_id AND d->'input'->>'project_id'=p.project_id AND d->'input'->>'environment_id'=p.environment_id AND d->'input'->>'plan_id'=p.id AND EXISTS( + SELECT 1 FROM loomplane_cloud_targets t + JOIN loomplane_cloud_profiles c ON c.org_id=t.org_id AND c.id=t.cloud_id + JOIN loomplane_cloud_project_grants g ON g.org_id=t.org_id AND g.cloud_id=t.cloud_id AND g.project_id=p.project_id AND NOT g.revoked + JOIN loomplane_cloud_connections cn ON cn.org_id=t.org_id AND cn.id=t.connection_id AND cn.status='ready' AND cn.cloud='kubernetes' + JOIN loomplane_runtime_attachments rt ON rt.org_id=t.org_id AND rt.id=d->'input'->>'attachment_id' AND rt.cluster_id=t.managed_resource_id AND rt.project_id=p.project_id AND rt.runtime_connection_id=t.connection_id AND rt.deleted_at IS NULL AND rt.body->>'trust_revision'=d->'input'->>'trust_revision' AND rt.body->>'namespace_uid'=cn.details->>'namespace_uid' AND rt.body->>'trust_fingerprint'=cn.details->>'cluster_ca' + JOIN loomplane_managed_resources mr ON mr.org_id=t.org_id AND mr.id=t.managed_resource_id AND mr.deleted_at IS NULL AND mr.status NOT IN ('missing','identity_changed') + WHERE t.org_id=p.org_id AND t.id=d->'input'->>'target_id' AND t.cloud_id=d->'input'->>'cloud_id' AND t.project_id=p.project_id AND t.managed_resource_id=d->'input'->>'resource_id' AND t.connection_id=d->'input'->>'connection_id' + AND t.revision=(d->'placement'->>'target_revision')::bigint AND c.revision=(d->'placement'->>'cloud_revision')::bigint AND g.revision=(d->'placement'->>'grant_revision')::bigint AND cn.generation=(d->>'connection_generation')::bigint + AND (cardinality(g.target_ids)=0 OR t.id=ANY(g.target_ids))),false) $function$`}, + {"admit capacity plans without an assignment", `CREATE OR REPLACE FUNCTION public.loomplane_admit_capacity_plan(candidate loomplane_plans, approved loomplane_plans) + RETURNS void + LANGUAGE plpgsql +AS $function$ +DECLARE + a JSONB; + pin JSONB; + host loomplane_cloud_servers%ROWTYPE; + member loomplane_server_pool_members%ROWTYPE; + pool loomplane_server_pools%ROWTYPE; + cpu BIGINT; + mem BIGINT; + used_cpu BIGINT; + used_mem BIGINT; +BEGIN + + + -- Order host and connection locks consistently across every accepted plan. + PERFORM 1 FROM loomplane_cloud_connections c + WHERE c.org_id=candidate.org_id AND c.id IN (SELECT x->>'connection_id' FROM jsonb_array_elements(coalesce(candidate.result->'actions','[]')) x) + ORDER BY c.id + FOR UPDATE; + PERFORM pg_advisory_xact_lock(hashtextextended('host-admission/'||identity,0)) + FROM ( + SELECT DISTINCT c.details->>'docker_id' identity + FROM loomplane_cloud_connections c + WHERE c.org_id=candidate.org_id AND c.cloud='server' AND coalesce(c.details->>'docker_id','')<>'' AND c.id IN (SELECT x->>'connection_id' FROM jsonb_array_elements(coalesce(candidate.result->'actions','[]')) x) + ORDER BY identity + ) identities; + PERFORM 1 FROM loomplane_cloud_servers s + WHERE s.org_id=candidate.org_id AND s.id IN (SELECT x->'service'->'cloud_placement'->>'server_id' FROM jsonb_array_elements(coalesce(candidate.result->'actions','[]')) x) + ORDER BY s.id + FOR UPDATE; + + FOR a IN SELECT value FROM jsonb_array_elements(coalesce(candidate.result->'actions','[]')) LOOP + IF a->>'op'='delete' OR (a->>'op'='keep' AND NOT coalesce((a->>'adopt_cloud_placement')::boolean,false)) THEN CONTINUE; END IF; + IF coalesce((a->'compensation'->>'retained')::boolean,false) THEN + IF NOT loomplane_retained_compensation(approved,a) THEN RAISE EXCEPTION 'retained compensation identity changed' USING ERRCODE='23514'; END IF; + CONTINUE; + END IF; + IF coalesce(a->'service'->'capacity_intent','null')<>'null'::jsonb THEN + IF NOT EXISTS(SELECT 1 FROM loomplane_capacity_intents i WHERE i.org_id=approved.org_id AND i.plan_id=approved.id AND i.service=a->>'name' AND i.plan_revision=approved.revision AND i.body=a->'service'->'capacity_intent') THEN + RAISE EXCEPTION 'missing approved deferred intent' USING ERRCODE='23514'; + END IF; + CONTINUE; + END IF; + pin:=a->'service'->'cloud_placement'; + IF pin ? 'allocation' AND (jsonb_typeof(pin->'allocation')<>'string' OR length(pin->>'allocation')>200 OR pin->>'allocation'<>btrim(pin->>'allocation')) THEN + RAISE EXCEPTION 'allocation must be a bounded string' USING ERRCODE='23514'; + END IF; + IF coalesce(pin->>'pool_id','')='' THEN + IF a->>'provider'='server' AND EXISTS( + SELECT 1 FROM loomplane_server_pool_members m + JOIN loomplane_cloud_servers s ON s.id=m.server_id + JOIN loomplane_cloud_connections c ON c.org_id=candidate.org_id AND c.id=a->>'connection_id' + WHERE (s.runtime_connection_id=c.id OR (coalesce(c.details->>'docker_id','')<>'' AND c.details->>'docker_id'=s.body->'health'->>'docker_id')) AND s.status NOT IN ('deleted','disconnected') + ) THEN + RAISE EXCEPTION 'pooled capacity requires a pool target' USING ERRCODE='23514'; + END IF; + CONTINUE; + END IF; + IF coalesce(candidate.result->>'cloud_sync_id','')<>'' AND NOT loomplane_accepted_pool_sync(approved) THEN + RAISE EXCEPTION 'pool sync needs its exact immutable accepted participant plan' USING ERRCODE='23514'; + END IF; + IF jsonb_array_length(coalesce(a->'routes','[]'))>0 AND ( + coalesce(pin->>'allocation','')='' OR EXISTS( + SELECT 1 FROM loomplane_bindings b + WHERE b.org_id=candidate.org_id AND b.project_id=candidate.project_id AND b.environment_id=candidate.environment_id AND b.subject='service' AND b.name=a->>'name' + AND (coalesce(b.config->'cloud_placement'->>'allocation','')=pin->>'allocation' + OR (b.config->'cloud_placement' ? 'allocation' AND jsonb_typeof(b.config->'cloud_placement'->'allocation')<>'string') + OR (coalesce(b.config->'cloud_placement'->>'pool_id','')<>'' AND NOT EXISTS(SELECT 1 FROM loomplane_capacity_reservations r WHERE r.org_id=b.org_id AND r.project_id=b.project_id AND r.environment_id=b.environment_id AND r.service=b.name AND r.plan_id=b.plan_id AND r.server_id=b.config->'cloud_placement'->>'server_id' AND r.binding_id=b.id AND r.body=b.config->'cloud_placement'))))) THEN + RAISE EXCEPTION 'routed allocation must retain the exact source and reserve a distinct candidate' USING ERRCODE='23514'; + END IF; + IF EXISTS(SELECT 1 FROM loomplane_capacity_reservations WHERE org_id=candidate.org_id AND environment_id=candidate.environment_id AND service=a->>'name' AND binding_id='' AND plan_id<>candidate.id) THEN + RAISE EXCEPTION 'recover the unresolved accepted placement before another deployment' USING ERRCODE='23514'; + END IF; + IF coalesce((pin->>'pool_revision')::bigint,0)<1 OR coalesce((pin->>'server_revision')::bigint,0)<1 OR coalesce((pin->>'connection_generation')::bigint,0)<1 + OR coalesce((pin->>'cpu_millis')::bigint,0)<1 OR coalesce((pin->>'memory_bytes')::bigint,0)<1 + OR coalesce((a->'service'->'scale'->>'min')::int,1)<>1 OR coalesce((a->'service'->'scale'->>'max')::int,1)<>1 THEN + RAISE EXCEPTION 'pool placement needs bounded resources and one replica' USING ERRCODE='23514'; + END IF; + IF EXISTS( + SELECT 1 FROM loomplane_bindings b + WHERE b.org_id=candidate.org_id AND b.environment_id=candidate.environment_id AND b.subject='service' AND b.name=a->>'name' AND coalesce(b.config->'cloud_placement'->>'server_id','')<>pin->>'server_id' + AND (coalesce(b.config->'catalog','null')<>'null'::jsonb OR (NOT loomplane_accepted_pool_sync(approved) AND NOT EXISTS(SELECT 1 FROM loomplane_placement_moves m WHERE m.org_id=b.org_id AND m.project_id=b.project_id AND m.environment_id=b.environment_id AND m.service=b.name AND m.source_server_id=b.config->'cloud_placement'->>'server_id' AND m.destination_server_id=pin->>'server_id' AND m.source_config=b.config AND m.expires_at>now()))) + ) THEN + RAISE EXCEPTION 'host relocation needs a current explicit stateless move review' USING ERRCODE='23514'; + END IF; + + SELECT * INTO host FROM loomplane_cloud_servers WHERE org_id=candidate.org_id AND id=pin->>'server_id'; + SELECT * INTO pool FROM loomplane_server_pools WHERE org_id=candidate.org_id AND cloud_id=pin->>'cloud_id' AND id=pin->>'pool_id' FOR SHARE; + SELECT * INTO member FROM loomplane_server_pool_members WHERE org_id=candidate.org_id AND pool_id=pool.id AND server_id=host.id; + IF host.id IS NULL OR pool.id IS NULL OR member.server_id IS NULL OR host.status<>'ready' OR host.revision<>(pin->>'server_revision')::bigint OR pool.revision<>(pin->>'pool_revision')::bigint + OR host.runtime_connection_id<>pin->>'connection_id' OR a->>'connection_id'<>pin->>'connection_id' OR a->>'provider'<>'server' THEN + RAISE EXCEPTION 'pool placement changed; review again' USING ERRCODE='23514'; + END IF; + IF (coalesce((host.body->>'draining')::boolean,false) OR EXISTS(SELECT 1 FROM loomplane_server_pool_members WHERE server_id=host.id AND draining)) + AND NOT EXISTS(SELECT 1 FROM loomplane_bindings WHERE org_id=candidate.org_id AND environment_id=candidate.environment_id AND subject='service' AND name=a->>'name' AND config->'cloud_placement'->>'server_id'=host.id) THEN + RAISE EXCEPTION 'server is draining' USING ERRCODE='23514'; + END IF; + IF (host.body->'health'->>'checked_at')::timestamptz < now()-interval '15 minutes' OR (host.body->'health'->>'checked_at')::timestamptz > now()+interval '1 minute' + OR coalesce((host.body->'health'->>'effective_cpu_millis')::bigint,0)'health'->>'effective_memory_bytes')::bigint,0)>'connection_generation')::bigint) THEN + RAISE EXCEPTION 'runtime connection changed' USING ERRCODE='23514'; + END IF; + + PERFORM 1 FROM loomplane_cloud_project_grants WHERE org_id=candidate.org_id AND cloud_id=pin->>'cloud_id' AND project_id=candidate.project_id FOR SHARE; + PERFORM 1 FROM loomplane_cloud_targets WHERE org_id=candidate.org_id AND id=pin->>'target_id' FOR SHARE; + PERFORM 1 FROM loomplane_cloud_profiles WHERE org_id=candidate.org_id AND id=pin->>'cloud_id' FOR SHARE; + IF NOT EXISTS( + SELECT 1 FROM loomplane_cloud_targets t + JOIN loomplane_cloud_project_grants g ON g.org_id=t.org_id AND g.cloud_id=t.cloud_id AND g.project_id=candidate.project_id AND NOT g.revoked + JOIN loomplane_cloud_profiles c ON c.org_id=t.org_id AND c.id=t.cloud_id + WHERE t.org_id=candidate.org_id AND t.id=pin->>'target_id' AND t.pool_id=pool.id AND t.revision=(pin->>'target_revision')::bigint + AND c.revision=(pin->>'cloud_revision')::bigint AND g.revision=(pin->>'grant_revision')::bigint AND (cardinality(g.target_ids)=0 OR t.id=ANY(g.target_ids)) + ) THEN + RAISE EXCEPTION 'pool target authority changed' USING ERRCODE='23514'; + END IF; + + cpu:=coalesce((a->'service'->'size'->>'cpu')::numeric*1000,1000); + mem:=coalesce((a->'service'->'size'->>'memory')::bigint*1048576,536870912); + IF cpu<=0 OR mem<=0 OR cpu<>(pin->>'cpu_millis')::bigint OR mem<>(pin->>'memory_bytes')::bigint THEN + RAISE EXCEPTION 'capacity differs from runtime limits' USING ERRCODE='23514'; + END IF; + SELECT c.cpu,c.memory INTO used_cpu,used_mem + FROM loomplane_server_capacity(host.id,candidate.environment_id,jsonb_build_array(jsonb_build_object('service',a->>'name','server_id',host.id,'allocation',coalesce(pin->>'allocation',''),'cpu_millis',cpu,'memory_bytes',mem))) c; + IF used_cpu>member.cpu_millis OR used_mem>member.memory_bytes THEN + RAISE EXCEPTION 'insufficient reserved host capacity' USING ERRCODE='23514'; + END IF; + INSERT INTO loomplane_capacity_reservations(org_id,project_id,environment_id,service,plan_id,pool_id,server_id,connection_id,cpu_millis,memory_bytes,body) + VALUES(candidate.org_id,candidate.project_id,candidate.environment_id,a->>'name',candidate.id,pool.id,host.id,host.runtime_connection_id,cpu,mem,pin) + ON CONFLICT DO NOTHING; + END LOOP; + + RETURN; +END $function$`}, + {"drop the assignment table", `DROP TABLE IF EXISTS loomplane_cloud_assignments`}, + {"drop the assignment event function", `DROP FUNCTION IF EXISTS loomplane_environment_cloud_event_trigger()`}, + {"drop the assignment grant guard", `DROP FUNCTION IF EXISTS loomplane_cloud_assignment_grant_guard()`}, +} + +// Down gives every environment of a project its project's default Cloud, +// which is the closest the per-environment model can say. +var projectDefaultCloudDown = []migrationStep{ + {"recreate the assignment table", `CREATE TABLE IF NOT EXISTS loomplane_cloud_assignments( + org_id text NOT NULL, project_id text NOT NULL, environment_id text NOT NULL, cloud_id text, revision bigint NOT NULL CHECK (revision>0), + PRIMARY KEY (org_id,project_id,environment_id), + FOREIGN KEY (org_id,project_id,environment_id) REFERENCES loomplane_environments(org_id,project_id,id) ON DELETE CASCADE, + CONSTRAINT shared_cloud_assignment_owner FOREIGN KEY (org_id,cloud_id) REFERENCES loomplane_cloud_profiles(org_id,id) ON DELETE RESTRICT)`}, + {"recreate the assignment index", `CREATE INDEX IF NOT EXISTS loomplane_cloud_assignments_cloud ON loomplane_cloud_assignments(org_id,project_id,cloud_id)`}, + {"assign each environment its project's default", `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) +SELECT e.org_id,e.project_id,e.id,g.cloud_id,1 FROM loomplane_environments e +JOIN loomplane_cloud_project_grants g ON g.org_id=e.org_id AND g.project_id=e.project_id AND g.is_default AND NOT g.revoked +ON CONFLICT DO NOTHING`}, + {"restore the assignment grant guard", `CREATE OR REPLACE FUNCTION public.loomplane_cloud_assignment_grant_guard() + RETURNS trigger + LANGUAGE plpgsql +AS $function$ +BEGIN + IF NEW.cloud_id IS NULL THEN RETURN NEW; END IF; + IF TG_OP='UPDATE' AND NEW.cloud_id IS NOT DISTINCT FROM OLD.cloud_id THEN RETURN NEW; END IF; + + PERFORM pg_advisory_xact_lock(hashtextextended('cloud-organization/'||NEW.org_id,0)); + PERFORM 1 FROM loomplane_cloud_project_grants WHERE org_id=NEW.org_id AND project_id=NEW.project_id AND cloud_id=NEW.cloud_id AND NOT revoked FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Cloud is not granted to project' USING ERRCODE='23503'; + END IF; + IF EXISTS(SELECT 1 FROM loomplane_cloud_syncs WHERE org_id=NEW.org_id AND cloud_id=NEW.cloud_id AND (target_id<>'' OR body->>'default'='true') AND status NOT IN ('succeeded','reverted')) THEN + RAISE EXCEPTION 'Cloud target has unfinished migration work' USING ERRCODE='55P03'; + END IF; + + RETURN NEW; +END $function$`}, + {"restore the assignment event function", `CREATE OR REPLACE FUNCTION public.loomplane_environment_cloud_event_trigger() + RETURNS trigger + LANGUAGE plpgsql +AS $function$ +DECLARE + doc JSONB; +BEGIN + IF TG_OP='DELETE' THEN doc:=to_jsonb(OLD); ELSE doc:=to_jsonb(NEW); END IF; + + PERFORM loomplane_append_event(doc->>'org_id',doc->>'project_id','environment_cloud.updated',doc->>'environment_id',doc); + RETURN NULL; +END $function$`}, + {"restore the assignment grant trigger", `CREATE OR REPLACE TRIGGER loomplane_cloud_assignment_grant BEFORE INSERT OR UPDATE ON loomplane_cloud_assignments FOR EACH ROW EXECUTE FUNCTION loomplane_cloud_assignment_grant_guard()`}, + {"restore the assignment revision trigger", `CREATE OR REPLACE TRIGGER loomplane_cloud_assignment_revision BEFORE UPDATE ON loomplane_cloud_assignments FOR EACH ROW EXECUTE FUNCTION loomplane_cloud_revision_trigger()`}, + {"restore the assignment event trigger", `CREATE OR REPLACE TRIGGER loomplane_state_event AFTER INSERT OR DELETE OR UPDATE ON loomplane_cloud_assignments FOR EACH ROW EXECUTE FUNCTION loomplane_environment_cloud_event_trigger()`}, + {"restore the target delete guard", `CREATE OR REPLACE FUNCTION public.loomplane_cloud_target_delete_trigger() + RETURNS trigger + LANGUAGE plpgsql +AS $function$ +BEGIN + PERFORM 1 FROM loomplane_cloud_profiles WHERE org_id=OLD.org_id AND id=OLD.cloud_id FOR UPDATE; + IF EXISTS(SELECT 1 FROM loomplane_cloud_assignments WHERE org_id=OLD.org_id AND cloud_id=OLD.cloud_id) THEN + RAISE EXCEPTION 'target belongs to an assigned cloud' USING ERRCODE='23503'; + END IF; + RETURN OLD; +END $function$`}, + {"restore capacity intent checks", `CREATE OR REPLACE FUNCTION public.loomplane_capacity_intent_current(p loomplane_plans, i jsonb) + RETURNS boolean + LANGUAGE sql + STABLE +AS $function$ + SELECT coalesce(i->'demand'->>'org_id'=p.org_id AND i->'demand'->>'project_id'=p.project_id AND i->'demand'->>'environment_id'=p.environment_id AND i->'demand'->>'plan_id'=p.id + AND EXISTS(SELECT 1 FROM loomplane_cloud_targets t + JOIN loomplane_cloud_project_grants g ON g.org_id=t.org_id AND g.cloud_id=t.cloud_id AND g.project_id=p.project_id AND NOT g.revoked + JOIN loomplane_cloud_assignments a ON a.org_id=t.org_id AND a.project_id=p.project_id AND a.environment_id=p.environment_id AND a.cloud_id=t.cloud_id + JOIN loomplane_cloud_profiles c ON c.org_id=t.org_id AND c.id=t.cloud_id + JOIN loomplane_cloud_capacity_policies cp ON cp.org_id=t.org_id AND cp.cloud_id=t.cloud_id + JOIN loomplane_cloud_connections pc ON pc.org_id=t.org_id AND pc.id=i->'template'->>'connection_id' AND pc.generation=(i->'provider_pin'->>'connection_generation')::bigint + AND (CASE pc.cloud + WHEN 'digitalocean' THEN coalesce(nullif(pc.details->>'team_uuid',''),pc.details->>'account_uuid') + WHEN 'vercel' THEN coalesce(nullif(pc.details->>'team_id',''),pc.details->>'user_id') + ELSE pc.account END)=i->'provider_pin'->>'account_id' + AND pc.status='ready' + WHERE t.org_id=p.org_id AND t.id=i->'demand'->>'target_id' AND t.cloud_id=i->'demand'->>'cloud_id' AND t.pool_id=i->'demand'->>'pool_id' + AND t.provider='server' AND t.revision=(i->>'target_revision')::bigint AND a.revision=(i->>'assignment_revision')::bigint AND c.revision=(i->>'cloud_revision')::bigint AND g.revision=(i->>'grant_revision')::bigint + AND (cardinality(g.target_ids)=0 OR t.id=ANY(g.target_ids)) AND cp.enabled + AND EXISTS(SELECT 1 FROM jsonb_array_elements(cp.body->'pools') template + WHERE template->>'pool_id'=t.pool_id AND template-ARRAY['min_servers','max_servers','limits'] = (i->'template')-ARRAY['min_servers','max_servers','limits'])) ,false) $function$`}, + {"restore workload scope checks", `CREATE OR REPLACE FUNCTION public.loomplane_cluster_workload_scope_current(p loomplane_plans, d jsonb) + RETURNS boolean + LANGUAGE sql + STABLE +AS $function$ + SELECT coalesce(d->'input'->>'org_id'=p.org_id AND d->'input'->>'project_id'=p.project_id AND d->'input'->>'environment_id'=p.environment_id AND d->'input'->>'plan_id'=p.id AND EXISTS( + SELECT 1 FROM loomplane_cloud_targets t + JOIN loomplane_cloud_profiles c ON c.org_id=t.org_id AND c.id=t.cloud_id + JOIN loomplane_cloud_project_grants g ON g.org_id=t.org_id AND g.cloud_id=t.cloud_id AND g.project_id=p.project_id AND NOT g.revoked + JOIN loomplane_cloud_assignments a ON a.org_id=t.org_id AND a.project_id=p.project_id AND a.environment_id=p.environment_id AND a.cloud_id=t.cloud_id + JOIN loomplane_cloud_connections cn ON cn.org_id=t.org_id AND cn.id=t.connection_id AND cn.status='ready' AND cn.cloud='kubernetes' + JOIN loomplane_runtime_attachments rt ON rt.org_id=t.org_id AND rt.id=d->'input'->>'attachment_id' AND rt.cluster_id=t.managed_resource_id AND rt.project_id=p.project_id AND rt.runtime_connection_id=t.connection_id AND rt.deleted_at IS NULL AND rt.body->>'trust_revision'=d->'input'->>'trust_revision' AND rt.body->>'namespace_uid'=cn.details->>'namespace_uid' AND rt.body->>'trust_fingerprint'=cn.details->>'cluster_ca' + JOIN loomplane_managed_resources mr ON mr.org_id=t.org_id AND mr.id=t.managed_resource_id AND mr.deleted_at IS NULL AND mr.status NOT IN ('missing','identity_changed') + WHERE t.org_id=p.org_id AND t.id=d->'input'->>'target_id' AND t.cloud_id=d->'input'->>'cloud_id' AND t.project_id=p.project_id AND t.managed_resource_id=d->'input'->>'resource_id' AND t.connection_id=d->'input'->>'connection_id' + AND t.revision=(d->'placement'->>'target_revision')::bigint AND c.revision=(d->'placement'->>'cloud_revision')::bigint AND g.revision=(d->'placement'->>'grant_revision')::bigint AND a.revision=(d->'placement'->>'assignment_revision')::bigint AND cn.generation=(d->>'connection_generation')::bigint + AND (cardinality(g.target_ids)=0 OR t.id=ANY(g.target_ids))),false) $function$`}, + {"restore capacity plan admission", `CREATE OR REPLACE FUNCTION public.loomplane_admit_capacity_plan(candidate loomplane_plans, approved loomplane_plans) + RETURNS void + LANGUAGE plpgsql +AS $function$ +DECLARE + a JSONB; + pin JSONB; + host loomplane_cloud_servers%ROWTYPE; + member loomplane_server_pool_members%ROWTYPE; + pool loomplane_server_pools%ROWTYPE; + cpu BIGINT; + mem BIGINT; + used_cpu BIGINT; + used_mem BIGINT; +BEGIN + + + -- Order host and connection locks consistently across every accepted plan. + PERFORM 1 FROM loomplane_cloud_connections c + WHERE c.org_id=candidate.org_id AND c.id IN (SELECT x->>'connection_id' FROM jsonb_array_elements(coalesce(candidate.result->'actions','[]')) x) + ORDER BY c.id + FOR UPDATE; + PERFORM pg_advisory_xact_lock(hashtextextended('host-admission/'||identity,0)) + FROM ( + SELECT DISTINCT c.details->>'docker_id' identity + FROM loomplane_cloud_connections c + WHERE c.org_id=candidate.org_id AND c.cloud='server' AND coalesce(c.details->>'docker_id','')<>'' AND c.id IN (SELECT x->>'connection_id' FROM jsonb_array_elements(coalesce(candidate.result->'actions','[]')) x) + ORDER BY identity + ) identities; + PERFORM 1 FROM loomplane_cloud_servers s + WHERE s.org_id=candidate.org_id AND s.id IN (SELECT x->'service'->'cloud_placement'->>'server_id' FROM jsonb_array_elements(coalesce(candidate.result->'actions','[]')) x) + ORDER BY s.id + FOR UPDATE; + + FOR a IN SELECT value FROM jsonb_array_elements(coalesce(candidate.result->'actions','[]')) LOOP + IF a->>'op'='delete' OR (a->>'op'='keep' AND NOT coalesce((a->>'adopt_cloud_placement')::boolean,false)) THEN CONTINUE; END IF; + IF coalesce((a->'compensation'->>'retained')::boolean,false) THEN + IF NOT loomplane_retained_compensation(approved,a) THEN RAISE EXCEPTION 'retained compensation identity changed' USING ERRCODE='23514'; END IF; + CONTINUE; + END IF; + IF coalesce(a->'service'->'capacity_intent','null')<>'null'::jsonb THEN + IF NOT EXISTS(SELECT 1 FROM loomplane_capacity_intents i WHERE i.org_id=approved.org_id AND i.plan_id=approved.id AND i.service=a->>'name' AND i.plan_revision=approved.revision AND i.body=a->'service'->'capacity_intent') THEN + RAISE EXCEPTION 'missing approved deferred intent' USING ERRCODE='23514'; + END IF; + CONTINUE; + END IF; + pin:=a->'service'->'cloud_placement'; + IF pin ? 'allocation' AND (jsonb_typeof(pin->'allocation')<>'string' OR length(pin->>'allocation')>200 OR pin->>'allocation'<>btrim(pin->>'allocation')) THEN + RAISE EXCEPTION 'allocation must be a bounded string' USING ERRCODE='23514'; + END IF; + IF coalesce(pin->>'pool_id','')='' THEN + IF a->>'provider'='server' AND EXISTS( + SELECT 1 FROM loomplane_server_pool_members m + JOIN loomplane_cloud_servers s ON s.id=m.server_id + JOIN loomplane_cloud_connections c ON c.org_id=candidate.org_id AND c.id=a->>'connection_id' + WHERE (s.runtime_connection_id=c.id OR (coalesce(c.details->>'docker_id','')<>'' AND c.details->>'docker_id'=s.body->'health'->>'docker_id')) AND s.status NOT IN ('deleted','disconnected') + ) THEN + RAISE EXCEPTION 'pooled capacity requires a pool target' USING ERRCODE='23514'; + END IF; + CONTINUE; + END IF; + IF coalesce(candidate.result->>'cloud_sync_id','')<>'' AND NOT loomplane_accepted_pool_sync(approved) THEN + RAISE EXCEPTION 'pool sync needs its exact immutable accepted participant plan' USING ERRCODE='23514'; + END IF; + IF jsonb_array_length(coalesce(a->'routes','[]'))>0 AND ( + coalesce(pin->>'allocation','')='' OR EXISTS( + SELECT 1 FROM loomplane_bindings b + WHERE b.org_id=candidate.org_id AND b.project_id=candidate.project_id AND b.environment_id=candidate.environment_id AND b.subject='service' AND b.name=a->>'name' + AND (coalesce(b.config->'cloud_placement'->>'allocation','')=pin->>'allocation' + OR (b.config->'cloud_placement' ? 'allocation' AND jsonb_typeof(b.config->'cloud_placement'->'allocation')<>'string') + OR (coalesce(b.config->'cloud_placement'->>'pool_id','')<>'' AND NOT EXISTS(SELECT 1 FROM loomplane_capacity_reservations r WHERE r.org_id=b.org_id AND r.project_id=b.project_id AND r.environment_id=b.environment_id AND r.service=b.name AND r.plan_id=b.plan_id AND r.server_id=b.config->'cloud_placement'->>'server_id' AND r.binding_id=b.id AND r.body=b.config->'cloud_placement'))))) THEN + RAISE EXCEPTION 'routed allocation must retain the exact source and reserve a distinct candidate' USING ERRCODE='23514'; + END IF; + IF EXISTS(SELECT 1 FROM loomplane_capacity_reservations WHERE org_id=candidate.org_id AND environment_id=candidate.environment_id AND service=a->>'name' AND binding_id='' AND plan_id<>candidate.id) THEN + RAISE EXCEPTION 'recover the unresolved accepted placement before another deployment' USING ERRCODE='23514'; + END IF; + IF coalesce((pin->>'pool_revision')::bigint,0)<1 OR coalesce((pin->>'server_revision')::bigint,0)<1 OR coalesce((pin->>'connection_generation')::bigint,0)<1 + OR coalesce((pin->>'cpu_millis')::bigint,0)<1 OR coalesce((pin->>'memory_bytes')::bigint,0)<1 + OR coalesce((a->'service'->'scale'->>'min')::int,1)<>1 OR coalesce((a->'service'->'scale'->>'max')::int,1)<>1 THEN + RAISE EXCEPTION 'pool placement needs bounded resources and one replica' USING ERRCODE='23514'; + END IF; + IF EXISTS( + SELECT 1 FROM loomplane_bindings b + WHERE b.org_id=candidate.org_id AND b.environment_id=candidate.environment_id AND b.subject='service' AND b.name=a->>'name' AND coalesce(b.config->'cloud_placement'->>'server_id','')<>pin->>'server_id' + AND (coalesce(b.config->'catalog','null')<>'null'::jsonb OR (NOT loomplane_accepted_pool_sync(approved) AND NOT EXISTS(SELECT 1 FROM loomplane_placement_moves m WHERE m.org_id=b.org_id AND m.project_id=b.project_id AND m.environment_id=b.environment_id AND m.service=b.name AND m.source_server_id=b.config->'cloud_placement'->>'server_id' AND m.destination_server_id=pin->>'server_id' AND m.source_config=b.config AND m.expires_at>now()))) + ) THEN + RAISE EXCEPTION 'host relocation needs a current explicit stateless move review' USING ERRCODE='23514'; + END IF; + + SELECT * INTO host FROM loomplane_cloud_servers WHERE org_id=candidate.org_id AND id=pin->>'server_id'; + SELECT * INTO pool FROM loomplane_server_pools WHERE org_id=candidate.org_id AND cloud_id=pin->>'cloud_id' AND id=pin->>'pool_id' FOR SHARE; + SELECT * INTO member FROM loomplane_server_pool_members WHERE org_id=candidate.org_id AND pool_id=pool.id AND server_id=host.id; + IF host.id IS NULL OR pool.id IS NULL OR member.server_id IS NULL OR host.status<>'ready' OR host.revision<>(pin->>'server_revision')::bigint OR pool.revision<>(pin->>'pool_revision')::bigint + OR host.runtime_connection_id<>pin->>'connection_id' OR a->>'connection_id'<>pin->>'connection_id' OR a->>'provider'<>'server' THEN + RAISE EXCEPTION 'pool placement changed; review again' USING ERRCODE='23514'; + END IF; + IF (coalesce((host.body->>'draining')::boolean,false) OR EXISTS(SELECT 1 FROM loomplane_server_pool_members WHERE server_id=host.id AND draining)) + AND NOT EXISTS(SELECT 1 FROM loomplane_bindings WHERE org_id=candidate.org_id AND environment_id=candidate.environment_id AND subject='service' AND name=a->>'name' AND config->'cloud_placement'->>'server_id'=host.id) THEN + RAISE EXCEPTION 'server is draining' USING ERRCODE='23514'; + END IF; + IF (host.body->'health'->>'checked_at')::timestamptz < now()-interval '15 minutes' OR (host.body->'health'->>'checked_at')::timestamptz > now()+interval '1 minute' + OR coalesce((host.body->'health'->>'effective_cpu_millis')::bigint,0)'health'->>'effective_memory_bytes')::bigint,0)>'connection_generation')::bigint) THEN + RAISE EXCEPTION 'runtime connection changed' USING ERRCODE='23514'; + END IF; + + PERFORM 1 FROM loomplane_cloud_project_grants WHERE org_id=candidate.org_id AND cloud_id=pin->>'cloud_id' AND project_id=candidate.project_id FOR SHARE; + PERFORM 1 FROM loomplane_cloud_targets WHERE org_id=candidate.org_id AND id=pin->>'target_id' FOR SHARE; + PERFORM 1 FROM loomplane_cloud_assignments WHERE org_id=candidate.org_id AND environment_id=candidate.environment_id FOR SHARE; + PERFORM 1 FROM loomplane_cloud_profiles WHERE org_id=candidate.org_id AND id=pin->>'cloud_id' FOR SHARE; + IF NOT EXISTS( + SELECT 1 FROM loomplane_cloud_targets t + JOIN loomplane_cloud_project_grants g ON g.org_id=t.org_id AND g.cloud_id=t.cloud_id AND g.project_id=candidate.project_id AND NOT g.revoked + JOIN loomplane_cloud_assignments ca ON ca.org_id=t.org_id AND ca.project_id=candidate.project_id AND ca.environment_id=candidate.environment_id AND ca.cloud_id=t.cloud_id + JOIN loomplane_cloud_profiles c ON c.org_id=t.org_id AND c.id=t.cloud_id + WHERE t.org_id=candidate.org_id AND t.id=pin->>'target_id' AND t.pool_id=pool.id AND t.revision=(pin->>'target_revision')::bigint AND ca.revision=(pin->>'assignment_revision')::bigint + AND c.revision=(pin->>'cloud_revision')::bigint AND g.revision=(pin->>'grant_revision')::bigint AND (cardinality(g.target_ids)=0 OR t.id=ANY(g.target_ids)) + ) THEN + RAISE EXCEPTION 'pool target authority changed' USING ERRCODE='23514'; + END IF; + + cpu:=coalesce((a->'service'->'size'->>'cpu')::numeric*1000,1000); + mem:=coalesce((a->'service'->'size'->>'memory')::bigint*1048576,536870912); + IF cpu<=0 OR mem<=0 OR cpu<>(pin->>'cpu_millis')::bigint OR mem<>(pin->>'memory_bytes')::bigint THEN + RAISE EXCEPTION 'capacity differs from runtime limits' USING ERRCODE='23514'; + END IF; + SELECT c.cpu,c.memory INTO used_cpu,used_mem + FROM loomplane_server_capacity(host.id,candidate.environment_id,jsonb_build_array(jsonb_build_object('service',a->>'name','server_id',host.id,'allocation',coalesce(pin->>'allocation',''),'cpu_millis',cpu,'memory_bytes',mem))) c; + IF used_cpu>member.cpu_millis OR used_mem>member.memory_bytes THEN + RAISE EXCEPTION 'insufficient reserved host capacity' USING ERRCODE='23514'; + END IF; + INSERT INTO loomplane_capacity_reservations(org_id,project_id,environment_id,service,plan_id,pool_id,server_id,connection_id,cpu_millis,memory_bytes,body) + VALUES(candidate.org_id,candidate.project_id,candidate.environment_id,a->>'name',candidate.id,pool.id,host.id,host.runtime_connection_id,cpu,mem,pin) + ON CONFLICT DO NOTHING; + END LOOP; + + RETURN; +END $function$`}, + {"drop the Cloud delete guard", `DROP TRIGGER IF EXISTS loomplane_cloud_profile_delete ON loomplane_cloud_profiles`}, + {"drop the Cloud delete guard function", `DROP FUNCTION IF EXISTS loomplane_cloud_profile_delete_guard()`}, + {"drop the default Cloud event", `DROP TRIGGER IF EXISTS loomplane_project_cloud_event ON loomplane_cloud_project_grants`}, + {"drop the default Cloud event function", `DROP FUNCTION IF EXISTS loomplane_project_cloud_event_trigger()`}, + {"drop the default guard", `DROP TRIGGER IF EXISTS loomplane_cloud_default ON loomplane_cloud_project_grants`}, + {"drop the default guard function", `DROP FUNCTION IF EXISTS loomplane_cloud_default_guard()`}, + {"drop the default index", `DROP INDEX IF EXISTS loomplane_cloud_project_default`}, + {"drop the default flag", `ALTER TABLE loomplane_cloud_project_grants DROP COLUMN IF EXISTS is_default`}, +} diff --git a/database/migrations/project_default_cloud_test.go b/database/migrations/project_default_cloud_test.go new file mode 100644 index 000000000..7b3c14731 --- /dev/null +++ b/database/migrations/project_default_cloud_test.go @@ -0,0 +1,101 @@ +//go:build integration + +package migrations + +import ( + "slices" + "testing" + + "github.com/xraph/grove/migrate" +) + +func TestProjectDefaultCloudMigration(t *testing.T) { + conn, ex := scratch(t) + ctx := t.Context() + before := migrate.NewGroup(GroupName) + for _, step := range Group().Migrations() { + if step.Name != "project_default_cloud" { + before.MustRegister(step) + } + } + if _, err := migrate.NewOrchestrator(ex, before).Migrate(ctx); err != nil { + t.Fatalf("up others: %v", err) + } + + // Project p runs prod and staging on Cloud a and preview on Cloud b, so + // a becomes its default. Project q's only assigned Cloud lost its grant, + // so q gets no default. + exec(t, conn, + `INSERT INTO loomplane_projects(id,org_id,name,slug,status,created_by,created_at,updated_at) VALUES('p','o','P','p','ready','u',now(),now()),('q','o','Q','q','ready','u',now(),now())`, + `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('prod','o','p','prod','production',now(),now()),('staging','o','p','staging','preview',now(),now()),('preview','o','p','preview','preview',now(),now()),('qprod','o','q','prod','production',now(),now())`, + `INSERT INTO loomplane_cloud_profiles(id,org_id,project_id,name,revision,created_at,updated_at) VALUES('a','o','p','A',1,now(),now()),('b','o','p','B',1,now(),now())`, + `INSERT INTO loomplane_cloud_project_grants(org_id,cloud_id,project_id,target_ids,revoked) VALUES('o','a','p','{}',false),('o','b','p','{}',false),('o','a','q','{}',false)`, + `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('o','p','prod','a',1),('o','p','staging','a',1),('o','p','preview','b',1),('o','q','qprod','a',1)`, + `UPDATE loomplane_cloud_project_grants SET revoked=true,revision=revision+1 WHERE project_id='q'`, + ) + revisions := func() []string { + return strs(t, conn, `SELECT project_id||'/'||cloud_id||'='||revision FROM loomplane_cloud_project_grants ORDER BY 1`) + } + pinned := revisions() + + o := migrate.NewOrchestrator(ex, Group()) + if _, err := o.Migrate(ctx); err != nil { + t.Fatalf("up: %v", err) + } + defaults := func() []string { + return strs(t, conn, `SELECT project_id||'/'||cloud_id FROM loomplane_cloud_project_grants WHERE is_default ORDER BY 1`) + } + if got := defaults(); !slices.Equal(got, []string{"p/a"}) { + t.Fatalf("defaults = %v, want p/a only", got) + } + // Marking the default left every revision a plan pinned where it was. + if got := revisions(); !slices.Equal(got, pinned) { + t.Fatalf("revisions moved: %v, want %v", got, pinned) + } + if got := strs(t, conn, `SELECT table_name FROM information_schema.tables WHERE table_name='loomplane_cloud_assignments'`); len(got) != 0 { + t.Fatalf("the assignment table survived: %v", got) + } + + for _, sql := range []string{ + // One live default per project. + `UPDATE loomplane_cloud_project_grants SET is_default=true,revision=revision+1 WHERE project_id='p' AND cloud_id='b'`, + // A revoked grant can't be asked to be the default. + `INSERT INTO loomplane_cloud_project_grants(org_id,cloud_id,project_id,target_ids,revoked,is_default) VALUES('o','b','q','{}',true,true)`, + } { + if _, err := conn.Exec(ctx, sql); err == nil { + t.Fatalf("constraint accepted %s", sql) + } + } + // Switching is one transaction: clear the old default, set the new. + exec(t, conn, `BEGIN`, + `UPDATE loomplane_cloud_project_grants SET is_default=false,revision=revision+1 WHERE project_id='p' AND cloud_id='a'`, + `UPDATE loomplane_cloud_project_grants SET is_default=true,revision=revision+1 WHERE project_id='p' AND cloud_id='b'`, + `COMMIT`) + if got := defaults(); !slices.Equal(got, []string{"p/b"}) { + t.Fatalf("after switch = %v, want p/b", got) + } + if got := strs(t, conn, `SELECT data->>'cloud_id' FROM loomplane_events WHERE type='project_cloud.updated' ORDER BY sequence DESC LIMIT 1`); !slices.Equal(got, []string{"b"}) { + t.Fatalf("last project_cloud.updated names %v, want b", got) + } + // Revoking the default grant, however it's written, ends the default. + exec(t, conn, `UPDATE loomplane_cloud_project_grants SET revoked=true,revision=revision+1 WHERE project_id='p' AND cloud_id='b'`) + if got := defaults(); len(got) != 0 { + t.Fatalf("revoked grant stayed default: %v", got) + } + exec(t, conn, `UPDATE loomplane_cloud_project_grants SET revoked=false,is_default=true,revision=revision+1 WHERE project_id='p' AND cloud_id='b'`) + + res, err := o.Rollback(ctx) + if err != nil || len(res.Rollback) != 1 || res.Rollback[0].Name != "project_default_cloud" { + t.Fatalf("down: %+v %v", res, err) + } + // Every environment of p takes p's default; q had none. + if got := strs(t, conn, `SELECT environment_id||'='||cloud_id FROM loomplane_cloud_assignments ORDER BY 1`); !slices.Equal(got, []string{"preview=b", "prod=b", "staging=b"}) { + t.Fatalf("assignments after down = %v", got) + } + if _, err = o.Migrate(ctx); err != nil { + t.Fatalf("up again: %v", err) + } + if got := defaults(); !slices.Equal(got, []string{"p/b"}) { + t.Fatalf("defaults after up again = %v, want p/b", got) + } +} diff --git a/extensions/cloudinfra/clusters.go b/extensions/cloudinfra/clusters.go index 7af9e7df0..00cda7ca8 100644 --- a/extensions/cloudinfra/clusters.go +++ b/extensions/cloudinfra/clusters.go @@ -133,7 +133,14 @@ func (e *Extension) clusterRoutes(r forge.Router, guard identity.Guard) error { opts = append(opts, forge.WithRequestSchema(rt.request)) } if rt.method == http.MethodPost { - opts = append(opts, forge.WithInvalidates("CloudCluster", "CloudClusterOperation", "CloudClusterPage", "CloudClusterOperationPage", "RuntimeAttachmentPage")) + // Every write changes what the cluster and operation lists show. + // A write about an existing cluster names it in its response; a + // preview of a new one has no resource yet. + tags := []string{"CloudCluster[]", "CloudClusterOperation[]"} + if rt.name != "cloudClusters.preview" { + tags = append(tags, "CloudCluster:{res.resourceId}", "RuntimeAttachmentPage:{res.resourceId}") + } + opts = append(opts, forge.WithInvalidates(tags...)) } var err error if rt.method == http.MethodGet { diff --git a/extensions/discovery/bitbucket.go b/extensions/discovery/bitbucket.go index 9edb3416a..2885f8755 100644 --- a/extensions/discovery/bitbucket.go +++ b/extensions/discovery/bitbucket.go @@ -59,7 +59,7 @@ func (e *Extension) bitbucketRoutes(r forge.Router, guard identity.Guard) error forge.WithName("bitbucket.disconnect"), forge.WithSummary("Disconnect a workspace. The consumer stays approved on Bitbucket."), forge.WithNoContentResponse(), - forge.WithEntity(forge.EntityDef{Type: "BitbucketWorkspace", IDField: "id"}), + forge.WithEntity(forge.EntityDef{Type: "BitbucketWorkspaceView", IDField: "id"}), ); err != nil { return err } diff --git a/extensions/discovery/routes.go b/extensions/discovery/routes.go index 6676c5f5d..f3bb486f9 100644 --- a/extensions/discovery/routes.go +++ b/extensions/discovery/routes.go @@ -113,7 +113,7 @@ func (e *Extension) sourceRoutes(r forge.Router, guard identity.Guard) error { forge.WithName("sources.delete"), forge.WithSummary("Detach a source. Its alias stays taken, so old plans keep their meaning."), forge.WithNoContentResponse(), - forge.WithEntity(forge.EntityDef{Type: "Source", IDField: "id"}), + forge.WithEntity(forge.EntityDef{Type: "DiscoverySource", IDField: "id"}), ) } diff --git a/extensions/planning/clouds.go b/extensions/planning/clouds.go index ddb2a330a..ecf4b8dd8 100644 --- a/extensions/planning/clouds.go +++ b/extensions/planning/clouds.go @@ -36,14 +36,25 @@ type CloudSyncList struct { func (CloudSyncList) ForgeEnvelope() forge.EnvelopeDef { return forge.EnvelopeDef{ItemsField: "syncs"} } -// EnvironmentCloud distinguishes an unassigned environment from missing scope. -type EnvironmentCloud struct { - Assignment *cloudprofiles.Assignment `json:"assignment" nullable:"true" required:"true"` - Revision int64 `json:"revision"` +// DefaultCloud is the Cloud every environment of a project uses unless a +// service names another. Cloud is null when the project has none. Revision +// is the token a reviewed change compares against: the default's grant +// revision, or zero for none. +type DefaultCloud struct { + ProjectID string `json:"project_id"` + Cloud *cloudprofiles.ProjectCloud `json:"cloud" nullable:"true" required:"true"` + Revision int64 `json:"revision"` } -// EnvironmentCloudInput reviews a Cloud assignment at the current generation. -type EnvironmentCloudInput struct { +// ForgeEntity keys the read by project, so a project_cloud.updated event +// reaches it. +func (DefaultCloud) ForgeEntity() forge.EntityDef { + return forge.EntityDef{Type: "DefaultCloud", IDField: "project_id"} +} + +// DefaultCloudInput reviews making a Cloud the project's default, or with no +// Cloud, leaving the project without one. +type DefaultCloudInput struct { CloudID string `json:"cloud_id"` Revision int64 `json:"revision"` } @@ -84,7 +95,7 @@ func (e *Extension) cloudRoutes(r forge.Router, guard identity.Guard) error { const target = targets + "/:targetId" const syncs = base + "/cloud-syncs" const sync = syncs + "/:syncId" - const assignment = base + "/environments/:environmentId/cloud" + const defaultCloud = base + "/default-cloud" routes := append(e.cloudLocationRoutes(), []cloudRoute{ {http.MethodGet, "/clouds", "organizationClouds.list", e.listClouds, nil, CloudList{}, http.StatusOK}, {http.MethodPost, "/clouds", "organizationClouds.create", e.createCloud, cloudprofiles.CreateInput{}, cloudprofiles.Profile{}, http.StatusCreated}, @@ -126,8 +137,8 @@ func (e *Extension) cloudRoutes(r forge.Router, guard identity.Guard) error { {http.MethodDelete, target, "cloudTargets.delete", e.deleteCloudTarget, nil, nil, http.StatusNoContent}, {http.MethodPost, base + "/cloud-changes/preview", "cloudChanges.preview", e.previewCloudChange, cloudprofiles.ChangeInput{}, cloudprofiles.Preview{}, http.StatusOK}, {http.MethodPost, base + "/cloud-changes/apply", "cloudChanges.apply", e.applyCloudChange, ApplyCloudInput{}, cloudprofiles.Sync{}, http.StatusAccepted}, - {http.MethodGet, assignment, "environmentClouds.get", e.getEnvironmentCloud, nil, EnvironmentCloud{}, http.StatusOK}, - {http.MethodPost, assignment + "/preview", "environmentClouds.preview", e.previewEnvironmentCloud, EnvironmentCloudInput{}, cloudprofiles.Preview{}, http.StatusOK}, + {http.MethodGet, defaultCloud, "defaultCloud.get", e.getDefaultCloud, nil, DefaultCloud{}, http.StatusOK}, + {http.MethodPost, defaultCloud + "/preview", "defaultCloud.preview", e.previewDefaultCloud, DefaultCloudInput{}, cloudprofiles.Preview{}, http.StatusOK}, {http.MethodGet, syncs, "cloudSyncs.list", e.listCloudSyncs, nil, CloudSyncList{}, http.StatusOK}, {http.MethodGet, sync, "cloudSyncs.get", e.getCloudSync, nil, cloudprofiles.Sync{}, http.StatusOK}, {http.MethodPost, sync + "/retry", "cloudSyncs.retry", e.retryCloudSync, nil, cloudprofiles.Sync{}, http.StatusAccepted}, @@ -268,19 +279,24 @@ func (e *Extension) deleteCloudTarget(c forge.Context) error { return nil, e.cloudProfiles.DeleteTarget(ctx, p, c.Param("id"), c.Param("cloudId"), c.Param("targetId")) }) } -func (e *Extension) getEnvironmentCloud(c forge.Context) error { +func (e *Extension) getDefaultCloud(c forge.Context) error { return cloudCall(c, http.StatusOK, func(ctx context.Context, p security.Principal) (any, error) { - a, revision, err := e.cloudProfiles.EnvironmentCloud(ctx, p, c.Param("id"), c.Param("environmentId")) - return EnvironmentCloud{Assignment: a, Revision: revision}, err + project := c.Param("id") + cloud, err := e.cloudProfiles.DefaultCloud(ctx, p, project) + out := DefaultCloud{ProjectID: project, Cloud: cloud} + if cloud != nil { + out.Revision = cloud.GrantRevision + } + return out, err }) } -func (e *Extension) previewEnvironmentCloud(c forge.Context) error { - in, err := cloudBody[EnvironmentCloudInput](c) +func (e *Extension) previewDefaultCloud(c forge.Context) error { + in, err := cloudBody[DefaultCloudInput](c) if err != nil { return err } return cloudCall(c, http.StatusOK, func(ctx context.Context, p security.Principal) (any, error) { - return e.plans.PreviewCloudChange(ctx, p, c.Param("id"), cloudprofiles.ChangeInput{EnvironmentID: c.Param("environmentId"), CloudID: in.CloudID, Revision: in.Revision}) + return e.plans.PreviewCloudChange(ctx, p, c.Param("id"), cloudprofiles.ChangeInput{ProjectDefault: true, CloudID: in.CloudID, Revision: in.Revision}) }) } func (e *Extension) previewCloudChange(c forge.Context) error { diff --git a/extensions/realtime/filter_test.go b/extensions/realtime/filter_test.go index 1e434d139..1a188169f 100644 --- a/extensions/realtime/filter_test.go +++ b/extensions/realtime/filter_test.go @@ -41,7 +41,7 @@ func TestFilter_requiresDeploymentReadForLogsAndLimitsSelectedProjects(t *testin } func TestFilterCloudEventsRequireTheirResourcePermissions(t *testing.T) { - input := []store.Event{{ProjectID: "proj_a", Type: "cloud.updated"}, {ProjectID: "proj_a", Type: "cloud_target.updated"}, {ProjectID: "proj_a", Type: "environment_cloud.updated"}, {ProjectID: "proj_a", Type: "cloud_sync.updated"}, {ProjectID: "proj_b", Type: "cloud_sync.updated"}} + input := []store.Event{{ProjectID: "proj_a", Type: "cloud.updated"}, {ProjectID: "proj_a", Type: "cloud_target.updated"}, {ProjectID: "proj_a", Type: "project_cloud.updated"}, {ProjectID: "proj_a", Type: "cloud_sync.updated"}, {ProjectID: "proj_b", Type: "cloud_sync.updated"}} p := security.Principal{OrgID: "org_a", UserID: "usr_a"} sub := Subscription{ProjectIDs: []string{"proj_a"}} for denied, want := range map[security.Permission]int{security.CloudAccountRead: 1, security.DeploymentRead: 3} { diff --git a/extensions/realtime/handlers.go b/extensions/realtime/handlers.go index 48581f26b..c03a282c9 100644 --- a/extensions/realtime/handlers.go +++ b/extensions/realtime/handlers.go @@ -55,7 +55,7 @@ func permission(event string) security.Permission { return security.DeploymentRead case "binding": return security.InfrastructureRead - case "connection", "cloud", "cloud_target", "environment_cloud": + case "connection", "cloud", "cloud_target", "project_cloud": return security.CloudAccountRead case "node": return security.NodeRead diff --git a/extensions/realtime/routes.go b/extensions/realtime/routes.go index beed55490..81ca5ebfb 100644 --- a/extensions/realtime/routes.go +++ b/extensions/realtime/routes.go @@ -53,20 +53,20 @@ func streamBindings() forge.RouteOption { forge.Emits[planning.Binding]("binding.updated").As(forge.StreamUpsert).Invalidates("Binding[]", "Instance[]"), forge.Emits[planning.Binding]("binding.deleted"), forge.Emits[connections.Connection]("connection.updated").As(forge.StreamUpsert), forge.Emits[connections.Connection]("connection.deleted"), forge.Emits[deployments.Deployment]("deployment.updated").As(forge.StreamUpsert).Invalidates("Deployment[]", "Instance[]"), forge.Emits[deployments.Deployment]("deployment.deleted"), - forge.Emits[deployments.CanaryVerdict]("canary_verdict.updated").As(forge.StreamUpsert).Invalidates("CanaryReport"), forge.Emits[deployments.CanaryVerdict]("canary_verdict.deleted").Invalidates("CanaryReport"), + forge.Emits[deployments.CanaryVerdict]("canary_verdict.updated").As(forge.StreamUpsert), forge.Emits[deployments.CanaryVerdict]("canary_verdict.deleted"), forge.Emits[releasewatch.Watch]("release_watch.updated").As(forge.StreamUpsert), forge.Emits[releasewatch.Watch]("release_watch.deleted"), forge.Emits[cloudprofiles.Profile]("cloud.updated").As(forge.StreamUpsert), forge.Emits[cloudprofiles.Profile]("cloud.deleted"), forge.Emits[cloudprofiles.Target]("cloud_target.updated").As(forge.StreamUpsert), forge.Emits[cloudprofiles.Target]("cloud_target.deleted"), - forge.Emits[cloudprofiles.EnvironmentCloudEvent]("environment_cloud.updated").Invalidates("EnvironmentCloud"), - forge.Emits[cloudprofiles.CloudSyncEvent]("cloud_sync.updated").Invalidates("Sync", "Sync[]", "EnvironmentCloud"), - forge.Emits[cloudinfra.ClusterChange]("cloud_cluster.updated").Invalidates("CloudCluster", "CloudClusterPage", "CloudClusterOperation", "CloudClusterOperationPage", "Target", "Target[]", "Connection", "Connection[]", "Profile", "Profile[]"), - forge.Emits[cloudinfra.CapacityChange]("cloud_capacity.updated").Invalidates("CapacityPolicyView:{cloud_id}", "CapacityUsage:{cloud_id}", "Expansion[]"), - forge.Emits[notifications.NotificationCreated]("notification.created").Invalidates("NotificationList"), + forge.Emits[cloudprofiles.ProjectCloudEvent]("project_cloud.updated").Invalidates("DefaultCloud:{projectId}"), + forge.Emits[cloudprofiles.CloudSyncEvent]("cloud_sync.updated").Invalidates("Sync:{id}", "Sync[]", "DefaultCloud:{projectId}"), + forge.Emits[cloudinfra.ClusterChange]("cloud_cluster.updated").Invalidates("CloudCluster:{resourceId}", "CloudCluster[]", "CloudClusterOperation:{operationId}", "CloudClusterOperation[]", "CloudprofilesTarget[]", "Connection[]", "Profile:{cloudId}"), + forge.Emits[cloudinfra.CapacityChange]("cloud_capacity.updated").Invalidates("CapacityPolicyView:{cloudId}", "CapacityUsage:{cloudId}", "Expansion[]"), + forge.Emits[notifications.NotificationCreated]("notification.created").Invalidates("Notification[]"), forge.Emits[nodes.Node]("node.updated").As(forge.StreamUpsert), - forge.Emits[agentruns.TaskEvent]("agent_task.updated").As(forge.StreamUpsert).Invalidates("AgentTask", "AgentTask[]"), forge.Emits[agentruns.TaskEvent]("agent_task.deleted"), - forge.Emits[agentreports.Report]("agent_report.updated").As(forge.StreamUpsert).Invalidates("AgentReport", "AgentReport[]"), forge.Emits[agentreports.Report]("agent_report.deleted"), - forge.Emits[agentrequests.RequestEvent]("agent_request.updated").As(forge.StreamUpsert).Invalidates("AgentRequest", "AgentRequest[]"), forge.Emits[agentrequests.RequestEvent]("agent_request.deleted"), - forge.Emits[releaseprep.ReleaseReportEvent]("release_report.updated").As(forge.StreamUpsert).Invalidates("ReleaseReport", "ReleaseReport[]"), forge.Emits[releaseprep.ReleaseReportEvent]("release_report.deleted").Invalidates("ReleaseReport", "ReleaseReport[]"), + forge.Emits[agentruns.TaskEvent]("agent_task.updated").As(forge.StreamPatch).Invalidates("Task:{id}"), forge.Emits[agentruns.TaskEvent]("agent_task.deleted").As(forge.StreamPatch).Invalidates("Task:{id}"), + forge.Emits[agentreports.Report]("agent_report.updated").As(forge.StreamUpsert), forge.Emits[agentreports.Report]("agent_report.deleted"), + forge.Emits[agentrequests.RequestEvent]("agent_request.updated").As(forge.StreamPatch).Invalidates("Request:{id}", "Request[]"), forge.Emits[agentrequests.RequestEvent]("agent_request.deleted").As(forge.StreamPatch).Invalidates("Request:{id}", "Request[]"), + forge.Emits[releaseprep.ReleaseReportEvent]("release_report.updated").As(forge.StreamPatch).Invalidates("ReleaseReport:{id}", "ReleaseReport[]"), forge.Emits[releaseprep.ReleaseReportEvent]("release_report.deleted").As(forge.StreamPatch).Invalidates("ReleaseReport:{id}", "ReleaseReport[]"), forge.Emits[store.Log]("build.log").As(forge.StreamUpsert), forge.Emits[store.Collection]("build.collection").As(forge.StreamUpsert), ) } @@ -92,7 +92,7 @@ func (e *Extension) routes(router forge.Router) error { "deployment.updated": deployments.Deployment{}, "deployment.deleted": deployments.Deployment{}, "canary_verdict.updated": deployments.CanaryVerdict{}, "canary_verdict.deleted": deployments.CanaryVerdict{}, "release_watch.updated": releasewatch.Watch{}, "release_watch.deleted": releasewatch.Watch{}, "build.log": store.Log{}, "build.collection": store.Collection{}, "cloud.updated": cloudprofiles.Profile{}, "cloud.deleted": cloudprofiles.Profile{}, "cloud_target.updated": cloudprofiles.Target{}, "cloud_target.deleted": cloudprofiles.Target{}, - "environment_cloud.updated": cloudprofiles.EnvironmentCloudEvent{}, "cloud_sync.updated": cloudprofiles.CloudSyncEvent{}, + "project_cloud.updated": cloudprofiles.ProjectCloudEvent{}, "cloud_sync.updated": cloudprofiles.CloudSyncEvent{}, "cloud_cluster.updated": cloudinfra.ClusterChange{}, "cloud_capacity.updated": cloudinfra.CapacityChange{}, "notification.created": notifications.NotificationCreated{}, "node.updated": nodes.Node{}, "agent_task.updated": agentruns.TaskEvent{}, "agent_task.deleted": agentruns.TaskEvent{}, "agent_request.updated": agentrequests.RequestEvent{}, "agent_request.deleted": agentrequests.RequestEvent{}, "agent_report.updated": agentreports.Report{}, "agent_report.deleted": agentreports.Report{}, diff --git a/internal/agentknowledge/docs.json b/internal/agentknowledge/docs.json index 8e36c8474..72c06667b 100644 --- a/internal/agentknowledge/docs.json +++ b/internal/agentknowledge/docs.json @@ -1,6 +1,6 @@ { "version": 1, - "digest": "b9ea5ce3714b7121df8706b63d14b2e042b2fe48db1e875bfe9bad92cd76d48b", + "digest": "e2a66a6c616f22e646dd4571696bf4300f962d26862e26eeafa65832e930b41b", "pages": [ { "path": "", @@ -84,7 +84,7 @@ "title": "Models", "description": "Browse the model registry, deploy a model in one click on a GPU or a server you have, run it in more than one environment, link services to it, and move or remove it later.", "url": "https://www.loomplane.com/docs/ai/models", - "text": "Open **AI**, then **Models**. The **Registry** tab lists the open models Loomplane knows how to serve, and the **Deployed** tab lists the ones running in your projects, with what each costs per hour and this month.\n\nA model you deploy belongs to one project and runs in the environments you deploy it to, each environment running its own copy on a server or cluster you connected, or on a DigitalOcean GPU server Loomplane creates for it. Services in an environment link to that environment's copy and call it with `MODEL_URL` and `MODEL_API_KEY`.\n\n## The registry\n\nEach card shows the model's publisher, its size in parameters, its context window, its license, what it does (chat, reasoning, code, vision, embeddings, reranking or speech to text) and what it needs to run, such as \"Needs 22 GB GPU, or runs on CPU\". A badge says how sure Loomplane is that it runs, which the next section explains.\n\nSearch by name, or narrow the list:\n\n- **Task**, **Size** (under 4B up to over 100B parameters) and **License**.\n- **Commercial use only** keeps models whose license Loomplane knows and that allow commercial use. A license it doesn't know never counts.\n- **Fits my GPUs** keeps models that fit a GPU or a server your workspace has, or a GPU server it can create. If Loomplane can't read your targets, it says \"Couldn't check your GPUs.\" and shows everything.\n- **Tested only** keeps models a qualification run served.\n\nOpen a card for the model's page. It lists each quantization (the weights Loomplane can serve, each pinned to a Hugging Face commit), where each one fits, the license, and the model card from Hugging Face. **Deploy** is there and on the card.\n\nEvery entry and every quantization is pinned to a 40-character commit SHA, never to `main`, so the weights you deploy today are the weights you deploy next month.\n\n## Tested, estimated, failed and untested\n\nEvery model, and every GPU it might run on, carries one of these:\n\n| Badge | What it means |\n|---|---|\n| **Tested on** a GPU | Loomplane's qualification job deployed this quantization on that GPU kind, with the engine version Loomplane ships, and served real requests from it |\n| **Estimated** | The memory math says it fits. Nobody has run it there |\n| **Failed on** a GPU | A qualification run on that GPU failed. Loomplane won't offer it there, whatever the math says |\n| **Untested** | You pasted it from Hugging Face. No qualification run will ever check it |\n| **Doesn't fit** | The memory math says it won't fit, with the reason |\n\nAn estimate never reads as tested. A test counts only for the GPU kind it ran on, the engine version Loomplane ships today and the weights revision the registry pins. When Loomplane moves to a new engine release, or the registry re-pins a model's weights, its fits go back to **Estimated** until a run proves them again. A passed run at a shorter context than Loomplane would serve proves nothing about the longer one, so that doesn't count either.\n\n### How models get tested\n\nThe qualification job runs in Loomplane's own CI, in a DigitalOcean account kept for it alone, never in your workspace or with your credentials. Once a week it creates one GPU Droplet (the GPU kind rotates through the RTX 4000 Ada, the L40S and the H100), starts a sample of registry models on it with the engines Loomplane ships, and calls each one the way your service would: a streamed chat completion, an embedding of the right length, a rerank, a transcription. Then it deletes the Droplet. Each result records the GPU, the GPU count, the context, the engine version and what it measured, or why it failed, and the results ship in the next Loomplane release. Results older than 30 days are run again.\n\nUntil a run covers a model, it reads **Estimated**, which is what the memory math alone can promise.\n\n### How fit is estimated\n\nFor vLLM, the memory one GPU needs is:\n\n- the weights, divided by the number of GPUs,\n- plus the KV cache for the context, at 2 bytes a value, split across GPUs only as far as the model's KV heads allow,\n- plus overhead: 1.5 GiB (1 GiB for embedding and rerank models), 8% of that GPU's share of the weights, and another 1 GiB for vision and speech models' encoders.\n\nThat has to fit in 90% of the GPU's memory, since vLLM gets `--gpu-memory-utilization 0.90`. Loomplane tries 1, 2, 4 and then 8 GPUs and takes the smallest count that fits. It serves the longest context that fits, rounded down to a multiple of 1024, at least 4096 tokens (or the model's own limit if that's shorter) and at most 32,768. Embedding and rerank models keep no KV cache and serve up to 8,192 tokens.\n\nHere's an 8B model with 16 GiB of bf16 weights, 32 layers, 8 KV heads and a head size of 128. Each token of context takes 128 KiB of KV cache. On an NVIDIA L4 (24 GiB, so 21.6 GiB usable) the overhead is 2.78 GiB, and at 4,096 tokens the model needs 16 + 0.5 + 2.78 = 19.28 GiB. It fits. The room left over holds 23,101 tokens, so Loomplane serves 22,528. On an RTX 4000 Ada (20 GiB, 18 GiB usable) it doesn't fit on one GPU. Its card says \"Needs 22 GB GPU\", which is 19.28 divided by 0.9, rounded up.\n\nThe GPU also has to be new enough. vLLM needs CUDA compute capability 7.5, which rules out the V100, and `fp8` and `mxfp4` weights need 8.0, which rules out the T4 as well. llama.cpp runs on 6.1 and up. A GPU kind Loomplane has no compute capability for never fits.\n\nOn CPU, a model needs 1.1 times its weights, plus its KV cache, plus 0.5 GiB. That has to fit in 3.5 GiB for Text Embeddings Inference and 7 GiB for llama.cpp, which leaves the operating system room in the 4,096 MB and 8,192 MB those containers reserve. llama.cpp on CPU serves 8,192 tokens.\n\n## The engines\n\nLoomplane runs each model with one of three inference servers, picked by the quantization:\n\n| Engine | Runs on | Serves | Manifest kind |\n|---|---|---|---|\n| vLLM 0.31 | NVIDIA GPU | Chat, reasoning, code, vision, embeddings and speech to text, from safetensors | `model-vllm` |\n| Text Embeddings Inference 1.9 | CPU | Embedding and rerank models | `model-tei` |\n| llama.cpp b11580 | CPU or NVIDIA GPU | Models as a single GGUF file (`Q8_0`, `MXFP4` or `Q4_K_M`) | `model-llamacpp`, `model-llamacpp-gpu` |\n\nA model that has both kinds of quantization gives you a **GPU** and **CPU** switch in the deploy dialog. Images are pinned by digest. The GPU images are amd64 only, so a GPU model can't run on an Arm server.\n\n## Deploy a model\n\n\nChoose **Deploy** on a card or a model's page.\n\n\nUnder **Where**, pick the project and the environment. The dialog says \"Runs in staging. Services in staging can link to it.\" The project needs a saved manifest first.\n\nTo add an environment to a model that's already deployed, open its page and choose **Deploy to another environment**. You get the same dialog for the same model, and the environments it runs in already read \"(runs there)\" and can't be picked.\n\n\nPick where it runs. For a GPU model the list shows your connected servers and clusters with GPUs, how many are free (or how many a cluster has per node) and what they cost, and, when the environment's Cloud has a DigitalOcean account, GPU server sizes Loomplane can create, marked **New server**. A target the model doesn't fit says why and can't be picked. For a CPU model, pick a ready server or cluster.\n\n\nPick a quantization, or leave it and Loomplane takes the first that fits. Set **Context in tokens**, or leave it for the most that fits, up to 32,768. **Budget alert** is optional; see [What models cost](/docs/ai/model-costs).\n\n\nRead the summary at the bottom: what it costs per hour and roughly per month, and anything that stops the deploy. Then choose **Plan it**.\n\n\nNothing runs before that. **Plan it** adds the model to the project's `loomplane.yaml` and plans the environment, and the plan waits for approval like any other. Once it's approved, the engine downloads the weights and loads them, which for a big model takes a while. Loomplane waits up to two hours for vLLM, an hour for llama.cpp and 30 minutes for Text Embeddings Inference before it calls a start failed.\n\nYou need `ai:edit` to deploy to an environment that isn't production, and `ai:manage` for production. The dialog tells you when you can't.\n\nA model already running in that environment is refused (\"llm already runs Qwen2.5 7B Instruct in staging.\"). Deploying a model the project already runs to another environment adds that environment to the same resource: the dialog says \"Adds production to llm.\", and production gets its own copy on the server you pick, with its own key, cost and budget. The copy has to run on the same engine as the others. Pick a CPU server for a model that runs on vLLM in staging and the dialog refuses it, and tells you to pick a target the model runs on as it is, or deploy it as a separately named model.\n\n### On a new GPU server\n\nWhen you pick a **New server**, Loomplane creates a DigitalOcean GPU Droplet for the model first. The Droplet bills from the moment it exists, so creating it is a step of its own:\n\n1. **Review server** asks DigitalOcean for the size's price and shows the server Loomplane would create, named after the project, the model and the environment, such as `shop-qwen2-5-7b-instruct-staging-gpu`, in its region and at its hourly price. Nothing is created yet.\n2. **Create the server and plan it** approves that server. The review is good for five minutes, so a stale one asks you to review again.\n\nOnly admins can review and create GPU servers (`organization_cloud:manage`). Anyone else sees \"An admin creates GPU servers. Ask one to deploy this, or pick a server you have.\" The DigitalOcean account has to be in the environment's Cloud, too.\n\nThe model then shows **Waiting for a server**. Once the server is up and has passed its GPU checks, Loomplane adds the model to the manifest and makes the plan. The server bills from the moment it's created until you delete it in **Infrastructure**, whether the model gets traffic or not, and whether the model is still there or not.\n\nThe Cloud's capacity policy applies to these servers like any other. When it holds a server back for now (an approval still to come, capacity still to grow, a count that's out of date) the model keeps waiting and says why, with a link to the Cloud's **Capacity** tab for admins. When it refuses (no ceiling for that GPU kind, a ceiling that would be passed, a provider quota with no room) the deploy is refused with the reason. **Cancel** on a waiting model stops the wait. If the server was already approved, it says so, and you delete the server in **Infrastructure**.\n\n## What a deploy writes\n\nA deploy is one edit to `loomplane.yaml`. You can read it, and you could have written it yourself:\n\n```yaml\nresources:\n qwen2-5-7b-instruct:\n kind: model-vllm\n version: \"0.31\"\n provider: server\n target: conn_01jabc...\n gpu: { kind: nvidia-l4, count: 1 }\n settings:\n entry: Qwen/Qwen2.5-7B-Instruct\n model: Qwen/Qwen2.5-7B-Instruct\n revision: a09a35458c702b33eeacc393d103063234e8bc28\n quantization: bf16\n served_name: Qwen/Qwen2.5-7B-Instruct\n max_model_len: \"32768\"\n cache_mb: \"20480\"\n environments:\n staging:\n enabled: true\n```\n\nModel kinds run only in the environments where they're enabled, and each of those environments runs its own copy. The settings must match the registry's pin for the entry: a `model`, `revision` or GGUF `file` that differs from it is refused. `cache_mb` sizes a GPU model's weight cache on Kubernetes, 20,480 MB by default.\n\nA model you add to the manifest by hand shows on the Models page too, with its state and its hourly price. Loomplane keeps no budget or price override for it, and it isn't counted in the month's spend.\n\n## Run it in more than one environment\n\nHere's the model above running in staging and production. Production has its own block, which says only what's different there:\n\n```yaml\nresources:\n qwen2-5-7b-instruct:\n kind: model-vllm\n version: \"0.31\"\n provider: server\n target: conn_01jabc...\n gpu: { kind: nvidia-l4, count: 1 }\n settings:\n entry: Qwen/Qwen2.5-7B-Instruct\n model: Qwen/Qwen2.5-7B-Instruct\n revision: a09a35458c702b33eeacc393d103063234e8bc28\n quantization: bf16\n served_name: Qwen/Qwen2.5-7B-Instruct\n max_model_len: \"32768\"\n cache_mb: \"20480\"\n environments:\n staging:\n enabled: true\n production:\n enabled: true\n target: \n gpu: { kind: nvidia-h100, count: 1 }\n settings:\n max_model_len: \"16384\"\n```\n\nStaging reads everything from the top level. Production reads the top level too, except where its block says otherwise, so its copy runs on the production GPU server, on an H100, with a 16,384 token context. Each copy has its own `MODEL_API_KEY`, its own cost and budget alert, and its own row on the **Deployed** tab. Copies usually run on different servers, but nothing stops you picking the server another environment's copy already uses, and then the two share it. A service that needs `qwen2-5-7b-instruct` lists that one name, and in each environment it gets that environment's `MODEL_URL`.\n\nA few rules for the blocks:\n\n- `target` is optional at the top level. Each environment needs one, from its own block or from the top level, and when neither has one, only that environment's plan stops and asks for it. A block that runs the model on another provider doesn't take the top-level target with it.\n- One model runs on one engine everywhere. If production needs another engine, say llama.cpp on a CPU server while staging runs vLLM on a GPU, deploy it to production as a separately named model.\n- When Loomplane adds an environment, the block's `settings` get only what differs from the top level: `quantization`, `model`, `revision`, `file`, `max_model_len` or `cache_mb`. It never writes `entry` or `served_name` there, so your code asks for the same model name in every environment.\n- A block can't say \"no file\". If the top level names a GGUF `file` that another environment reads, you can't add an environment with weights that have no file: the preview refuses it before anything is written, and tells you to deploy it there as a separately named model or remove it from the other environments first.\n\nThe model page shows one environment's copy at a time. When the model runs in more than one, the header links each of them.\n\n## Link a service\n\nOn the model's page, under **Linked services**, choose **Link a service** and pick one. That adds the model to the service's `needs`, which you can also write yourself:\n\n```yaml\nservices:\n api:\n needs: [qwen2-5-7b-instruct]\n```\n\nOn its next release in that environment the service gets two variables:\n\n- `MODEL_URL`, the model's address on the environment's private network.\n- `MODEL_API_KEY`, the key the model's guard checks. Loomplane generates it and never shows it.\n\nThe service has to run on the same server or cluster as the model. **Linked services** says **Reachable** when it does, and when it doesn't, why: \"api runs on edge-1, and qwen2-5-7b-instruct runs on gpu-1. Run them on the same server or cluster.\"\n\nChat models speak the OpenAI API, so the `openai` package works with `MODEL_URL` plus `/v1`:\n\n```python\nimport os\nfrom openai import OpenAI\n\nclient = OpenAI(\n base_url=os.environ[\"MODEL_URL\"] + \"/v1\",\n api_key=os.environ[\"MODEL_API_KEY\"],\n)\n\nreply = client.chat.completions.create(\n model=\"Qwen/Qwen2.5-7B-Instruct\",\n messages=[{\"role\": \"user\", \"content\": \"Say hello.\"}],\n)\nprint(reply.choices[0].message.content)\n```\n\nThe `model` field is the name the model is served as, its Hugging Face repo unless `served_name` says otherwise. The model page's **Example** tab has curl, Python and JavaScript for the model's own tasks: embeddings at `/v1/embeddings` (with the query prefix the model wants, such as `\"query: \"`, when the registry knows it), reranking at `POST $MODEL_URL/rerank`, and transcription at `POST $MODEL_URL/v1/audio/transcriptions`.\n\nA service that needs the model in an environment where it doesn't run gets a `need-off` warning on that environment's plans, saying it gets no `MODEL_URL` there because the model doesn't run there. The warning doesn't block those deploys. It says how to fix it: \"Deploy qwen2-5-7b-instruct to production from its model page.\"\n\n## Any Hugging Face model\n\nAbove the registry, **Any Hugging Face model** takes a repo (`owner/name`) or its page's address. **Check** reads the repo at its current commit, works out what it needs from its `config.json` and its weights, and shows it as a card marked **Untested**, which you deploy like any other. It's kept for your workspace for an hour, and stored once you deploy it. You need `ai:edit` to use it.\n\nLoomplane reads the repo anonymously, and uses the workspace's Hugging Face token only for a gated or private one. Paste a token in this box by mistake and it's caught before it's sent anywhere.\n\nWhat it can serve:\n\n- single-file GGUF weights ending in `Q8_0`, `MXFP4` or `Q4_K_M`, with llama.cpp,\n- safetensors (or `pytorch_model` `.bin`) weights of an architecture the pinned vLLM knows,\n- embedding and rerank models Text Embeddings Inference knows, with weights under 1.5 GiB, on CPU.\n\nWhat it refuses, with the reason:\n\n- a model whose `config.json` points at Python in its own repo (`auto_map`). Loomplane never runs repository code for a pasted model (\"needs code from its repository to run, and Loomplane doesn't run repository code for pasted models\"). A registry entry can, but only after that code was reviewed at the commit the entry pins.\n- a task Loomplane doesn't serve, or a repo that doesn't say on Hugging Face what it does.\n- an architecture no shipped engine knows, or a `config.json` that doesn't give the layer count, heads or context length the memory math needs.\n- a GGUF split into parts, which llama.cpp can't download.\n\nOn Kubernetes, a llama.cpp model on CPU also needs its weights to fit the 20,480 MB volume the CPU kinds get there.\n\n## Gated models\n\nA gated model needs the workspace's Hugging Face token, from an account that has accepted the model's license. Without one, the deploy dialog says the model is gated and links to [AI settings](/docs/ai/settings#the-hugging-face-token). With one, it says \"Gated on Hugging Face. The workspace's token can download it.\" If the account never accepted the license, the engine's download fails, and the model page tells you which license to accept, then **Retry**.\n\n## The model page\n\nOpen a row on the **Deployed** tab. The header says the model's state:\n\n| State | What's happening |\n|---|---|\n| **Planned** | The plan that deploys it waits for approval |\n| **Waiting for a server** | Its GPU server is being created, or held back by the capacity policy, with the reason |\n| **Deploying** | Downloading and loading weights |\n| **Ready** | Serving. The page shows the address linked services reach it at |\n| **Failed** | It didn't start. The page says why and what to try |\n| **Update failed** | A change didn't start, and the version deployed before is still running, so linked services keep working |\n| **Needs attention** | Its GPU server failed or took too long. Fix or retry the server in **Infrastructure**, then **Retry** here |\n\n**Retry** plans the environment again for a model that failed to start, from the manifest as it is. For a model whose server needs attention, it waits for the same server again: Loomplane never creates a second one.\n\nWhen the engine runs out of GPU memory, the page says so (\"The model didn't fit in GPU memory at 22528 tokens. Try a shorter context or a smaller quantization.\") and offers **Move it with a shorter context**.\n\nThe **Overview** tab also shows where it runs, its engine and version, its quantization, its context, its badge on the GPU it runs on, its [cost](/docs/ai/model-costs) and its linked services.\n\n### Update available\n\nWhen a Loomplane release pins new weights for a model's registry entry, its page shows **Update available** with what changed. **Move to** the new pin plans the change. The model keeps serving the weights it has until you approve the plan and the new ones are loaded. Planning the model's environment without moving it fails with a sentence that says to do this first, so the change never happens silently.\n\nA pin move changes only the environment you move it from. When the model runs in staging and production and you move production, the page says \"Moves production only. staging keeps its weights until you move it from its own page.\" Staging keeps its weights and keeps showing **Update available** until you move it from staging's page.\n\n### Move it\n\n**Settings**, then **Move**, runs this environment's copy on another GPU, server or cluster, or with another quantization or context. The other environments keep their copies as they are. It's the deploy dialog again, new GPU server and review included. The model keeps its name, so linked services keep their `MODEL_URL`, and it keeps running where it is until the move is deployed. While a move waits for a new GPU server, the page shows what that server costs, since both bill once it's up. A server Loomplane created for the model's old place keeps billing after the move until you delete it in **Infrastructure**, and the page says so.\n\n### Remove it\n\n**Settings**, then **Remove**, takes out the environment you're looking at and plans it. When the model runs in other environments too, that's all it removes: the dialog says \"Removes llm from production. It keeps running in staging.\" A service in production that links to the model goes on linking to it, gets no `MODEL_URL` there once the plan is approved, and the plan warns `need-off` for it. The remove dialog lists those services before you confirm.\n\nRemoving the last environment removes the model from the manifest. That one is refused while a service links to it (\"checkout in staging links to it. Unlink it first.\"). The downloaded weights stay on the server as retained storage, so deploying the model there again doesn't download them again. Delete them from the server's storage when you no longer need them. If Loomplane created the GPU server for this model, the server isn't removed with it, and keeps costing money until you delete it in **Infrastructure**.\n\nMove, remove, retry and cancel need the same permission as deploying: `ai:edit`, or `ai:manage` in production. Linking a service is a manifest edit, so it needs `project:update`.\n\n## On a Docker server\n\n`docker ps` shows a llama.cpp engine as `unhealthy`. Its image's own health check looks at a port the engine doesn't listen on. Loomplane checks the engine's `/health` itself, so ignore it.\n\nEach model is two containers: the engine and a guard in front of it. Only the guard's port is ever routed, and it refuses any request without `Authorization: Bearer $MODEL_API_KEY`, except `/health`. See [GPUs](/docs/clouds/gpus) for what a server or cluster needs before it can run GPU work at all." + "text": "Open **AI**, then **Models**. The **Registry** tab lists the open models Loomplane knows how to serve, and the **Deployed** tab lists the ones running in your projects, with what each costs per hour and this month.\n\nA model you deploy belongs to one project and runs in the environments you deploy it to, each environment running its own copy on a server or cluster you connected, or on a DigitalOcean GPU server Loomplane creates for it. Services in an environment link to that environment's copy and call it with `MODEL_URL` and `MODEL_API_KEY`.\n\n## The registry\n\nEach card shows the model's publisher, its size in parameters, its context window, its license, what it does (chat, reasoning, code, vision, embeddings, reranking or speech to text) and what it needs to run, such as \"Needs 22 GB GPU, or runs on CPU\". A badge says how sure Loomplane is that it runs, which the next section explains.\n\nSearch by name, or narrow the list:\n\n- **Task**, **Size** (under 4B up to over 100B parameters) and **License**.\n- **Commercial use only** keeps models whose license Loomplane knows and that allow commercial use. A license it doesn't know never counts.\n- **Fits my GPUs** keeps models that fit a GPU or a server your workspace has, or a GPU server it can create. If Loomplane can't read your targets, it says \"Couldn't check your GPUs.\" and shows everything.\n- **Tested only** keeps models a qualification run served.\n\nOpen a card for the model's page. It lists each quantization (the weights Loomplane can serve, each pinned to a Hugging Face commit), where each one fits, the license, and the model card from Hugging Face. **Deploy** is there and on the card.\n\nEvery entry and every quantization is pinned to a 40-character commit SHA, never to `main`, so the weights you deploy today are the weights you deploy next month.\n\n## Tested, estimated, failed and untested\n\nEvery model, and every GPU it might run on, carries one of these:\n\n| Badge | What it means |\n|---|---|\n| **Tested on** a GPU | Loomplane's qualification job deployed this quantization on that GPU kind, with the engine version Loomplane ships, and served real requests from it |\n| **Estimated** | The memory math says it fits. Nobody has run it there |\n| **Failed on** a GPU | A qualification run on that GPU failed. Loomplane won't offer it there, whatever the math says |\n| **Untested** | You pasted it from Hugging Face. No qualification run will ever check it |\n| **Doesn't fit** | The memory math says it won't fit, with the reason |\n\nAn estimate never reads as tested. A test counts only for the GPU kind it ran on, the engine version Loomplane ships today and the weights revision the registry pins. When Loomplane moves to a new engine release, or the registry re-pins a model's weights, its fits go back to **Estimated** until a run proves them again. A passed run at a shorter context than Loomplane would serve proves nothing about the longer one, so that doesn't count either.\n\n### How models get tested\n\nThe qualification job runs in Loomplane's own CI, in a DigitalOcean account kept for it alone, never in your workspace or with your credentials. Once a week it creates one GPU Droplet (the GPU kind rotates through the RTX 4000 Ada, the L40S and the H100), starts a sample of registry models on it with the engines Loomplane ships, and calls each one the way your service would: a streamed chat completion, an embedding of the right length, a rerank, a transcription. Then it deletes the Droplet. Each result records the GPU, the GPU count, the context, the engine version and what it measured, or why it failed, and the results ship in the next Loomplane release. Results older than 30 days are run again.\n\nUntil a run covers a model, it reads **Estimated**, which is what the memory math alone can promise.\n\n### How fit is estimated\n\nFor vLLM, the memory one GPU needs is:\n\n- the weights, divided by the number of GPUs,\n- plus the KV cache for the context, at 2 bytes a value, split across GPUs only as far as the model's KV heads allow,\n- plus overhead: 1.5 GiB (1 GiB for embedding and rerank models), 8% of that GPU's share of the weights, and another 1 GiB for vision and speech models' encoders.\n\nThat has to fit in 90% of the GPU's memory, since vLLM gets `--gpu-memory-utilization 0.90`. Loomplane tries 1, 2, 4 and then 8 GPUs and takes the smallest count that fits. It serves the longest context that fits, rounded down to a multiple of 1024, at least 4096 tokens (or the model's own limit if that's shorter) and at most 32,768. Embedding and rerank models keep no KV cache and serve up to 8,192 tokens.\n\nHere's an 8B model with 16 GiB of bf16 weights, 32 layers, 8 KV heads and a head size of 128. Each token of context takes 128 KiB of KV cache. On an NVIDIA L4 (24 GiB, so 21.6 GiB usable) the overhead is 2.78 GiB, and at 4,096 tokens the model needs 16 + 0.5 + 2.78 = 19.28 GiB. It fits. The room left over holds 23,101 tokens, so Loomplane serves 22,528. On an RTX 4000 Ada (20 GiB, 18 GiB usable) it doesn't fit on one GPU. Its card says \"Needs 22 GB GPU\", which is 19.28 divided by 0.9, rounded up.\n\nThe GPU also has to be new enough. vLLM needs CUDA compute capability 7.5, which rules out the V100, and `fp8` and `mxfp4` weights need 8.0, which rules out the T4 as well. llama.cpp runs on 6.1 and up. A GPU kind Loomplane has no compute capability for never fits.\n\nOn CPU, a model needs 1.1 times its weights, plus its KV cache, plus 0.5 GiB. That has to fit in 3.5 GiB for Text Embeddings Inference and 7 GiB for llama.cpp, which leaves the operating system room in the 4,096 MB and 8,192 MB those containers reserve. llama.cpp on CPU serves 8,192 tokens.\n\n## The engines\n\nLoomplane runs each model with one of three inference servers, picked by the quantization:\n\n| Engine | Runs on | Serves | Manifest kind |\n|---|---|---|---|\n| vLLM 0.31 | NVIDIA GPU | Chat, reasoning, code, vision, embeddings and speech to text, from safetensors | `model-vllm` |\n| Text Embeddings Inference 1.9 | CPU | Embedding and rerank models | `model-tei` |\n| llama.cpp b11580 | CPU or NVIDIA GPU | Models as a single GGUF file (`Q8_0`, `MXFP4` or `Q4_K_M`) | `model-llamacpp`, `model-llamacpp-gpu` |\n\nA model that has both kinds of quantization gives you a **GPU** and **CPU** switch in the deploy dialog. Images are pinned by digest. The GPU images are amd64 only, so a GPU model can't run on an Arm server.\n\n## Deploy a model\n\n\nChoose **Deploy** on a card or a model's page.\n\n\nUnder **Where**, pick the project and the environment. The dialog says \"Runs in staging. Services in staging can link to it.\" The project needs a saved manifest first.\n\nTo add an environment to a model that's already deployed, open its page and choose **Deploy to another environment**. You get the same dialog for the same model, and the environments it runs in already read \"(runs there)\" and can't be picked.\n\n\nPick where it runs. For a GPU model the list shows your connected servers and clusters with GPUs, how many are free (or how many a cluster has per node) and what they cost, and, when the project's Cloud has a DigitalOcean account, GPU server sizes Loomplane can create, marked **New server**. A target the model doesn't fit says why and can't be picked. For a CPU model, pick a ready server or cluster.\n\n\nPick a quantization, or leave it and Loomplane takes the first that fits. Set **Context in tokens**, or leave it for the most that fits, up to 32,768. **Budget alert** is optional; see [What models cost](/docs/ai/model-costs).\n\n\nRead the summary at the bottom: what it costs per hour and roughly per month, and anything that stops the deploy. Then choose **Plan it**.\n\n\nNothing runs before that. **Plan it** adds the model to the project's `loomplane.yaml` and plans the environment, and the plan waits for approval like any other. Once it's approved, the engine downloads the weights and loads them, which for a big model takes a while. Loomplane waits up to two hours for vLLM, an hour for llama.cpp and 30 minutes for Text Embeddings Inference before it calls a start failed.\n\nYou need `ai:edit` to deploy to an environment that isn't production, and `ai:manage` for production. The dialog tells you when you can't.\n\nA model already running in that environment is refused (\"llm already runs Qwen2.5 7B Instruct in staging.\"). Deploying a model the project already runs to another environment adds that environment to the same resource: the dialog says \"Adds production to llm.\", and production gets its own copy on the server you pick, with its own key, cost and budget. The copy has to run on the same engine as the others. Pick a CPU server for a model that runs on vLLM in staging and the dialog refuses it, and tells you to pick a target the model runs on as it is, or deploy it as a separately named model.\n\n### On a new GPU server\n\nWhen you pick a **New server**, Loomplane creates a DigitalOcean GPU Droplet for the model first. The Droplet bills from the moment it exists, so creating it is a step of its own:\n\n1. **Review server** asks DigitalOcean for the size's price and shows the server Loomplane would create, named after the project, the model and the environment, such as `shop-qwen2-5-7b-instruct-staging-gpu`, in its region and at its hourly price. Nothing is created yet.\n2. **Create the server and plan it** approves that server. The review is good for five minutes, so a stale one asks you to review again.\n\nOnly admins can review and create GPU servers (`organization_cloud:manage`). Anyone else sees \"An admin creates GPU servers. Ask one to deploy this, or pick a server you have.\" The DigitalOcean account has to be in the environment's Cloud, too.\n\nThe model then shows **Waiting for a server**. Once the server is up and has passed its GPU checks, Loomplane adds the model to the manifest and makes the plan. The server bills from the moment it's created until you delete it in **Infrastructure**, whether the model gets traffic or not, and whether the model is still there or not.\n\nThe Cloud's capacity policy applies to these servers like any other. When it holds a server back for now (an approval still to come, capacity still to grow, a count that's out of date) the model keeps waiting and says why, with a link to the Cloud's **Capacity** tab for admins. When it refuses (no ceiling for that GPU kind, a ceiling that would be passed, a provider quota with no room) the deploy is refused with the reason. **Cancel** on a waiting model stops the wait. If the server was already approved, it says so, and you delete the server in **Infrastructure**.\n\n## What a deploy writes\n\nA deploy is one edit to `loomplane.yaml`. You can read it, and you could have written it yourself:\n\n```yaml\nresources:\n qwen2-5-7b-instruct:\n kind: model-vllm\n version: \"0.31\"\n provider: server\n target: conn_01jabc...\n gpu: { kind: nvidia-l4, count: 1 }\n settings:\n entry: Qwen/Qwen2.5-7B-Instruct\n model: Qwen/Qwen2.5-7B-Instruct\n revision: a09a35458c702b33eeacc393d103063234e8bc28\n quantization: bf16\n served_name: Qwen/Qwen2.5-7B-Instruct\n max_model_len: \"32768\"\n cache_mb: \"20480\"\n environments:\n staging:\n enabled: true\n```\n\nModel kinds run only in the environments where they're enabled, and each of those environments runs its own copy. The settings must match the registry's pin for the entry: a `model`, `revision` or GGUF `file` that differs from it is refused. `cache_mb` sizes a GPU model's weight cache on Kubernetes, 20,480 MB by default.\n\nA model you add to the manifest by hand shows on the Models page too, with its state and its hourly price. Loomplane keeps no budget or price override for it, and it isn't counted in the month's spend.\n\n## Run it in more than one environment\n\nHere's the model above running in staging and production. Production has its own block, which says only what's different there:\n\n```yaml\nresources:\n qwen2-5-7b-instruct:\n kind: model-vllm\n version: \"0.31\"\n provider: server\n target: conn_01jabc...\n gpu: { kind: nvidia-l4, count: 1 }\n settings:\n entry: Qwen/Qwen2.5-7B-Instruct\n model: Qwen/Qwen2.5-7B-Instruct\n revision: a09a35458c702b33eeacc393d103063234e8bc28\n quantization: bf16\n served_name: Qwen/Qwen2.5-7B-Instruct\n max_model_len: \"32768\"\n cache_mb: \"20480\"\n environments:\n staging:\n enabled: true\n production:\n enabled: true\n target: \n gpu: { kind: nvidia-h100, count: 1 }\n settings:\n max_model_len: \"16384\"\n```\n\nStaging reads everything from the top level. Production reads the top level too, except where its block says otherwise, so its copy runs on the production GPU server, on an H100, with a 16,384 token context. Each copy has its own `MODEL_API_KEY`, its own cost and budget alert, and its own row on the **Deployed** tab. Copies usually run on different servers, but nothing stops you picking the server another environment's copy already uses, and then the two share it. A service that needs `qwen2-5-7b-instruct` lists that one name, and in each environment it gets that environment's `MODEL_URL`.\n\nA few rules for the blocks:\n\n- `target` is optional at the top level. Each environment needs one, from its own block or from the top level, and when neither has one, only that environment's plan stops and asks for it. A block that runs the model on another provider doesn't take the top-level target with it.\n- One model runs on one engine everywhere. If production needs another engine, say llama.cpp on a CPU server while staging runs vLLM on a GPU, deploy it to production as a separately named model.\n- When Loomplane adds an environment, the block's `settings` get only what differs from the top level: `quantization`, `model`, `revision`, `file`, `max_model_len` or `cache_mb`. It never writes `entry` or `served_name` there, so your code asks for the same model name in every environment.\n- A block can't say \"no file\". If the top level names a GGUF `file` that another environment reads, you can't add an environment with weights that have no file: the preview refuses it before anything is written, and tells you to deploy it there as a separately named model or remove it from the other environments first.\n\nThe model page shows one environment's copy at a time. When the model runs in more than one, the header links each of them.\n\n## Link a service\n\nOn the model's page, under **Linked services**, choose **Link a service** and pick one. That adds the model to the service's `needs`, which you can also write yourself:\n\n```yaml\nservices:\n api:\n needs: [qwen2-5-7b-instruct]\n```\n\nOn its next release in that environment the service gets two variables:\n\n- `MODEL_URL`, the model's address on the environment's private network.\n- `MODEL_API_KEY`, the key the model's guard checks. Loomplane generates it and never shows it.\n\nThe service has to run on the same server or cluster as the model. **Linked services** says **Reachable** when it does, and when it doesn't, why: \"api runs on edge-1, and qwen2-5-7b-instruct runs on gpu-1. Run them on the same server or cluster.\"\n\nChat models speak the OpenAI API, so the `openai` package works with `MODEL_URL` plus `/v1`:\n\n```python\nimport os\nfrom openai import OpenAI\n\nclient = OpenAI(\n base_url=os.environ[\"MODEL_URL\"] + \"/v1\",\n api_key=os.environ[\"MODEL_API_KEY\"],\n)\n\nreply = client.chat.completions.create(\n model=\"Qwen/Qwen2.5-7B-Instruct\",\n messages=[{\"role\": \"user\", \"content\": \"Say hello.\"}],\n)\nprint(reply.choices[0].message.content)\n```\n\nThe `model` field is the name the model is served as, its Hugging Face repo unless `served_name` says otherwise. The model page's **Example** tab has curl, Python and JavaScript for the model's own tasks: embeddings at `/v1/embeddings` (with the query prefix the model wants, such as `\"query: \"`, when the registry knows it), reranking at `POST $MODEL_URL/rerank`, and transcription at `POST $MODEL_URL/v1/audio/transcriptions`.\n\nA service that needs the model in an environment where it doesn't run gets a `need-off` warning on that environment's plans, saying it gets no `MODEL_URL` there because the model doesn't run there. The warning doesn't block those deploys. It says how to fix it: \"Deploy qwen2-5-7b-instruct to production from its model page.\"\n\n## Any Hugging Face model\n\nAbove the registry, **Any Hugging Face model** takes a repo (`owner/name`) or its page's address. **Check** reads the repo at its current commit, works out what it needs from its `config.json` and its weights, and shows it as a card marked **Untested**, which you deploy like any other. It's kept for your workspace for an hour, and stored once you deploy it. You need `ai:edit` to use it.\n\nLoomplane reads the repo anonymously, and uses the workspace's Hugging Face token only for a gated or private one. Paste a token in this box by mistake and it's caught before it's sent anywhere.\n\nWhat it can serve:\n\n- single-file GGUF weights ending in `Q8_0`, `MXFP4` or `Q4_K_M`, with llama.cpp,\n- safetensors (or `pytorch_model` `.bin`) weights of an architecture the pinned vLLM knows,\n- embedding and rerank models Text Embeddings Inference knows, with weights under 1.5 GiB, on CPU.\n\nWhat it refuses, with the reason:\n\n- a model whose `config.json` points at Python in its own repo (`auto_map`). Loomplane never runs repository code for a pasted model (\"needs code from its repository to run, and Loomplane doesn't run repository code for pasted models\"). A registry entry can, but only after that code was reviewed at the commit the entry pins.\n- a task Loomplane doesn't serve, or a repo that doesn't say on Hugging Face what it does.\n- an architecture no shipped engine knows, or a `config.json` that doesn't give the layer count, heads or context length the memory math needs.\n- a GGUF split into parts, which llama.cpp can't download.\n\nOn Kubernetes, a llama.cpp model on CPU also needs its weights to fit the 20,480 MB volume the CPU kinds get there.\n\n## Gated models\n\nA gated model needs the workspace's Hugging Face token, from an account that has accepted the model's license. Without one, the deploy dialog says the model is gated and links to [AI settings](/docs/ai/settings#the-hugging-face-token). With one, it says \"Gated on Hugging Face. The workspace's token can download it.\" If the account never accepted the license, the engine's download fails, and the model page tells you which license to accept, then **Retry**.\n\n## The model page\n\nOpen a row on the **Deployed** tab. The header says the model's state:\n\n| State | What's happening |\n|---|---|\n| **Planned** | The plan that deploys it waits for approval |\n| **Waiting for a server** | Its GPU server is being created, or held back by the capacity policy, with the reason |\n| **Deploying** | Downloading and loading weights |\n| **Ready** | Serving. The page shows the address linked services reach it at |\n| **Failed** | It didn't start. The page says why and what to try |\n| **Update failed** | A change didn't start, and the version deployed before is still running, so linked services keep working |\n| **Needs attention** | Its GPU server failed or took too long. Fix or retry the server in **Infrastructure**, then **Retry** here |\n\n**Retry** plans the environment again for a model that failed to start, from the manifest as it is. For a model whose server needs attention, it waits for the same server again: Loomplane never creates a second one.\n\nWhen the engine runs out of GPU memory, the page says so (\"The model didn't fit in GPU memory at 22528 tokens. Try a shorter context or a smaller quantization.\") and offers **Move it with a shorter context**.\n\nThe **Overview** tab also shows where it runs, its engine and version, its quantization, its context, its badge on the GPU it runs on, its [cost](/docs/ai/model-costs) and its linked services.\n\n### Update available\n\nWhen a Loomplane release pins new weights for a model's registry entry, its page shows **Update available** with what changed. **Move to** the new pin plans the change. The model keeps serving the weights it has until you approve the plan and the new ones are loaded. Planning the model's environment without moving it fails with a sentence that says to do this first, so the change never happens silently.\n\nA pin move changes only the environment you move it from. When the model runs in staging and production and you move production, the page says \"Moves production only. staging keeps its weights until you move it from its own page.\" Staging keeps its weights and keeps showing **Update available** until you move it from staging's page.\n\n### Move it\n\n**Settings**, then **Move**, runs this environment's copy on another GPU, server or cluster, or with another quantization or context. The other environments keep their copies as they are. It's the deploy dialog again, new GPU server and review included. The model keeps its name, so linked services keep their `MODEL_URL`, and it keeps running where it is until the move is deployed. While a move waits for a new GPU server, the page shows what that server costs, since both bill once it's up. A server Loomplane created for the model's old place keeps billing after the move until you delete it in **Infrastructure**, and the page says so.\n\n### Remove it\n\n**Settings**, then **Remove**, takes out the environment you're looking at and plans it. When the model runs in other environments too, that's all it removes: the dialog says \"Removes llm from production. It keeps running in staging.\" A service in production that links to the model goes on linking to it, gets no `MODEL_URL` there once the plan is approved, and the plan warns `need-off` for it. The remove dialog lists those services before you confirm.\n\nRemoving the last environment removes the model from the manifest. That one is refused while a service links to it (\"checkout in staging links to it. Unlink it first.\"). The downloaded weights stay on the server as retained storage, so deploying the model there again doesn't download them again. Delete them from the server's storage when you no longer need them. If Loomplane created the GPU server for this model, the server isn't removed with it, and keeps costing money until you delete it in **Infrastructure**.\n\nMove, remove, retry and cancel need the same permission as deploying: `ai:edit`, or `ai:manage` in production. Linking a service is a manifest edit, so it needs `project:update`.\n\n## On a Docker server\n\n`docker ps` shows a llama.cpp engine as `unhealthy`. Its image's own health check looks at a port the engine doesn't listen on. Loomplane checks the engine's `/health` itself, so ignore it.\n\nEach model is two containers: the engine and a guard in front of it. Only the guard's port is ever routed, and it refuses any request without `Authorization: Bearer $MODEL_API_KEY`, except `/health`. See [GPUs](/docs/clouds/gpus) for what a server or cluster needs before it can run GPU work at all." }, { "path": "ai/settings", @@ -105,7 +105,7 @@ "title": "Adopting and moving services", "description": "Bring running services under a Cloud target, then move them to another account or provider with a reviewed, recoverable sync.", "url": "https://www.loomplane.com/docs/clouds/adopting-and-moving", - "text": "## Adopt an existing service\n\nKeep your existing manifest until you choose to adopt a Cloud. Create a target with the service's current provider, connection and region, assign that Cloud to its environment, and save a manifest revision that sets `cloud_target` while removing any effective direct `provider` and `target` settings. Check inherited defaults and environment overrides too, because a service can't resolve both forms of placement.\n\nReview the ordinary deployment plan before you approve it. When the resolved placement and configuration match what already serves, the plan records Cloud metadata without a provider deployment. If it proposes a replacement, check the account, region and effective settings first.\n\nCloud targets currently place services. Resources and gateways keep their direct placement. A Cloud switch doesn't move database or storage contents.\n\n## Replace an account or provider\n\nConnect the destination account under Integrations first. Renewing a token for the same verified account keeps its connection ID and doesn't move services. Replacing the account takes a new connection. Stable provider identities, such as a Vercel user or team ID, tell renewal from replacement. If an older connection lacks its immutable identity, reconnect it before you switch.\n\n```bash\nloomctl cloud-targets show my-project cloud_... target_...\nloomctl cloud-targets switch my-project cloud_... target_... \\\n --provider vercel --connection conn_new --revision 1\n```\n\nRead the preview. It lists the old and proposed placement, affected environments and services, action counts, external routing requirements and blockers. A Cloud shared by production and staging can affect both, so use separate Clouds when their destinations should change independently.\n\nTo accept a review you already saved, use its ID and digest:\n\n```bash\nloomctl cloud-syncs apply my-project \\\n --preview cpv_... --revision REVIEW_DIGEST \\\n --request-id switch-frontend-2026-10-20 --yes --wait --timeout 30m\n```\n\nThe command fetches and shows that exact preview before it applies it. Or repeat `cloud-targets switch` with `--yes`, which creates and shows a fresh review before accepting it. Previews expire after 24 hours, and a revision change or altered serving inputs need another review.\n\nThe idempotency key belongs to acceptance. After a lost response, reuse the same preview, digest and `--request-id` to recover the original sync ID. A new preview is a separate request, even if the destination looks identical.\n\nA switch migrates the release that currently serves, using each binding's saved source artifact and encrypted variable snapshot. It doesn't deploy an unapproved draft, and missing historical inputs block it. Future ordinary releases use the new account.\n\nA service region set in the manifest, in its environment override or in defaults stays pinned when you change a target's default region. Services that inherit the target or provider default follow the new one. Older bindings without recorded region provenance keep their applied region during a sync. Deploy an ordinary release to record that before you rely on a default change to move them.\n\n### Switch a default\n\n```bash\nloomctl clouds switch-default my-project cloud_... \\\n --provider vercel --connection conn_new --revision 3\nloomctl clouds switch-default my-project cloud_... \\\n --provider vercel --connection conn_new --revision 3 \\\n --yes --request-id move-default --wait --timeout 30m\n```\n\nThe review covers every environment that uses the Cloud, across projects, and moves only the services the old default placed. Services on a target, or with their own `provider`, keep theirs, though one that depends on a moved service is redeployed to pick up the new address. Leave out the provider and connection (or pass `--clear`) to remove the default. Clearing is blocked while serving services still use it. One default switch runs per Cloud at a time, and no environment can be assigned to or from the Cloud until it settles.\n\nA Cloud reassignment works the same way for default-placed services: they move to the new Cloud's default, and the review blocks if the new Cloud has none your project can use.\n\n## Follow and recover a sync\n\n```bash\nloomctl cloud-syncs my-project\nloomctl cloud-syncs show my-project csync_...\nloomctl cloud-syncs wait my-project csync_... --timeout 30m\nloomctl cloud-syncs retry my-project csync_... --wait --timeout 30m\n```\n\nUse `--json` for scripts. Finish or revert unfinished syncs before renaming a Cloud or target in the same project.\n\n| State | Meaning and next action |\n|---|---|\n| `pending` | Accepted and saved. Dispatch will schedule or recover it |\n| `running` | Services are being reconciled from recorded inputs |\n| `routing_pending` | The managed deployment finished, but you must verify external routing |\n| `cleanup_pending` | Old resources are being removed. An error means cleanup needs recovery or a retry |\n| `failed` | Inspect per-environment errors, restore access or dependencies, then retry |\n| `succeeded` | Every affected environment and its cleanup finished |\n| `reverting` | A compensating operation owns the remaining work. Follow its sync ID |\n| `reverted` | Compensation finished and original ownership was released |\n\nWaits stop at success, failure, external routing or a cleanup error, and keep going through active cleanup. A timeout returns the latest record so you can resume. Restarting Loomplane recovers committed work. Partial completion is kept: a successful environment stays deployed when another fails. Old resources stay until managed consumers and required external routing have finished, and failed operations keep their guards so an ordinary release can't race unfinished cleanup.\n\n## Complete external routing, or revert\n\nIf you control DNS or another entry point, update it and check that traffic reaches the new service. Then record that for each affected environment:\n\n```bash\nloomctl cloud-syncs routing my-project csync_... \\\n --environment env_... --evidence 'Production DNS and HTTPS verified' \\\n --wait --timeout 10m\n```\n\nThis records your evidence and schedules the remaining cleanup. It doesn't change DNS. Without that evidence, Loomplane keeps the old resources.\n\n```bash\nloomctl cloud-syncs revert my-project csync_...\nloomctl cloud-syncs revert my-project csync_... \\\n --yes --request-id restore-frontend --wait --timeout 30m\n```\n\nRevert reviews compensation from the actual serving state. Read each environment's `compensation_mode` and `compensation_message`. `restore_retained` restores the exact retained original server runtime, `recreate` deploys saved inputs again, and `mixed` does both. A managed platform always recreates from saved inputs. Compensation refuses work that changed outside the original operation, and original credentials must stay available until all cleanup finishes.\n\n Fixture-backed checks verify persisted switching, historical input recovery and next-release account selection. They don't establish access, quotas, DNS propagation or service behavior in your real provider account. Qualify those yourself before a production migration, and move database or storage contents separately." + "text": "## Adopt an existing service\n\nKeep your existing manifest until you choose to adopt a Cloud. Create a target with the service's current provider, connection and region in your project's default Cloud, then save a manifest revision that sets `cloud_target` while removing any effective direct `provider` and `target` settings. The project's Clouds tab does this for you: pick the target beside the service and it writes the change for every environment, clearing placement an environment set on its own. Check inherited defaults too, because a service can't resolve both forms of placement.\n\nReview the ordinary deployment plan before you approve it. When the resolved placement and configuration match what already serves, the plan records Cloud metadata without a provider deployment. If it proposes a replacement, check the account, region and effective settings first.\n\nCloud targets currently place services. Resources and gateways keep their direct placement. A Cloud switch doesn't move database or storage contents.\n\n## Replace an account or provider\n\nConnect the destination account under Integrations first. Renewing a token for the same verified account keeps its connection ID and doesn't move services. Replacing the account takes a new connection. Stable provider identities, such as a Vercel user or team ID, tell renewal from replacement. If an older connection lacks its immutable identity, reconnect it before you switch.\n\n```bash\nloomctl cloud-targets show my-project cloud_... target_...\nloomctl cloud-targets switch my-project cloud_... target_... \\\n --provider vercel --connection conn_new --revision 1\n```\n\nRead the preview. It lists the old and proposed placement, affected environments and services, action counts, external routing requirements and blockers. A target serves every environment that names it, so production and staging on the same target move together. Give them separate targets, with an environment override in loomplane.yaml, when their destinations should change independently.\n\nTo accept a review you already saved, use its ID and digest:\n\n```bash\nloomctl cloud-syncs apply my-project \\\n --preview cpv_... --revision REVIEW_DIGEST \\\n --request-id switch-frontend-2026-10-20 --yes --wait --timeout 30m\n```\n\nThe command fetches and shows that exact preview before it applies it. Or repeat `cloud-targets switch` with `--yes`, which creates and shows a fresh review before accepting it. Previews expire after 24 hours, and a revision change or altered serving inputs need another review.\n\nThe idempotency key belongs to acceptance. After a lost response, reuse the same preview, digest and `--request-id` to recover the original sync ID. A new preview is a separate request, even if the destination looks identical.\n\nA switch migrates the release that currently serves, using each binding's saved source artifact and encrypted variable snapshot. It doesn't deploy an unapproved draft, and missing historical inputs block it. Future ordinary releases use the new account.\n\nA service region set in the manifest, in its environment override or in defaults stays pinned when you change a target's default region. Services that inherit the target or provider default follow the new one. Older bindings without recorded region provenance keep their applied region during a sync. Deploy an ordinary release to record that before you rely on a default change to move them.\n\n### Switch a default\n\n```bash\nloomctl clouds switch-default my-project cloud_... \\\n --provider vercel --connection conn_new --revision 3\nloomctl clouds switch-default my-project cloud_... \\\n --provider vercel --connection conn_new --revision 3 \\\n --yes --request-id move-default --wait --timeout 30m\n```\n\nThe review covers every environment that uses the Cloud, across projects, and moves only the services the old default placed. Services on a target, or with their own `provider`, keep theirs, though one that depends on a moved service is redeployed to pick up the new address. Leave out the provider and connection (or pass `--clear`) to remove the default. Clearing is blocked while serving services still use it. One default switch runs per Cloud at a time, and no project can make the Cloud its default until it settles.\n\nChanging a project's default Cloud (`clouds make-default`, see [Cloud targets](/docs/clouds/cloud-targets#change-the-default-cloud)) works the same way for every environment of the project: services on the old default move to the new Cloud, by target name or to its default placement, and the review blocks if the new Cloud lacks a target a running service names.\n\n## Follow and recover a sync\n\n```bash\nloomctl cloud-syncs my-project\nloomctl cloud-syncs show my-project csync_...\nloomctl cloud-syncs wait my-project csync_... --timeout 30m\nloomctl cloud-syncs retry my-project csync_... --wait --timeout 30m\n```\n\nUse `--json` for scripts. Finish or revert unfinished syncs before renaming a Cloud or target in the same project.\n\n| State | Meaning and next action |\n|---|---|\n| `pending` | Accepted and saved. Dispatch will schedule or recover it |\n| `running` | Services are being reconciled from recorded inputs |\n| `routing_pending` | The managed deployment finished, but you must verify external routing |\n| `cleanup_pending` | Old resources are being removed. An error means cleanup needs recovery or a retry |\n| `failed` | Inspect per-environment errors, restore access or dependencies, then retry |\n| `succeeded` | Every affected environment and its cleanup finished |\n| `reverting` | A compensating operation owns the remaining work. Follow its sync ID |\n| `reverted` | Compensation finished and original ownership was released |\n\nWaits stop at success, failure, external routing or a cleanup error, and keep going through active cleanup. A timeout returns the latest record so you can resume. Restarting Loomplane recovers committed work. Partial completion is kept: a successful environment stays deployed when another fails. Old resources stay until managed consumers and required external routing have finished, and failed operations keep their guards so an ordinary release can't race unfinished cleanup.\n\n## Complete external routing, or revert\n\nIf you control DNS or another entry point, update it and check that traffic reaches the new service. Then record that for each affected environment:\n\n```bash\nloomctl cloud-syncs routing my-project csync_... \\\n --environment env_... --evidence 'Production DNS and HTTPS verified' \\\n --wait --timeout 10m\n```\n\nThis records your evidence and schedules the remaining cleanup. It doesn't change DNS. Without that evidence, Loomplane keeps the old resources.\n\n```bash\nloomctl cloud-syncs revert my-project csync_...\nloomctl cloud-syncs revert my-project csync_... \\\n --yes --request-id restore-frontend --wait --timeout 30m\n```\n\nRevert reviews compensation from the actual serving state. Read each environment's `compensation_mode` and `compensation_message`. `restore_retained` restores the exact retained original server runtime, `recreate` deploys saved inputs again, and `mixed` does both. A managed platform always recreates from saved inputs. Compensation refuses work that changed outside the original operation, and original credentials must stay available until all cleanup finishes.\n\n Fixture-backed checks verify persisted switching, historical input recovery and next-release account selection. They don't establish access, quotas, DNS propagation or service behavior in your real provider account. Qualify those yourself before a production migration, and move database or storage contents separately." }, { "path": "clouds/aws", @@ -131,9 +131,9 @@ { "path": "clouds/cloud-targets", "title": "Cloud targets", - "description": "Group accounts into an organization Cloud, name targets, grant them to projects, and place services by name or tag.", + "description": "Group accounts into an organization Cloud, name targets, grant them to projects, and place services by name or tag in every environment.", "url": "https://www.loomplane.com/docs/clouds/cloud-targets", - "text": "Create an organization Cloud before you create a project. Add named targets, grant a project access, then assign the Cloud to an environment. A Cloud belongs to one organization. A target selects either a managed provider account or a server pool. Your manifest can then say `frontend` without carrying an account ID.\n\n```yaml\nversion: 1\nservices:\n web:\n source: node:apps/web\n cloud_target: frontend\n```\n\n## Create and grant\n\nUse the IDs these commands return:\n\n```bash\nloomctl clouds create --organization --name Production\nloomctl cloud-targets create cloud_... --organization \\\n --name frontend --provider vercel --connection conn_...\n# Once your project exists, grant all targets or select them with --targets.\nloomctl cloud-grants grant cloud_... project_... --targets target_...\nloomctl clouds assignment my-project env_...\nloomctl clouds assign my-project env_... --cloud cloud_... --revision 0\nloomctl clouds assign my-project env_... --cloud cloud_... --revision 0 \\\n --yes --request-id assign-production --wait --timeout 10m\n```\n\nYou can list, create, rename and delete organization Clouds with `--organization` and no project argument. The same flag works on `cloud-targets` and `cloud-syncs`. The project forms still work too, such as `clouds create my-project --name Production`. Assignment always needs a project.\n\n```bash\nloomctl clouds --organization\nloomctl clouds show cloud_... --organization\nloomctl cloud-grants cloud_...\nloomctl cloud-grants revoke cloud_... project_...\nloomctl cloud-syncs --organization\n```\n\nAn empty `--targets` grants the whole Cloud, including its default placement. A target list grants only those. Revoking prevents fresh placement but keeps the authority needed to clean up work you already accepted. Sharing capacity doesn't grant another project's releases, variables, logs or routes.\n\nThe first assignment uses revision `0`. Read `clouds assignment` before later changes, because unassigning keeps the generation. An unassigned environment can have a nonzero revision, and you need it to assign again. An environment from another project returns a scoped error, never an empty assignment.\n\n## Pick a target by tags\n\nYou don't have to name a target. Give your targets tags, then ask for the tags you need:\n\n```bash\nloomctl cloud-targets create my-project cloud_... \\\n --name eu-gpu --provider cloud-run --connection conn_... --tags eu,gpu\nloomctl cloud-targets update my-project cloud_... target_... \\\n --display-name \"EU GPU\" --tags eu,gpu,large --revision 1\n```\n\n```yaml\nversion: 1\ndefaults:\n cloud_tags: [eu]\nservices:\n web:\n source: node:apps/web\n cloud_tags: [frontend, eu]\n trainer:\n source: python:trainer\n cloud_tags: [gpu]\n environments:\n staging: { cloud_target: shared-gpu }\n```\n\nA tag is a lowercase slug of up to 32 characters, and a target carries at most 16. A service resolves to the one target that carries every tag it lists, looking only at the targets your project's grant allows. If none match, the plan fails with `cloud-tag-unmatched`. If several do, it fails with `cloud-tag-ambiguous` and names each, so you can add a tag only one carries or name the target with `cloud_target`.\n\n`cloud_target` and `cloud_tags` can't sit together at the same level. An environment override that sets one replaces whichever the service set, so staging above uses `shared-gpu` by name. `defaults.cloud_tags` applies to every service that sets no `cloud_target`, `cloud_tags`, `provider` or `target` of its own, and it can't be combined with `defaults.provider`. Like `cloud_target`, tags conflict with an effective direct `provider` or `target`, including an inherited one.\n\nOver HTTP, send `tags` when you create or update a target. Leave `tags` out of an update and they stay. Send `[]` and they're removed (`--clear-tags` in `loomctl`). Changing a target's tags advances its revision, so a plan approved against the old ones has to be planned again.\n\n## A default placement without targets\n\nA Cloud can have a default placement: one provider, one connection and an optional region. While a Cloud has no targets, that default is the only place its services go. Its connection has to be ready and belong to that provider's cloud.\n\n```bash\ncurl -X PUT .../api/v1/clouds/cloud_.../default-placement \\\n -d '{\"default_placement\":{\"provider\":\"vercel\",\"connection_id\":\"conn_...\",\"region\":\"iad1\"},\"revision\":1}'\n```\n\nYou can also pass `default_placement` when you create the Cloud, and send `\"default_placement\": null` to clear it. A service uses the default when it has no placement of its own. That keeps working after you add targets: adding a target only places the services that name or tag it. A service with its own `provider` keeps its direct placement.\n\nThe default reaches a project only when its grant covers the whole Cloud. If an admin granted a chosen set of targets, your services can use those targets but not the default.\n\nYou can set a first default at any time. Once an environment uses the Cloud, `default-placement` refuses to replace or clear it (HTTP 409). Change it with a reviewed switch, described in [Adopting and moving services](/docs/clouds/adopting-and-moving#switch-a-default)." + "text": "Create an organization Cloud, add named targets, and grant a project access. A project's first Cloud becomes its default Cloud, and every environment of the project deploys through it. A Cloud belongs to one organization. A target selects either a managed provider account or a server pool. Your manifest can then say `frontend` without carrying an account ID, and the same name works in production, staging and every preview.\n\n```yaml\nversion: 1\nservices:\n web:\n source: node:apps/web\n cloud_target: frontend\n```\n\n## Create and grant\n\nUse the IDs these commands return:\n\n```bash\nloomctl clouds create --organization --name Production\nloomctl cloud-targets create cloud_... --organization \\\n --name frontend --provider vercel --connection conn_...\n# Once your project exists, grant all targets or select them with --targets.\n# A project's first grant makes that Cloud its default.\nloomctl cloud-grants grant cloud_... project_... --targets target_...\nloomctl clouds default my-project\n```\n\nYou can list, create, rename and delete organization Clouds with `--organization` and no project argument. The same flag works on `cloud-targets` and `cloud-syncs`. The project forms still work too, such as `clouds create my-project --name Production`. A project's default Cloud always needs a project.\n\n```bash\nloomctl clouds --organization\nloomctl clouds show cloud_... --organization\nloomctl cloud-grants cloud_...\nloomctl cloud-grants revoke cloud_... project_...\nloomctl cloud-syncs --organization\n```\n\nAn empty `--targets` grants the whole Cloud, including its default placement. A target list grants only those. Revoking prevents fresh placement but keeps the authority needed to clean up work you already accepted. Sharing capacity doesn't grant another project's releases, variables, logs or routes.\n\n## Change the default Cloud\n\nEnvironments don't pick Clouds. To move a project to another Cloud, make that Cloud its default. It's a reviewed change, because services already running move with it:\n\n```bash\nloomctl clouds default my-project # shows the Cloud and its revision\nloomctl clouds make-default my-project cloud_... --revision 3\nloomctl clouds make-default my-project cloud_... --revision 3 \\\n --yes --request-id move-to-eu --wait --timeout 10m\n```\n\n`--revision` is the current default's revision from `clouds default`, or `0` when the project has none. The review covers every environment of the project and moves only the services that run on the old default. Pass `none` instead of a Cloud ID to leave the project without a default. Only a Cloud granted to the project can become its default, and revoking a grant ends its default without moving anything.\n\nEnvironments still differ where your manifest says so. Give staging its own target with an environment override, as `trainer` does below.\n\n## Use another Cloud\n\nA service can run on a target in any Cloud granted to the project. Name the Cloud with `cloud`:\n\n```yaml\nservices:\n web:\n source: node:apps/web\n cloud_target: frontend # the project's default Cloud\n trainer:\n source: python:trainer\n cloud: GPU Lab\n cloud_target: a100\n environments:\n preview:\n cloud_target: eu-run # a target without cloud is in the default Cloud\n staging:\n cloud: GPU Lab EU # same target name, another Cloud\n```\n\n`cloud` alone uses that Cloud's default placement. An environment that names a target also says which Cloud it's in, so `preview` above goes back to the default Cloud. A name no Cloud granted to the project has fails the plan with `cloud-unknown` at `services.trainer.cloud`. In the dashboard, **Runs on** lists every granted Cloud's targets under the Cloud's name, and each Cloud on the project's Clouds tab can take services.\n\nChanging the project's default Cloud leaves services that name their Cloud where they are. A change to a Cloud itself, such as switching one of its targets, reaches every service placed on it.\n\n## Pick a target by tags\n\nYou don't have to name a target. Give your targets tags, then ask for the tags you need:\n\n```bash\nloomctl cloud-targets create my-project cloud_... \\\n --name eu-gpu --provider cloud-run --connection conn_... --tags eu,gpu\nloomctl cloud-targets update my-project cloud_... target_... \\\n --display-name \"EU GPU\" --tags eu,gpu,large --revision 1\n```\n\n```yaml\nversion: 1\ndefaults:\n cloud_tags: [eu]\nservices:\n web:\n source: node:apps/web\n cloud_tags: [frontend, eu]\n trainer:\n source: python:trainer\n cloud_tags: [gpu]\n environments:\n staging: { cloud_target: shared-gpu }\n```\n\nA tag is a lowercase slug of up to 32 characters, and a target carries at most 16. A service resolves to the one target that carries every tag it lists, looking only at the targets your project's grant allows. If none match, the plan fails with `cloud-tag-unmatched`. If several do, it fails with `cloud-tag-ambiguous` and names each, so you can add a tag only one carries or name the target with `cloud_target`.\n\n`cloud_target` and `cloud_tags` can't sit together at the same level. An environment override that sets one replaces whichever the service set, so staging above uses `shared-gpu` by name. `defaults.cloud_tags` applies to every service that sets no `cloud_target`, `cloud_tags`, `provider` or `target` of its own, and it can't be combined with `defaults.provider`. Like `cloud_target`, tags conflict with an effective direct `provider` or `target`, including an inherited one.\n\nOver HTTP, send `tags` when you create or update a target. Leave `tags` out of an update and they stay. Send `[]` and they're removed (`--clear-tags` in `loomctl`). Changing a target's tags advances its revision, so a plan approved against the old ones has to be planned again.\n\n## A default placement without targets\n\nA Cloud can have a default placement: one provider, one connection and an optional region. While a Cloud has no targets, that default is the only place its services go. Its connection has to be ready and belong to that provider's cloud.\n\n```bash\ncurl -X PUT .../api/v1/clouds/cloud_.../default-placement \\\n -d '{\"default_placement\":{\"provider\":\"vercel\",\"connection_id\":\"conn_...\",\"region\":\"iad1\"},\"revision\":1}'\n```\n\nYou can also pass `default_placement` when you create the Cloud, and send `\"default_placement\": null` to clear it. A service uses the default when it has no placement of its own. That keeps working after you add targets: adding a target only places the services that name or tag it. A service with its own `provider` keeps its direct placement.\n\nThe default reaches a project only when its grant covers the whole Cloud. If an admin granted a chosen set of targets, your services can use those targets but not the default.\n\nYou can set a first default at any time. Once the Cloud is a project's default Cloud, or runs a service its default placed, `default-placement` refuses to replace or clear it (HTTP 409). Change it with a reviewed switch, described in [Adopting and moving services](/docs/clouds/adopting-and-moving#switch-a-default)." }, { "path": "clouds/digitalocean", @@ -301,7 +301,7 @@ "title": "Add a service to a project", "description": "Add a service from your code, a database from the catalog, or any source path to a project's environment, from the dashboard, loomctl or the API.", "url": "https://www.loomplane.com/docs/guides/add-a-service", - "text": "You don't have to edit `loomplane.yaml` by hand to add something to a project. Open the project and click **Add service**. It's also in each environment's menu on the Overview, on the Services tab, and anywhere the project has nothing to deploy yet.\n\nThe dialog has three ways in:\n\n- **From your code** lists the services the latest analysis found that `loomplane.yaml` doesn't run yet. Each one comes with a free name, the provider your other services use if it runs that kind of service, and what it needs among what the manifest already has. When a new analysis finds a service, the Overview says so and offers to add it.\n- **Catalog** has the databases, caches, gateways and the rest. Pick where it runs: a checked server or Kubernetes cluster, or a provider that runs it for you, such as Cloud SQL for Postgres.\n- **Any source path** takes a directory, a Dockerfile or a Procfile process that analysis didn't pick up. The name follows the path until you type one.\n\nThen you choose what it needs and which services use it. Each service you tick gets its address in a variable, such as `DATABASE_URL` for Postgres or `BILLING_URL` for a service called `billing`, and the dialog shows the name next to it. You also choose whether it runs in every environment or only in the one you're adding it to.\n\nBefore anything is saved, the dialog asks the server what the change would be and shows you the lines it adds to `loomplane.yaml`. If the server would refuse it, you see why right there.\n\n**Add and plan** saves it as one new revision and plans the environment, then opens the plan for review. **Add only** saves it and leaves planning to you. Nothing deploys until someone approves a plan.\n\n## Only one environment\n\n\"Only staging\" writes `environments.staging.enabled: true` on the new entry, and `enabled: false` for every other environment the project has:\n\n```yaml\nresources:\n cache:\n kind: redis\n provider: server\n target: conn_01jc...\n environments:\n staging:\n enabled: true\n production:\n enabled: false\n```\n\nA service that runs in production can't need something that's off there. So if you add `cache` to staging only and tick `api` as a service that uses it, Loomplane refuses, and says to add `cache` everywhere or turn `api` off in production first. You'd get the same problem on the production plan otherwise, just later.\n\n## From a terminal\n\n`loomctl services suggest` lists what analysis found that the manifest doesn't run:\n\n```bash\n$ loomctl services suggest shop\nNAME SOURCE KIND PROVIDER NEEDS\nworker go:cmd/worker worker ecs-fargate db\n\nAdd one with: loomctl services add shop --suggested worker\n```\n\n`loomctl services add` adds any of the three, and plans `--env` (production by default):\n\n```bash\nloomctl services add shop --suggested worker --env staging\nloomctl services add shop --source services/billing --needs db --needed-by api\nloomctl services add shop --kind redis --needed-by api,worker --env staging --only\n```\n\nThe project can be its name, slug or ID. A name defaults to the suggestion's, the catalog kind's, or the source's last directory, numbered when it's taken. A catalog kind runs on your only ready server or cluster when you don't give `--target`, and when there are several, loomctl lists them so you can choose.\n\n`--dry-run` prints the `loomplane.yaml` it would save and changes nothing. `--no-plan` saves it without planning.\n\n## From the API\n\nIt's one edit: `POST /api/v1/projects/:id/manifest/edits` with `add_service` or `add_resource`. Both take `enabled_in` and `only` for the environment, and `needed_by` for the services that use it. `add_service` takes `source`, and optionally `repo`, `kind`, `provider`, `region`, `target`, `port`, `public` and `needs`.\n\n```json\n{\n \"add_service\": {\n \"name\": \"billing\",\n \"source\": \"services/billing\",\n \"needs\": [\"db\"],\n \"needed_by\": [\"api\"],\n \"enabled_in\": \"staging\",\n \"only\": true\n },\n \"dry_run\": true\n}\n```\n\n`dry_run` returns the revision the edit would save, YAML and all, without saving it. `GET /api/v1/projects/:id/manifest/suggestions` returns what analysis found, each one already shaped as an `add_service` edit. The first add to a project that has no `loomplane.yaml` yet starts one." + "text": "You don't have to edit `loomplane.yaml` by hand to add something to a project. Open the project and click **Add service**. It's also in each environment's menu on the Overview, on the Services tab, and anywhere the project has nothing to deploy yet.\n\nThe dialog has three ways in:\n\n- **From your code** lists the services the latest analysis found that `loomplane.yaml` doesn't run yet. Each one comes with a free name, the provider your other services use if it runs that kind of service, and what it needs among what the manifest already has. When a new analysis finds a service, the Overview says so and offers to add it.\n- **Catalog** has the databases, caches, gateways and the rest. Pick where it runs: a checked server or Kubernetes cluster, or a provider that runs it for you, such as Cloud SQL for Postgres.\n- **Any source path** takes a directory, a Dockerfile or a Procfile process that analysis didn't pick up. The name follows the path until you type one.\n\nA service's **Runs on** lists your Clouds' targets first, the project's default Cloud and then each other Cloud the project may use, each under its name, and then the providers you can use directly. Picking a target writes `cloud_target`, plus `cloud` when it's in a Cloud other than the default (see [Cloud targets](/docs/clouds/cloud-targets#use-another-cloud)).\n\nThen you choose what it needs and which services use it. Each service you tick gets its address in a variable, such as `DATABASE_URL` for Postgres or `BILLING_URL` for a service called `billing`, and the dialog shows the name next to it. You also choose whether it runs in every environment or only in the one you're adding it to.\n\nBefore anything is saved, the dialog asks the server what the change would be and shows you the lines it adds to `loomplane.yaml`. If the server would refuse it, you see why right there.\n\n**Add and plan** saves it as one new revision and plans the environment, then opens the plan for review. **Add only** saves it and leaves planning to you. Nothing deploys until someone approves a plan.\n\n## Only one environment\n\n\"Only staging\" writes `environments.staging.enabled: true` on the new entry, and `enabled: false` for every other environment the project has:\n\n```yaml\nresources:\n cache:\n kind: redis\n provider: server\n target: conn_01jc...\n environments:\n staging:\n enabled: true\n production:\n enabled: false\n```\n\nA service that runs in production can't need something that's off there. So if you add `cache` to staging only and tick `api` as a service that uses it, Loomplane refuses, and says to add `cache` everywhere or turn `api` off in production first. You'd get the same problem on the production plan otherwise, just later.\n\n## From a terminal\n\n`loomctl services suggest` lists what analysis found that the manifest doesn't run:\n\n```bash\n$ loomctl services suggest shop\nNAME SOURCE KIND PROVIDER NEEDS\nworker go:cmd/worker worker ecs-fargate db\n\nAdd one with: loomctl services add shop --suggested worker\n```\n\n`loomctl services add` adds any of the three, and plans `--env` (production by default):\n\n```bash\nloomctl services add shop --suggested worker --env staging\nloomctl services add shop --source services/billing --needs db --needed-by api\nloomctl services add shop --suggested trainer --cloud \"GPU Lab\" --cloud-target a100\nloomctl services add shop --kind redis --needed-by api,worker --env staging --only\n```\n\nThe project can be its name, slug or ID. A name defaults to the suggestion's, the catalog kind's, or the source's last directory, numbered when it's taken. A catalog kind runs on your only ready server or cluster when you don't give `--target`, and when there are several, loomctl lists them so you can choose.\n\n`--cloud-target` puts a service on a Cloud target, in the project's default Cloud unless `--cloud` names another, and replaces the provider a suggestion came with. It can't be combined with `--provider` or `--target`.\n\n`--dry-run` prints the `loomplane.yaml` it would save and changes nothing. `--no-plan` saves it without planning.\n\n## From the API\n\nIt's one edit: `POST /api/v1/projects/:id/manifest/edits` with `add_service` or `add_resource`. Both take `enabled_in` and `only` for the environment, and `needed_by` for the services that use it. `add_service` takes `source`, and optionally `repo`, `kind`, `cloud`, `cloud_target`, `provider`, `region`, `target`, `port`, `public` and `needs`. `cloud_target` and `cloud` can't be set with `provider` or `target`.\n\n```json\n{\n \"add_service\": {\n \"name\": \"billing\",\n \"source\": \"services/billing\",\n \"needs\": [\"db\"],\n \"needed_by\": [\"api\"],\n \"enabled_in\": \"staging\",\n \"only\": true\n },\n \"dry_run\": true\n}\n```\n\n`dry_run` returns the revision the edit would save, YAML and all, without saving it. `GET /api/v1/projects/:id/manifest/suggestions` returns what analysis found, each one already shaped as an `add_service` edit. The first add to a project that has no `loomplane.yaml` yet starts one." }, { "path": "guides/bitbucket-repositories", @@ -448,14 +448,14 @@ "title": "loomctl", "description": "Every loomctl command, grouped by what it does, with its main flags.", "url": "https://www.loomplane.com/docs/reference/loomctl", - "text": "`loomctl` is Loomplane's command-line client and MCP server. It calls the API through `pkg/client`, signed in as you or with an API key, so anything it does, a script can do the same way. Run `loomctl --help`, or `loomctl --help`, for the flags on your version.\n\n## Install\n\n```bash\nbrew install xraph/tap/loomctl\n```\n\nOn Linux, each release has a `.deb` and an `.rpm` for amd64 and arm64, and [Install on Linux](/docs/operations/linux#install-loomctl) walks through them. You can also install it from the `xraph` Scoop bucket, or unpack a release archive. To build from source, `make build-cli` writes `bin/loomctl`.\n\n## Connect to Loomplane\n\nOn your own machine, sign in as yourself:\n\n```bash\nloomctl login --url https://loomplane.example.com\n```\n\nIt prints a short code and opens the dashboard's **/device** page with the code filled in. Sign in there if you aren't already, check the code matches the one in your terminal, and approve it. `loomctl` picks up the sign-in a few seconds later. If you belong to more than one organization it asks which one to act in, or you can name it up front with `--org`. On a machine with no browser, add `--no-browser` and open the address it prints on your phone or laptop instead.\n\nThe sign-in is your own account, with your role in each organization, so you don't make or paste a key for it. loomctl renews it while you use it, and `loomctl logout` ends the session on the server as well as forgetting it here.\n\nCI wants an API key instead, since nobody is there to approve a code. `loomctl` finds the server and key in `LOOMPLANE_URL` and `LOOMPLANE_API_KEY`, or in the file `loomctl login` writes (`loomctl.json` under `loomplane` in your user config directory, readable only by you). The environment wins over the saved login.\n\n| Command | What it does |\n|---|---|\n| `login --url URL [--org ORG] [--no-browser]` | Signs you in through the browser and saves the sign-in |\n| `login --url URL --key KEY` | Checks an API key and saves it in place of a sign-in. `--key -` reads the key from standard input |\n| `organizations [--json]` | Lists the organizations your sign-in can act in, with a `*` by the current one |\n| `organizations use ORG` | Acts in another of your organizations, by slug, name or ID. An API key stays in its own |\n| `logout` | Forgets the saved login. A sign-in's session ends with it; a key still works until you revoke it |\n| `whoami [--json]` | Who loomctl acts as and what it may do |\n\n## Projects and analysis\n\n| Command | What it does |\n|---|---|\n| `projects [--json]` | Lists the organization's projects |\n| `projects create NAME --repo REPO` | Creates a project. Repeat `--repo` for each repository, and write `alias=repository` to name one |\n| `analyze PROJECT [--source ALIAS] [--ref REF] [--no-wait]` | Reads a project's repositories. `--source` is repeatable. `--ref` is a branch, tag or commit for one repository |\n| `manifest PROJECT [--draft]` | Prints the saved `loomplane.yaml`, or a draft from the latest analysis |\n| `manifest save PROJECT [-f FILE]` | Saves a new revision. The file defaults to `loomplane.yaml`, and `-` reads standard input |\n| `vars PROJECT [--json]` | Lists variables. Secrets show no value |\n| `vars set PROJECT KEY=VALUE [--env E] [--service S] [--secret]` | Sets a variable. `KEY=-` reads the value from standard input |\n\n## Teams\n\n| Command | What it does |\n|---|---|\n| `teams [--json]` | Lists teams with their member counts and roles, such as `developer on checkout-api` or `admin on the workspace` |\n| `teams show TEAM [--json]` | Shows a team's description, roles and members. `TEAM` is a slug, name or ID |\n| `teams create NAME [--description TEXT]` | Creates a team |\n| `teams delete TEAM --yes` | Deletes a team. Without `--yes` nothing is sent |\n| `teams add TEAM EMAIL` | Adds a workspace member, found by email |\n| `teams remove TEAM EMAIL` | Takes a person out of a team |\n| `teams grant TEAM viewer\\|developer\\|admin [--project P]` | Gives the team a role on a project, or on the whole workspace without `--project` |\n| `teams revoke TEAM [--project P]` | Removes the team's role on that project, or on the workspace |\n| `projects team PROJECT TEAM` | Names the team responsible for a project |\n| `projects team PROJECT --none` | Clears it |\n\nManaging teams needs `member:manage`. Setting a project's team needs `project:update` on it. See [Teams](/docs/concepts/teams).\n\n## The built-in agent\n\nThese need the agent on. On a server with `ai.enabled` off they print \"This Loomplane doesn't run the agent (ai.enabled is off).\" and exit 1.\n\n| Command | What it does |\n|---|---|\n| `agent [--project REF] [--conversation ID]` | Opens a chat at a `you> ` prompt. Each line is a message, and the answer streams in as the agent writes it. When the agent asks a question you can answer, it asks it right there (`agent asks: ...`, options numbered): type the text or an option's number, or press Enter to leave it pending. Other requests print how to answer them. `/new` starts a new conversation, `/stop` stops the agent's task, `/follow` watches a task you left pending, and `/quit` or the end of input leaves. Ctrl-C while the agent answers stops its task and takes you back to the prompt. At the prompt it leaves. `--conversation` carries on one you started, picking up the agent where it waits |\n| `agent ask PROMPT [--project REF] [--conversation ID] [--json] [--no-wait]` | Asks one thing and prints the answer. Text goes to standard output as it comes. Each tool the agent uses goes to standard error as `· name (risk)`, then ` ok`, ` failed: why` or ` refused: why`. A question for a person prints with how to answer it. `--json` prints each event as one JSON line on standard output and nothing else. With `--no-wait`, a task that waits for a person exits 3 and tells you the `loomctl agent --conversation ID` to carry on with. Ctrl-C stops the task and exits 130 |\n| `agent conversations [--project REF] [--json]` | Lists your conversations: ID, project, title, status and when they were last updated |\n| `agent conversations rename ID TITLE` | Renames one of your conversations (up to 120 characters) |\n| `agent conversations delete ID` | Deletes one of your conversations, and stops the agent if it's still on it |\n| `agent requests [--all] [--mine] [--json]` | Lists what the agent is asking people for: ID, kind, project, question, who it was sent to, who it's asked for, and its age. `--all` includes settled requests. `--mine` keeps what's asked of you, your teams or, for admins, the workspace. A plan to approve adds the line `approve with: loomctl approve PLAN --revision REV` |\n| `agent requests answer ID TEXT...` | Answers a question |\n| `agent requests provide ID` | Sets the secret the agent asked for. The value comes from standard input, hidden on a terminal, and a value given as an argument is refused. It's never printed |\n| `agent requests done ID` | Says you connected GitHub or a cloud account |\n| `agent requests decline ID [--reason TEXT]` | Turns a request down. The agent sees the reason |\n| `agent reports [--all \\| --status resolved\\|closed] [--project REF] [--json]` | Lists what the watcher found: ID, severity, project, environment, title, how often and how long ago it was seen, and its GitHub issue. You get the open reports unless you pass `--all` or a `--status` |\n| `agent reports show ID [--json]` | Shows one report: its facts, what the agent's investigation found (summary, likely cause, suggestions and how sure it is) and the issue link |\n| `agent reports close ID [--reason TEXT]` | Closes a report. The reason is kept with it |\n| `agent watcher [--json]` | Says whether the watcher is watching or paused, and why if it's paused. It also lists each GitHub installation and whether it has accepted the Issues permission, so you can see why an issue hasn't been opened |\n\n`agent ask` exits 0 when the agent finishes, 1 when it fails, is stopped, or refuses the message (a 409: it's still on your last one, it's off for your workspace, or the budget is spent), 3 when `--no-wait` met a request, and 130 after Ctrl-C. A run Loomplane's safety checks stopped prints \"Loomplane's safety checks stopped this answer.\" and exits 1.\n\nSee [What needs a person](/docs/agents/what-needs-a-person#requests) for who is asked and who can answer.\n\n### Releases\n\n| Command | What it does |\n|---|---|\n| `release prepare PROJECT [--from ENV] [--to ENV] [--scope ALIAS] [--replace] [--wait] [--json]` | Asks for a release. Loomplane plans the promotion, collects evidence and has the agent review it. It prints the report's ID and path. Without `--from` and `--to` it uses the project's only staging and production environments. `--scope` takes aliases and is repeatable or comma separated. `--replace` replaces a production plan someone else has open. With `--wait` it follows the report every 3 seconds until it finishes or waits for a person, then prints it |\n| `release report ID [--json]` | Shows a release report: its state and reason, the seven gates as `pass` or `FAIL` with their details, each source's direction, commits and migrations, the soak, canaries, coverage, images and budget, and the agent's concerns under \"From the agent\". Text from outside Loomplane is printed in quotation marks. A report waiting for a person ends with `approve with: loomctl approve PLAN --revision REV` |\n| `release list PROJECT [--json]` | Lists a project's release reports: ID, environments, state, how many gates passed and its age |\n| `release cancel ID` | Stops a preparation that's still going |\n\nPreparing needs `deployment:create` and `agent:use` on the project. `loomctl mcp` has no tool that prepares a release, so a model can't start one through it. See [Release preparation](/docs/agents/release-preparation).\n\n## Plans and deployments\n\n| Command | What it does |\n|---|---|\n| `plan PROJECT [--env production] [--from ENV] [--scope ALIAS] [--catalog] [--no-wait] [--json]` | Plans a manifest for an environment. `--from` pins the commits another environment runs, which makes it a promotion. `--scope` is repeatable. `--catalog` plans standalone resources |\n| `promote PROJECT [--from staging] [--to production] [--scope ALIAS] [--no-wait] [--json]` | Plans `--to` to run what `--from` runs, reusing its images where it can. Prints a `Soak:` line with how long `--from` has run those commits and whether it was healthy |\n| `rollback PROJECT --reason TEXT [--env production] [--deployment ID] [--no-wait] [--json]` | Plans an environment back to its previous successful release. `--reason` is required. It prints which deployment it undoes and which it restores, and the plan lists what it leaves in place. `--deployment` has to name the environment's newest |\n| `plans PROJECT [--json]` | Lists a project's plans |\n| `show PLAN_ID [--json]` | Shows what a plan would do and anything in the way, with a `Release:` line when the environment sets a release strategy. A promotion or rollback adds a line saying what it moves, which images it reuses and, for a rollback, what it leaves in place |\n| `approve PLAN_ID [--revision REV] [--yes] [--note TEXT] [--no-wait]` | Approves a plan, which deploys it, and follows the deployment. `--revision` approves only if the plan is still at that revision |\n| `reject PLAN_ID [--note TEXT]` | Rejects a plan |\n| `deployments PROJECT [--json]` | Lists a project's deployments |\n| `deployment ID [--watch] [--json]` | Shows a deployment step by step. A canary adds a `Canary:` line and a table of the current retry's verdicts (step, weight, service, verdict, errors, latency and reason). When a revert or promotion failed it adds a `NEEDS YOU` line, because traffic may still be split. `--watch` follows it and prints each verdict once as it arrives. A deployment with a post-deploy watch adds a `Watch:` section with the status, each service's verdict and the services it can't watch. The `--watch` flag follows the deployment, and the Watch section is the release watch, which is a different thing |\n| `retry DEPLOYMENT_ID [--no-wait]` | Retries a failed deployment from the step that failed |\n| `status PROJECT [--json]` | What runs each service and resource, with addresses and drift |\n\n## Database services and recovery\n\n| Command | What it does |\n|---|---|\n| `services create NAME --target CONN [--kind K] [--provider P] [--region R] [--env E] [--json]` | Plans a standalone database service. `--kind` is `postgres` (default), `mysql`, `mariadb`, `redis` or `valkey`. `--provider` is `server` (default), `kubernetes`, `rds` or `cloud-sql` |\n| `services add PROJECT (--suggested NAME \\| --source PATH \\| --kind K) [--name N] [--env E] [--only] [--needs A,B] [--needed-by A,B] [--provider P] [--target CONN] [--dry-run] [--no-plan] [--json]` | Adds a service to a project and plans `--env`: one analysis found, one from any source path, or a catalog kind. `--only` runs it in `--env` alone. The name and a catalog kind's target default when there's one obvious choice. See [Add a service](/docs/guides/add-a-service) |\n| `services suggest PROJECT [--json]` | Lists the services analysis found that the project's manifest doesn't run yet |\n| `backups PROJECT`, `backups show ID`, `backups create PROJECT --resource NAME`, `backups retry ID` | List, read, create and retry backups. `create` takes `--env` and `--request-id` |\n| `backups policy PROJECT --resource NAME --every-hours N [--disable]`, `backups policies PROJECT` | Set and list backup schedules |\n| `backups retention ID`, `backups retire ID`, `retirements ...` | Preview and run [retention](/docs/services/retention). `retirements`, `retirements show`, `retirements history`, `retirements retry` follow them |\n| `backups retention-policy`, `retention-set`, `retention-history`, `retention-pause` | Automatic deletion policy |\n| `backups native-sources`, `native-inventory`, `native-refresh` | Native cloud snapshot history |\n| `backups native-copies review`, `create`, `show`, `cleanup` | Native recovery copies |\n| `restores PROJECT`, `restores create BACKUP_ID`, `restores show ID`, `restores delete ID --yes` | Isolated test restores |\n| `storage CONNECTION_ID [--json]` | Read-only [storage inventory](/docs/services/storage-inventory) |\n\nRecovery commands that wait take `--wait` and `--timeout` (45 minutes by default, and it must be positive), plus `--json`.\n\n## Clouds, targets and infrastructure\n\n| Command | What it does |\n|---|---|\n| `clouds [PROJECT] [--organization]`, `clouds create`, `show`, `update`, `delete` | Manage Clouds. With `--organization` no project argument is needed |\n| `clouds assignment`, `assign`, `switch-default` | Assign a Cloud to an environment and change its default placement |\n| `cloud-targets`, `show`, `create`, `update`, `delete`, `switch` | Manage targets within a Cloud |\n| `cloud-grants CLOUD`, `grant CLOUD PROJECT [--targets IDS]`, `revoke CLOUD PROJECT` | Project access to a Cloud |\n| `cloud-syncs`, `show`, `wait`, `retry`, `revert`, `routing`, `apply` | Follow and recover a placement change |\n| `cloud-servers CLOUD`, `options`, `check`, `usage`, `preview`, `apply`, `drain`, `operations`, `show`, `retry`, `cancel` | Servers inside an organization Cloud |\n| `cloud-pools CLOUD`, `save`, `move`, `recover` | Server pools |\n| `dns-zones`, `create`, `update`, `verify`, `remove`, `project` | Organization DNS zones |\n| `domain-routes PROJECT`, `preview`, `apply`, `show`, `retry`, `verify`, `remove`, `ttl`, `history` | Domain routes |\n\nMost of these review before they act and apply only with `--yes`. Many take `--wait`, `--timeout` and `--request-id`. [Cloud targets](/docs/clouds/cloud-targets), [Adopting and moving services](/docs/clouds/adopting-and-moving) and [Your own servers](/docs/clouds/your-own-servers) show them in context.\n\n## Nodes\n\n`loomctl node` joins and manages machines that connect to Loomplane. `loomplane node` has the same subcommands. See [Nodes](/docs/clouds/nodes).\n\n| Command | What it does |\n|---|---|\n| `node join [--token TOKEN] [--name NAME] [--label K=V] [--allow ENDPOINTS] [--cloud ID] [--builder dedicated] [--edge] [--foreground] [--state-dir DIR]` | Joins this machine and installs the service. Reads the token from `LOOMPLANE_JOIN_TOKEN` too. Without a token it mints one with your login, and under `sudo` that is the login of the user who ran `sudo`. Needs root on Linux |\n| `node run [--state-dir DIR] [--root-allowlist]` | Runs the node in the foreground. `--root-allowlist` trusts only a root-owned `allow.json`; the systemd unit sets it |\n| `node status [--json]` | Shows this node's config, key fingerprint, endpoints and whether it runs |\n| `node allow ENDPOINT...` | Widens what Loomplane may use here: `docker`, `dial`, `probe`, `kube` or `firecracker`. Writes `allow.json`, then tells the running node. Needs root on Linux |\n| `node leave [--purge] [--purge-volumes [--yes-delete-volumes=NAME]]` | Revokes this node, stops its service and removes its config. The next join makes a fresh key. `--purge` also removes the containers and networks Loomplane made on this machine's Docker. `--purge-volumes` deletes its volumes and their data too, and asks you to type the node's name first; `--yes-delete-volumes=NAME` answers for you in a script |\n| `node drain NAME-OR-ID [--yes]` | Stops new placements on the node's server, after listing what runs there and warning about databases with no backups. Asks first unless you pass `--yes`. Moving what runs there is a reviewed move each, in the dashboard |\n| `node list [--json]` | Lists the organization's nodes |\n| `node revoke NAME-OR-ID` | Stops Loomplane trusting a node |\n| `node update --release TAG` | Replaces the node's binary with a signed release, and rolls back if the service won't start or stops within five seconds |\n| `node verify-release --release TAG --archive FILE --checksums FILE --bundle FILE` | Checks a downloaded release against its signature |\n\n`join`, `list`, `revoke` and `drain` take `--url` and `--key` too. `revoke NAME` only matches live nodes. A node that Loomplane revoked exits with code 77, including one that was off when you revoked it and finds out at its next connect.\n\n## AI agents\n\n| Command | What it does |\n|---|---|\n| `mcp [--allow-deploy]` | Serves Loomplane's tools over MCP on standard input and output. `--allow-deploy` also offers `approve_plan`, `retry_deployment` and `create_rollback`. See [MCP server](/docs/agents/mcp-server) |\n\n## Server commands\n\nThe `loomplane` binary has its own commands, run with the same configuration the server runs with:\n\n| Command | What it does |\n|---|---|\n| `loomplane` (also `serve`, `start`, `run`) | Serves the API and dashboard |\n| `loomplane info` | Prints name, version and environment |\n| `loomplane extensions` | Lists registered extensions |\n| `loomplane backup --out FILE` | Backs up the database to a file. `backup inspect FILE` reads it |\n| `loomplane restore FILE [--force]` | Restores a backup into an empty database |\n| `loomplane migrations` | Shows applied and pending migrations |\n| `loomplane migrate` | Applies pending migrations |\n\n`loomplane-worker` runs repository analysis. `loomplane-agent` is the federation destination agent, which isn't ready for production." + "text": "`loomctl` is Loomplane's command-line client and MCP server. It calls the API through `pkg/client`, signed in as you or with an API key, so anything it does, a script can do the same way. Run `loomctl --help`, or `loomctl --help`, for the flags on your version.\n\n## Install\n\n```bash\nbrew install xraph/tap/loomctl\n```\n\nOn Linux, each release has a `.deb` and an `.rpm` for amd64 and arm64, and [Install on Linux](/docs/operations/linux#install-loomctl) walks through them. You can also install it from the `xraph` Scoop bucket, or unpack a release archive. To build from source, `make build-cli` writes `bin/loomctl`.\n\n## Connect to Loomplane\n\nOn your own machine, sign in as yourself:\n\n```bash\nloomctl login --url https://loomplane.example.com\n```\n\nIt prints a short code and opens the dashboard's **/device** page with the code filled in. Sign in there if you aren't already, check the code matches the one in your terminal, and approve it. `loomctl` picks up the sign-in a few seconds later. If you belong to more than one organization it asks which one to act in, or you can name it up front with `--org`. On a machine with no browser, add `--no-browser` and open the address it prints on your phone or laptop instead.\n\nThe sign-in is your own account, with your role in each organization, so you don't make or paste a key for it. loomctl renews it while you use it, and `loomctl logout` ends the session on the server as well as forgetting it here.\n\nCI wants an API key instead, since nobody is there to approve a code. `loomctl` finds the server and key in `LOOMPLANE_URL` and `LOOMPLANE_API_KEY`, or in the file `loomctl login` writes (`loomctl.json` under `loomplane` in your user config directory, readable only by you). The environment wins over the saved login.\n\n| Command | What it does |\n|---|---|\n| `login --url URL [--org ORG] [--no-browser]` | Signs you in through the browser and saves the sign-in |\n| `login --url URL --key KEY` | Checks an API key and saves it in place of a sign-in. `--key -` reads the key from standard input |\n| `organizations [--json]` | Lists the organizations your sign-in can act in, with a `*` by the current one |\n| `organizations use ORG` | Acts in another of your organizations, by slug, name or ID. An API key stays in its own |\n| `logout` | Forgets the saved login. A sign-in's session ends with it; a key still works until you revoke it |\n| `whoami [--json]` | Who loomctl acts as and what it may do |\n\n## Projects and analysis\n\n| Command | What it does |\n|---|---|\n| `projects [--json]` | Lists the organization's projects |\n| `projects create NAME --repo REPO` | Creates a project. Repeat `--repo` for each repository, and write `alias=repository` to name one |\n| `analyze PROJECT [--source ALIAS] [--ref REF] [--no-wait]` | Reads a project's repositories. `--source` is repeatable. `--ref` is a branch, tag or commit for one repository |\n| `manifest PROJECT [--draft]` | Prints the saved `loomplane.yaml`, or a draft from the latest analysis |\n| `manifest save PROJECT [-f FILE]` | Saves a new revision. The file defaults to `loomplane.yaml`, and `-` reads standard input |\n| `vars PROJECT [--json]` | Lists variables. Secrets show no value |\n| `vars set PROJECT KEY=VALUE [--env E] [--service S] [--secret]` | Sets a variable. `KEY=-` reads the value from standard input |\n\n## Teams\n\n| Command | What it does |\n|---|---|\n| `teams [--json]` | Lists teams with their member counts and roles, such as `developer on checkout-api` or `admin on the workspace` |\n| `teams show TEAM [--json]` | Shows a team's description, roles and members. `TEAM` is a slug, name or ID |\n| `teams create NAME [--description TEXT]` | Creates a team |\n| `teams delete TEAM --yes` | Deletes a team. Without `--yes` nothing is sent |\n| `teams add TEAM EMAIL` | Adds a workspace member, found by email |\n| `teams remove TEAM EMAIL` | Takes a person out of a team |\n| `teams grant TEAM viewer\\|developer\\|admin [--project P]` | Gives the team a role on a project, or on the whole workspace without `--project` |\n| `teams revoke TEAM [--project P]` | Removes the team's role on that project, or on the workspace |\n| `projects team PROJECT TEAM` | Names the team responsible for a project |\n| `projects team PROJECT --none` | Clears it |\n\nManaging teams needs `member:manage`. Setting a project's team needs `project:update` on it. See [Teams](/docs/concepts/teams).\n\n## The built-in agent\n\nThese need the agent on. On a server with `ai.enabled` off they print \"This Loomplane doesn't run the agent (ai.enabled is off).\" and exit 1.\n\n| Command | What it does |\n|---|---|\n| `agent [--project REF] [--conversation ID]` | Opens a chat at a `you> ` prompt. Each line is a message, and the answer streams in as the agent writes it. When the agent asks a question you can answer, it asks it right there (`agent asks: ...`, options numbered): type the text or an option's number, or press Enter to leave it pending. Other requests print how to answer them. `/new` starts a new conversation, `/stop` stops the agent's task, `/follow` watches a task you left pending, and `/quit` or the end of input leaves. Ctrl-C while the agent answers stops its task and takes you back to the prompt. At the prompt it leaves. `--conversation` carries on one you started, picking up the agent where it waits |\n| `agent ask PROMPT [--project REF] [--conversation ID] [--json] [--no-wait]` | Asks one thing and prints the answer. Text goes to standard output as it comes. Each tool the agent uses goes to standard error as `· name (risk)`, then ` ok`, ` failed: why` or ` refused: why`. A question for a person prints with how to answer it. `--json` prints each event as one JSON line on standard output and nothing else. With `--no-wait`, a task that waits for a person exits 3 and tells you the `loomctl agent --conversation ID` to carry on with. Ctrl-C stops the task and exits 130 |\n| `agent conversations [--project REF] [--json]` | Lists your conversations: ID, project, title, status and when they were last updated |\n| `agent conversations rename ID TITLE` | Renames one of your conversations (up to 120 characters) |\n| `agent conversations delete ID` | Deletes one of your conversations, and stops the agent if it's still on it |\n| `agent requests [--all] [--mine] [--json]` | Lists what the agent is asking people for: ID, kind, project, question, who it was sent to, who it's asked for, and its age. `--all` includes settled requests. `--mine` keeps what's asked of you, your teams or, for admins, the workspace. A plan to approve adds the line `approve with: loomctl approve PLAN --revision REV` |\n| `agent requests answer ID TEXT...` | Answers a question |\n| `agent requests provide ID` | Sets the secret the agent asked for. The value comes from standard input, hidden on a terminal, and a value given as an argument is refused. It's never printed |\n| `agent requests done ID` | Says you connected GitHub or a cloud account |\n| `agent requests decline ID [--reason TEXT]` | Turns a request down. The agent sees the reason |\n| `agent reports [--all \\| --status resolved\\|closed] [--project REF] [--json]` | Lists what the watcher found: ID, severity, project, environment, title, how often and how long ago it was seen, and its GitHub issue. You get the open reports unless you pass `--all` or a `--status` |\n| `agent reports show ID [--json]` | Shows one report: its facts, what the agent's investigation found (summary, likely cause, suggestions and how sure it is) and the issue link |\n| `agent reports close ID [--reason TEXT]` | Closes a report. The reason is kept with it |\n| `agent watcher [--json]` | Says whether the watcher is watching or paused, and why if it's paused. It also lists each GitHub installation and whether it has accepted the Issues permission, so you can see why an issue hasn't been opened |\n\n`agent ask` exits 0 when the agent finishes, 1 when it fails, is stopped, or refuses the message (a 409: it's still on your last one, it's off for your workspace, or the budget is spent), 3 when `--no-wait` met a request, and 130 after Ctrl-C. A run Loomplane's safety checks stopped prints \"Loomplane's safety checks stopped this answer.\" and exits 1.\n\nSee [What needs a person](/docs/agents/what-needs-a-person#requests) for who is asked and who can answer.\n\n### Releases\n\n| Command | What it does |\n|---|---|\n| `release prepare PROJECT [--from ENV] [--to ENV] [--scope ALIAS] [--replace] [--wait] [--json]` | Asks for a release. Loomplane plans the promotion, collects evidence and has the agent review it. It prints the report's ID and path. Without `--from` and `--to` it uses the project's only staging and production environments. `--scope` takes aliases and is repeatable or comma separated. `--replace` replaces a production plan someone else has open. With `--wait` it follows the report every 3 seconds until it finishes or waits for a person, then prints it |\n| `release report ID [--json]` | Shows a release report: its state and reason, the seven gates as `pass` or `FAIL` with their details, each source's direction, commits and migrations, the soak, canaries, coverage, images and budget, and the agent's concerns under \"From the agent\". Text from outside Loomplane is printed in quotation marks. A report waiting for a person ends with `approve with: loomctl approve PLAN --revision REV` |\n| `release list PROJECT [--json]` | Lists a project's release reports: ID, environments, state, how many gates passed and its age |\n| `release cancel ID` | Stops a preparation that's still going |\n\nPreparing needs `deployment:create` and `agent:use` on the project. `loomctl mcp` has no tool that prepares a release, so a model can't start one through it. See [Release preparation](/docs/agents/release-preparation).\n\n## Plans and deployments\n\n| Command | What it does |\n|---|---|\n| `plan PROJECT [--env production] [--from ENV] [--scope ALIAS] [--catalog] [--no-wait] [--json]` | Plans a manifest for an environment. `--from` pins the commits another environment runs, which makes it a promotion. `--scope` is repeatable. `--catalog` plans standalone resources |\n| `promote PROJECT [--from staging] [--to production] [--scope ALIAS] [--no-wait] [--json]` | Plans `--to` to run what `--from` runs, reusing its images where it can. Prints a `Soak:` line with how long `--from` has run those commits and whether it was healthy |\n| `rollback PROJECT --reason TEXT [--env production] [--deployment ID] [--no-wait] [--json]` | Plans an environment back to its previous successful release. `--reason` is required. It prints which deployment it undoes and which it restores, and the plan lists what it leaves in place. `--deployment` has to name the environment's newest |\n| `plans PROJECT [--json]` | Lists a project's plans |\n| `show PLAN_ID [--json]` | Shows what a plan would do and anything in the way, with a `Release:` line when the environment sets a release strategy. A promotion or rollback adds a line saying what it moves, which images it reuses and, for a rollback, what it leaves in place |\n| `approve PLAN_ID [--revision REV] [--yes] [--note TEXT] [--no-wait]` | Approves a plan, which deploys it, and follows the deployment. `--revision` approves only if the plan is still at that revision |\n| `reject PLAN_ID [--note TEXT]` | Rejects a plan |\n| `deployments PROJECT [--json]` | Lists a project's deployments |\n| `deployment ID [--watch] [--json]` | Shows a deployment step by step. A canary adds a `Canary:` line and a table of the current retry's verdicts (step, weight, service, verdict, errors, latency and reason). When a revert or promotion failed it adds a `NEEDS YOU` line, because traffic may still be split. `--watch` follows it and prints each verdict once as it arrives. A deployment with a post-deploy watch adds a `Watch:` section with the status, each service's verdict and the services it can't watch. The `--watch` flag follows the deployment, and the Watch section is the release watch, which is a different thing |\n| `retry DEPLOYMENT_ID [--no-wait]` | Retries a failed deployment from the step that failed |\n| `status PROJECT [--json]` | What runs each service and resource, with addresses and drift |\n\n## Database services and recovery\n\n| Command | What it does |\n|---|---|\n| `services create NAME --target CONN [--kind K] [--provider P] [--region R] [--env E] [--json]` | Plans a standalone database service. `--kind` is `postgres` (default), `mysql`, `mariadb`, `redis` or `valkey`. `--provider` is `server` (default), `kubernetes`, `rds` or `cloud-sql` |\n| `services add PROJECT (--suggested NAME \\| --source PATH \\| --kind K) [--name N] [--env E] [--only] [--needs A,B] [--needed-by A,B] [--cloud-target T [--cloud C] \\| --provider P [--target CONN]] [--dry-run] [--no-plan] [--json]` | Adds a service to a project and plans `--env`: one analysis found, one from any source path, or a catalog kind. `--only` runs it in `--env` alone. The name and a catalog kind's target default when there's one obvious choice. See [Add a service](/docs/guides/add-a-service) |\n| `services suggest PROJECT [--json]` | Lists the services analysis found that the project's manifest doesn't run yet |\n| `backups PROJECT`, `backups show ID`, `backups create PROJECT --resource NAME`, `backups retry ID` | List, read, create and retry backups. `create` takes `--env` and `--request-id` |\n| `backups policy PROJECT --resource NAME --every-hours N [--disable]`, `backups policies PROJECT` | Set and list backup schedules |\n| `backups retention ID`, `backups retire ID`, `retirements ...` | Preview and run [retention](/docs/services/retention). `retirements`, `retirements show`, `retirements history`, `retirements retry` follow them |\n| `backups retention-policy`, `retention-set`, `retention-history`, `retention-pause` | Automatic deletion policy |\n| `backups native-sources`, `native-inventory`, `native-refresh` | Native cloud snapshot history |\n| `backups native-copies review`, `create`, `show`, `cleanup` | Native recovery copies |\n| `restores PROJECT`, `restores create BACKUP_ID`, `restores show ID`, `restores delete ID --yes` | Isolated test restores |\n| `storage CONNECTION_ID [--json]` | Read-only [storage inventory](/docs/services/storage-inventory) |\n\nRecovery commands that wait take `--wait` and `--timeout` (45 minutes by default, and it must be positive), plus `--json`.\n\n## Clouds, targets and infrastructure\n\n| Command | What it does |\n|---|---|\n| `clouds [PROJECT] [--organization]`, `clouds create`, `show`, `update`, `delete` | Manage Clouds. With `--organization` no project argument is needed |\n| `clouds default`, `make-default`, `switch-default` | Show or change the project's default Cloud, and change a Cloud's default placement |\n| `cloud-targets`, `show`, `create`, `update`, `delete`, `switch` | Manage targets within a Cloud |\n| `cloud-grants CLOUD`, `grant CLOUD PROJECT [--targets IDS]`, `revoke CLOUD PROJECT` | Project access to a Cloud |\n| `cloud-syncs`, `show`, `wait`, `retry`, `revert`, `routing`, `apply` | Follow and recover a placement change |\n| `cloud-servers CLOUD`, `options`, `check`, `usage`, `preview`, `apply`, `drain`, `operations`, `show`, `retry`, `cancel` | Servers inside an organization Cloud |\n| `cloud-pools CLOUD`, `save`, `move`, `recover` | Server pools |\n| `dns-zones`, `create`, `update`, `verify`, `remove`, `project` | Organization DNS zones |\n| `domain-routes PROJECT`, `preview`, `apply`, `show`, `retry`, `verify`, `remove`, `ttl`, `history` | Domain routes |\n\nMost of these review before they act and apply only with `--yes`. Many take `--wait`, `--timeout` and `--request-id`. [Cloud targets](/docs/clouds/cloud-targets), [Adopting and moving services](/docs/clouds/adopting-and-moving) and [Your own servers](/docs/clouds/your-own-servers) show them in context.\n\n## Nodes\n\n`loomctl node` joins and manages machines that connect to Loomplane. `loomplane node` has the same subcommands. See [Nodes](/docs/clouds/nodes).\n\n| Command | What it does |\n|---|---|\n| `node join [--token TOKEN] [--name NAME] [--label K=V] [--allow ENDPOINTS] [--cloud ID] [--builder dedicated] [--edge] [--foreground] [--state-dir DIR]` | Joins this machine and installs the service. Reads the token from `LOOMPLANE_JOIN_TOKEN` too. Without a token it mints one with your login, and under `sudo` that is the login of the user who ran `sudo`. Needs root on Linux |\n| `node run [--state-dir DIR] [--root-allowlist]` | Runs the node in the foreground. `--root-allowlist` trusts only a root-owned `allow.json`; the systemd unit sets it |\n| `node status [--json]` | Shows this node's config, key fingerprint, endpoints and whether it runs |\n| `node allow ENDPOINT...` | Widens what Loomplane may use here: `docker`, `dial`, `probe`, `kube` or `firecracker`. Writes `allow.json`, then tells the running node. Needs root on Linux |\n| `node leave [--purge] [--purge-volumes [--yes-delete-volumes=NAME]]` | Revokes this node, stops its service and removes its config. The next join makes a fresh key. `--purge` also removes the containers and networks Loomplane made on this machine's Docker. `--purge-volumes` deletes its volumes and their data too, and asks you to type the node's name first; `--yes-delete-volumes=NAME` answers for you in a script |\n| `node drain NAME-OR-ID [--yes]` | Stops new placements on the node's server, after listing what runs there and warning about databases with no backups. Asks first unless you pass `--yes`. Moving what runs there is a reviewed move each, in the dashboard |\n| `node list [--json]` | Lists the organization's nodes |\n| `node revoke NAME-OR-ID` | Stops Loomplane trusting a node |\n| `node update --release TAG` | Replaces the node's binary with a signed release, and rolls back if the service won't start or stops within five seconds |\n| `node verify-release --release TAG --archive FILE --checksums FILE --bundle FILE` | Checks a downloaded release against its signature |\n\n`join`, `list`, `revoke` and `drain` take `--url` and `--key` too. `revoke NAME` only matches live nodes. A node that Loomplane revoked exits with code 77, including one that was off when you revoked it and finds out at its next connect.\n\n## AI agents\n\n| Command | What it does |\n|---|---|\n| `mcp [--allow-deploy]` | Serves Loomplane's tools over MCP on standard input and output. `--allow-deploy` also offers `approve_plan`, `retry_deployment` and `create_rollback`. See [MCP server](/docs/agents/mcp-server) |\n\n## Server commands\n\nThe `loomplane` binary has its own commands, run with the same configuration the server runs with:\n\n| Command | What it does |\n|---|---|\n| `loomplane` (also `serve`, `start`, `run`) | Serves the API and dashboard |\n| `loomplane info` | Prints name, version and environment |\n| `loomplane extensions` | Lists registered extensions |\n| `loomplane backup --out FILE` | Backs up the database to a file. `backup inspect FILE` reads it |\n| `loomplane restore FILE [--force]` | Restores a backup into an empty database |\n| `loomplane migrations` | Shows applied and pending migrations |\n| `loomplane migrate` | Applies pending migrations |\n\n`loomplane-worker` runs repository analysis. `loomplane-agent` is the federation destination agent, which isn't ready for production." }, { "path": "reference/loomplane-yaml", "title": "loomplane.yaml", "description": "Every field of the loomplane.yaml manifest, with its type, limits and meaning.", "url": "https://www.loomplane.com/docs/reference/loomplane-yaml", - "text": "This is the complete field reference. For how to think about a manifest, read [The manifest](/docs/concepts/the-manifest) first. The JSON schema at `pkg/manifest/schema.json` (`$id` `https://loomplane.dev/schemas/loomplane.json`) is the machine-readable version, and it's also the MCP resource `loomplane://schema/loomplane.yaml`. Loomplane rejects unknown fields and unsupported versions. A manifest can be up to 256 KiB.\n\n## Top level\n\n| Field | Type | Meaning |\n|---|---|---|\n| `version` | `1` or `2` | Required. `1` for all existing workflows. `2` adds the optional `federation` section |\n| `defaults` | object | `provider`, `region` and `cloud_tags` for everything that doesn't set its own |\n| `services` | map, up to 100 | What the application runs, by name |\n| `resources` | map, up to 100 | Backing services, by name. A resource can't share a service's name |\n| `gateways` | map, up to 10 | Public entry points that route by path |\n| `links` | map, up to 5 | Private network links between Google Cloud and AWS |\n| `environments` | map | `release`: how each environment's releases go live. Version 1 only. See [below](#environments) |\n| `ignore` | object | `resources`: kinds analysis found that you don't use |\n| `held` | object | `same_address`: `block` (default) or `warn` |\n| `federation` | object | Version 2 only. See [below](#federation-version-2) |\n\nNames (of services, resources, gateways, links and environments in overrides) match `^[a-z][a-z0-9-]{0,39}$`: lower case letters, digits and hyphens, starting with a letter, 40 characters at most.\n\n## defaults\n\n| Field | Meaning |\n|---|---|\n| `provider` | Provider for every service, resource and gateway that sets none |\n| `region` | Region for the same. It only applies together with the default provider: a service that names another provider doesn't take the default region |\n| `cloud_tags` | Up to 8 tags used to pick a Cloud target for every service with no placement of its own. Can't be combined with `provider` |\n\n## services\n\n| Field | Type | Meaning |\n|---|---|---|\n| `source` | string | Required. Where the service's code is, as analysis found it: a Go main package's directory, a Rust binary's source file, a Node package's, Python project's or JVM module's directory, or a Dockerfile. A Python Procfile process other than `web` is `shop/Procfile/worker`. When two ecosystems have a service at one path, prefix the ecosystem: `go:`, `rust:`, `node:`, `python:`, `jvm:` or `container:` |\n| `repo` | string | The alias of the repository the service is in. A project with one repository can leave it out |\n| `kind` | enum | Corrects what analysis decided: `http-service`, `web-app`, `static-site` or `worker` |\n| `build` | object | See [build](#build) |\n| `provider` | string | Where it runs, by the provider's name |\n| `region` | string | The provider's region |\n| `target` | `conn_...` | The checked server or Kubernetes connection to run on |\n| `cloud_target` | string | A named target in the environment's assigned Cloud. Can't be set with `cloud_tags` |\n| `cloud_tags` | array | Up to 8 tags. Selects the one target that carries every tag. Can't be set with `cloud_target` |\n| `endpoint` | object | See [endpoint](#endpoint) |\n| `health_path` | string | A readiness path, such as `/_/health`. Starts with `/` |\n| `port` | 1 to 65535 | The port it listens on. Without it, the one its Dockerfile exposes, or 8080 with a warning |\n| `public` | boolean | Whether it gets an address on the internet. Yes for anything that serves HTTP, no for a worker, unless you say |\n| `scale` | `{min, max}` | Instances. `min` is 0 or more, `max` is 1 to 100. On targets that let you choose |\n| `size` | `{cpu, memory}` | `cpu` is virtual CPUs above 0 and up to 8 (such as 0.5 or 2). `memory` is MiB, 128 to 32768 |\n| `needs` | array of names | Resources and services it talks to. Each gets it an address in a variable, and it deploys after them |\n| `need_options` | map | Options passed to a need, by need and then by option name |\n| `enabled` | boolean | `false` leaves it out |\n| `environments` | map | Overrides by environment name. Takes every field above except `source`, `repo`, `kind`, `build`, `needs` and `need_options` |\n\n`provider`, `cloud_target` and `cloud_tags` can't be mixed at the same level. An effective direct `provider` or `target` also conflicts with Cloud placement, including one inherited from `defaults`.\n\n### build\n\n| Field | Meaning |\n|---|---|\n| `context` | The directory its Dockerfile builds from, from the repository root. `.` is the root. Without it, the context a Compose file gives the Dockerfile, or the Dockerfile's own directory |\n| `builder` | For Kubernetes source builds: the `conn_...` of the SSH/Docker builder |\n| `registry` | The `conn_...` of the OCI registry |\n| `image` | An existing image pinned as `registry/repository@sha256:...`, instead of building |\n\nLoomplane passes the Dockerfile to the build by its path from the context, so it can sit anywhere. A service without a Dockerfile is built from its source, and `build` on it is ignored with a warning.\n\n### endpoint\n\nSettings for a service on your own server or cluster.\n\n| Field | Meaning |\n|---|---|\n| `host_port` | The published host port, 1 to 65535 |\n| `hostname` | The public hostname |\n| `ingress_class` | The Kubernetes ingress class |\n| `tls_secret` | The name of an existing Kubernetes TLS secret |\n\n### need_options\n\nOptions a service hands to something it needs, by need name and then option name:\n\n```yaml\nservices:\n api:\n source: services/api\n needs: [fabriq]\n need_options:\n fabriq:\n tenant: acme\n```\n\nThe need has to be in `needs`. Option names are lower case letters, digits and underscores, start with a letter and run to 32 characters. A value is up to 200 characters with no newline or other control character. Which options a kind accepts is checked when you plan.\n\nThe dashboard and `POST /projects/:id/manifest/edits` can change these in place without touching your comments. `link` adds a need to a service (with options if you give them, replacing old ones as a whole; with none, they stay). `unlink` removes the need and its options, and fails if the service doesn't need it. `set_use` sets one dependency on a catalog resource and leaves the rest of its `uses` alone. Send one of the three per edit.\n\n## resources\n\n| Field | Meaning |\n|---|---|\n| `kind` | Required. `postgres`, `mysql`, `mariadb`, `redis`, `valkey`, `mongodb`, `kafka`, `rabbitmq`, `nats`, `object-storage`, `search`, `memcached`, `clickhouse` and so on: the names analysis uses, or a catalog kind |\n| `provider`, `region` | Where it's provisioned |\n| `version` | The engine's version, such as `\"17\"`. Without it, the provider's newest |\n| `target` | The `conn_...` of the checked server or Kubernetes connection a catalog resource runs on |\n| `uses` | Where a catalog resource gets each dependency |\n| `settings` | Values a catalog kind takes, by setting name. Names follow the need option rule; a value is up to 1024 characters. The kind says which settings it has and what each must look like, and that's checked when you plan |\n| `environments` | `provider`, `region`, `enabled`, `gpu`, `target` or `settings` by environment name |\n\nAn environment's `target` replaces the resource's, and an environment that changes the provider doesn't keep the resource's target. Each setting an environment sets replaces that one setting, and the rest come from the resource.\n\n`POST /projects/:id/manifest/edits` can change a resource in place as well. `update_resource` sets its `provider`, `target`, `gpu` or `settings`, leaving out what you don't send. A setting sent as `\"\"` is deleted, and `clear_gpu` drops the GPU. Send `environment` with it and the change goes under that environment instead, where `enabled` turns the resource on or off. `remove_resource` takes the resource out, but not while a service needs it or another resource uses it: unlink those first.\n\n### uses\n\nA catalog resource can depend on other things, such as a Postgres for its data or a Redis for its cache. By default Loomplane provisions a new one of each and wires it in. `uses` chooses something else, one dependency at a time, keyed by the dependency's name as the catalog lists it.\n\n| Field | Meaning |\n|---|---|\n| `resource` | Use another resource in this manifest. It must exist and can't be the resource itself |\n| `external` | Connect to an endpoint you added to the catalog, by its ID (`endpoint_` and 26 characters) |\n| `enabled` | Turn an optional dependency on or off. `false` can't go with `resource` or `external` |\n\nSet `resource` or `external`, not both. Set nothing and you get a new one.\n\n```yaml\nresources:\n db:\n kind: postgres\n gateway:\n kind: sample\n target: conn_your_server\n uses:\n postgres:\n resource: db\n redis:\n external: endpoint_01jbz7q5mx8vh3k2r9t4w6y0ae\n falkordb:\n enabled: true\n```\n\n`sample` stands in for a catalog kind with those three dependencies, and `conn_your_server` for one of your checked connections. The manifest checks what it can see on its own: that `db` is in it and isn't `gateway` itself, and that the endpoint ID has the right form. The rest waits until you plan, when Loomplane finds out whether the kind has a dependency called `postgres`, whether `db` is a kind it accepts, and whether the endpoint answers from the target.\n\n## gateways\n\n| Field | Meaning |\n|---|---|\n| `provider`, `region` | Where it runs: `cloud-run` or `ecs-fargate` |\n| `routes` | Required. 1 to 50 routes |\n| `environments` | `provider`, `region` or `enabled` by environment name |\n\nA route is `{path, to, strip_prefix}`. `path` is a prefix such as `/api` that matches `/api` and anything under `/api/`. `to` is the service name. `strip_prefix` removes the prefix first, so `/api/users` arrives as `/users`. The longest matching path wins.\n\n## links\n\n| Field | Meaning |\n|---|---|\n| `between` | Required. The two clouds it joins: `gcp` and `aws` |\n| `region` | Where the Google Cloud side runs. Put it where the Cloud Run services that use it run |\n| `environments` | `region` or `enabled` by environment name |\n\nA link needs more than a connection check asks for. The Google Cloud key needs Compute Network Admin (`roles/compute.networkAdmin`). The AWS key needs `ec2:CreateVpnGateway`, `ec2:AttachVpnGateway`, `ec2:DetachVpnGateway`, `ec2:DeleteVpnGateway`, `ec2:DescribeVpnGateways`, `ec2:CreateCustomerGateway`, `ec2:DeleteCustomerGateway`, `ec2:CreateVpnConnection`, `ec2:DeleteVpnConnection`, `ec2:DescribeVpnConnections`, `ec2:DescribeRouteTables`, `ec2:EnableVgwRoutePropagation` and `ec2:CreateTags`. See [Gateways and networking](/docs/concepts/gateways-and-networking#links) for what a link builds and bills.\n\n## environments\n\n`environments..release` says how that environment's releases go live. An environment without a release block deploys the way it always has. The block is for version 1 manifests: a version 2 manifest that carries one is refused until federation and releases work together.\n\n| Field | Type | Meaning |\n|---|---|---|\n| `strategy` | `direct`, `blue_green` or `canary` | Required. `canary` moves traffic to the new version in steps |\n| `steps` | list of 1 to 10 integers | Canary only. Traffic percentages, strictly increasing, each 1 to 100, ending at 100. Default `[5, 25, 50, 100]` |\n| `hold` | duration | Canary only. How long to watch each step, in whole minutes from `1m` to `24h`, such as `10m` or `1h30m`. Default `10m` |\n| `thresholds.error_rate` | percentage | Highest share of failed requests a step may show. Above 0% and at most 100%. Default `1%` |\n| `thresholds.error_rate_delta` | percentage | How far above the current version's failure share a step may be. Above 0% and at most 100%. Default `0.5%` |\n| `thresholds.p95_latency_ratio` | number | How many times the current version's p95 latency a step may reach, from 1 to 10. Default `1.3` |\n| `min_requests` | integer | The fewest requests a step needs before its health counts, 1 to 1,000,000. Default `200` |\n| `watch` | duration | How long Loomplane watches a release's health after it deploys, in whole minutes up to `24h`, such as `15m` or `1h`. `0` turns it off. Default `15m` for `canary` and `blue_green`, and no watch for `direct`. A breach rolls the release back automatically |\n\nPercentages are written with a percent sign, such as `1%` or `0.5%`. Thresholds and `min_requests` are allowed with every strategy, because a canary and the post-deploy watch both read them, and a promotion's staging soak reads the error ceiling and `min_requests`. `steps` and `hold` are refused with any strategy but `canary`. Environment names follow the same rule as other names.\n\n```yaml\nenvironments:\n production:\n release:\n strategy: canary\n steps: [5, 25, 50, 100]\n hold: 10m\n thresholds:\n error_rate: 1%\n error_rate_delta: 0.5%\n p95_latency_ratio: 1.3\n min_requests: 200\n```\n\nSee [Canary releases](/docs/concepts/canary-releases) for what a canary does with these settings, and [Promotion and rollback](/docs/concepts/promotion-and-rollback#watch-a-release-after-it-deploys) for the watch.\n\n## ignore\n\n`ignore.resources` lists resource kinds analysis found that the application doesn't use, so plans stop asking about them.\n\n## held\n\n`held.same_address` decides what a scoped plan does when a held service uses a service that was deleted outside Loomplane and that the plan creates again. The held service isn't redeployed, so it keeps the old address.\n\nWith `block` (the default) that's a problem until you add the held repository to the scope. With `warn` it's a warning, but only when the planner can tell the address won't change: a Cloud Run service created again with the name, region and connection it had, which gets the same URL. Anything else, including a replacement, is still a problem.\n\n```yaml\nheld:\n same_address: warn\n```\n\n## Variables Loomplane adds\n\n| Needs | Variable |\n|---|---|\n| Postgres, MySQL, MariaDB | `DATABASE_URL` |\n| Redis, Valkey | `REDIS_URL` |\n| Memcached | `MEMCACHED_SERVERS` |\n| MongoDB | `MONGODB_URI` |\n| AMQP brokers | `AMQP_URL` |\n| Kafka | `KAFKA_BROKERS` |\n| NATS | `NATS_URL` |\n| Object storage | `STORAGE_URL` |\n| Search | `SEARCH_URL` |\n| ClickHouse | `CLICKHOUSE_URL` |\n| Another service | Its name in capitals plus `_URL` (`API_URL`) |\n\n## Provider names\n\n`vercel`, `cloud-run`, `cloud-sql`, `memorystore`, `cloud-storage`, `ecs-fargate`, `rds`, `elasticache`, `s3`, `cross-cloud-vpn`, `render`, `digitalocean`, `azure-container-apps`, `azure-database`, `azure-managed-redis`, `server`, `kubernetes`, plus any [provider plugin](/docs/extending/provider-plugins). The [Clouds overview](/docs/clouds) says what each runs and provisions.\n\n## Federation (version 2)\n\n Federation is still being built. Version 2 records federation proposals, and its plans stay blocked until destination agents, network drivers and policy enforcement pass qualification. Don't use it to try to get private traffic between clouds.\n\nTo convert a file, review its destinations and public exposure, change `version` explicitly, add the `federation` section and review the resulting blocked plan. Keep the original for rollback. The editor never upgrades it for you.\n\n| Map | Contents |\n|---|---|\n| `destinations` | Name to `{id: dest_..., environments: {env: dest_...}}`. IDs must resolve in the organization, project and environment |\n| `network_links` | `{from, to, transport}` where `transport` is `imported` or `ipsec` |\n| `service_exports` | `{service, destination, exposure: private, port, protocol, identity}`. `protocol` is `http`, `grpc` or `tcp`, and `identity` is `workload` or `gateway` |\n| `access_grants` | `{source_service, source_destination, export, methods, paths, grpc_methods, expires_at}` |\n| `placements` | `{service, destination}` |\n\nEach map allows 100 entries. A grant allows 16 HTTP methods, 32 paths of up to 1024 bytes, or 32 gRPC methods of up to 256 bytes (gRPC selectors look like `/package.Service/Method`). `expires_at` is RFC 3339, and an expired grant is rejected at execution even if the manifest still parses. Exports need `public: false` and an explicit service `port` that matches. Every export and source grant needs a matching placement. `needs` still controls configuration and startup order and grants no access.\n\nConnections supply credentials through Vault, so manifests contain no tokens, kubeconfigs or certificate keys. Management is off by default and turned on with `federation.enabled`. See [Configuration](/docs/reference/configuration)." + "text": "This is the complete field reference. For how to think about a manifest, read [The manifest](/docs/concepts/the-manifest) first. The JSON schema at `pkg/manifest/schema.json` (`$id` `https://loomplane.dev/schemas/loomplane.json`) is the machine-readable version, and it's also the MCP resource `loomplane://schema/loomplane.yaml`. Loomplane rejects unknown fields and unsupported versions. A manifest can be up to 256 KiB.\n\n## Top level\n\n| Field | Type | Meaning |\n|---|---|---|\n| `version` | `1` or `2` | Required. `1` for all existing workflows. `2` adds the optional `federation` section |\n| `defaults` | object | `provider`, `region` and `cloud_tags` for everything that doesn't set its own |\n| `services` | map, up to 100 | What the application runs, by name |\n| `resources` | map, up to 100 | Backing services, by name. A resource can't share a service's name |\n| `gateways` | map, up to 10 | Public entry points that route by path |\n| `links` | map, up to 5 | Private network links between Google Cloud and AWS |\n| `environments` | map | `release`: how each environment's releases go live. Version 1 only. See [below](#environments) |\n| `ignore` | object | `resources`: kinds analysis found that you don't use |\n| `held` | object | `same_address`: `block` (default) or `warn` |\n| `federation` | object | Version 2 only. See [below](#federation-version-2) |\n\nNames (of services, resources, gateways, links and environments in overrides) match `^[a-z][a-z0-9-]{0,39}$`: lower case letters, digits and hyphens, starting with a letter, 40 characters at most.\n\n## defaults\n\n| Field | Meaning |\n|---|---|\n| `provider` | Provider for every service, resource and gateway that sets none |\n| `region` | Region for the same. It only applies together with the default provider: a service that names another provider doesn't take the default region |\n| `cloud_tags` | Up to 8 tags used to pick a Cloud target for every service with no placement of its own. Can't be combined with `provider` |\n\n## services\n\n| Field | Type | Meaning |\n|---|---|---|\n| `source` | string | Required. Where the service's code is, as analysis found it: a Go main package's directory, a Rust binary's source file, a Node package's, Python project's or JVM module's directory, or a Dockerfile. A Python Procfile process other than `web` is `shop/Procfile/worker`. When two ecosystems have a service at one path, prefix the ecosystem: `go:`, `rust:`, `node:`, `python:`, `jvm:` or `container:` |\n| `repo` | string | The alias of the repository the service is in. A project with one repository can leave it out |\n| `kind` | enum | Corrects what analysis decided: `http-service`, `web-app`, `static-site` or `worker` |\n| `build` | object | See [build](#build) |\n| `provider` | string | Where it runs, by the provider's name |\n| `region` | string | The provider's region |\n| `target` | `conn_...` | The checked server or Kubernetes connection to run on |\n| `cloud` | string | The name of the Cloud `cloud_target`, `cloud_tags` or the Cloud's default placement resolve in: any Cloud granted to the project. Leave it out for the project's default Cloud. An environment override that names a target without `cloud` is in the default Cloud. Can't be set with `provider` or `target` |\n| `cloud_target` | string | A named target in the service's Cloud: the one `cloud` names, or the project's default. Can't be set with `cloud_tags` |\n| `cloud_tags` | array | Up to 8 tags. Selects the one target that carries every tag. Can't be set with `cloud_target` |\n| `endpoint` | object | See [endpoint](#endpoint) |\n| `health_path` | string | A readiness path, such as `/_/health`. Starts with `/` |\n| `port` | 1 to 65535 | The port it listens on. Without it, the one its Dockerfile exposes, or 8080 with a warning |\n| `public` | boolean | Whether it gets an address on the internet. Yes for anything that serves HTTP, no for a worker, unless you say |\n| `scale` | `{min, max}` | Instances. `min` is 0 or more, `max` is 1 to 100. On targets that let you choose |\n| `size` | `{cpu, memory}` | `cpu` is virtual CPUs above 0 and up to 8 (such as 0.5 or 2). `memory` is MiB, 128 to 32768 |\n| `needs` | array of names | Resources and services it talks to. Each gets it an address in a variable, and it deploys after them |\n| `need_options` | map | Options passed to a need, by need and then by option name |\n| `enabled` | boolean | `false` leaves it out |\n| `environments` | map | Overrides by environment name. Takes every field above except `source`, `repo`, `kind`, `build`, `needs` and `need_options` |\n\n`provider`, `cloud_target` and `cloud_tags` can't be mixed at the same level. An effective direct `provider` or `target` also conflicts with Cloud placement, including one inherited from `defaults`.\n\n### build\n\n| Field | Meaning |\n|---|---|\n| `context` | The directory its Dockerfile builds from, from the repository root. `.` is the root. Without it, the context a Compose file gives the Dockerfile, or the Dockerfile's own directory |\n| `builder` | For Kubernetes source builds: the `conn_...` of the SSH/Docker builder |\n| `registry` | The `conn_...` of the OCI registry |\n| `image` | An existing image pinned as `registry/repository@sha256:...`, instead of building |\n\nLoomplane passes the Dockerfile to the build by its path from the context, so it can sit anywhere. A service without a Dockerfile is built from its source, and `build` on it is ignored with a warning.\n\n### endpoint\n\nSettings for a service on your own server or cluster.\n\n| Field | Meaning |\n|---|---|\n| `host_port` | The published host port, 1 to 65535 |\n| `hostname` | The public hostname |\n| `ingress_class` | The Kubernetes ingress class |\n| `tls_secret` | The name of an existing Kubernetes TLS secret |\n\n### need_options\n\nOptions a service hands to something it needs, by need name and then option name:\n\n```yaml\nservices:\n api:\n source: services/api\n needs: [fabriq]\n need_options:\n fabriq:\n tenant: acme\n```\n\nThe need has to be in `needs`. Option names are lower case letters, digits and underscores, start with a letter and run to 32 characters. A value is up to 200 characters with no newline or other control character. Which options a kind accepts is checked when you plan.\n\nThe dashboard and `POST /projects/:id/manifest/edits` can change these in place without touching your comments. `link` adds a need to a service (with options if you give them, replacing old ones as a whole; with none, they stay). `unlink` removes the need and its options, and fails if the service doesn't need it. `set_use` sets one dependency on a catalog resource and leaves the rest of its `uses` alone. Send one of the three per edit.\n\n## resources\n\n| Field | Meaning |\n|---|---|\n| `kind` | Required. `postgres`, `mysql`, `mariadb`, `redis`, `valkey`, `mongodb`, `kafka`, `rabbitmq`, `nats`, `object-storage`, `search`, `memcached`, `clickhouse` and so on: the names analysis uses, or a catalog kind |\n| `provider`, `region` | Where it's provisioned |\n| `version` | The engine's version, such as `\"17\"`. Without it, the provider's newest |\n| `target` | The `conn_...` of the checked server or Kubernetes connection a catalog resource runs on |\n| `uses` | Where a catalog resource gets each dependency |\n| `settings` | Values a catalog kind takes, by setting name. Names follow the need option rule; a value is up to 1024 characters. The kind says which settings it has and what each must look like, and that's checked when you plan |\n| `environments` | `provider`, `region`, `enabled`, `gpu`, `target` or `settings` by environment name |\n\nAn environment's `target` replaces the resource's, and an environment that changes the provider doesn't keep the resource's target. Each setting an environment sets replaces that one setting, and the rest come from the resource.\n\n`POST /projects/:id/manifest/edits` can change a resource in place as well. `update_resource` sets its `provider`, `target`, `gpu` or `settings`, leaving out what you don't send. A setting sent as `\"\"` is deleted, and `clear_gpu` drops the GPU. Send `environment` with it and the change goes under that environment instead, where `enabled` turns the resource on or off. `remove_resource` takes the resource out, but not while a service needs it or another resource uses it: unlink those first.\n\n### uses\n\nA catalog resource can depend on other things, such as a Postgres for its data or a Redis for its cache. By default Loomplane provisions a new one of each and wires it in. `uses` chooses something else, one dependency at a time, keyed by the dependency's name as the catalog lists it.\n\n| Field | Meaning |\n|---|---|\n| `resource` | Use another resource in this manifest. It must exist and can't be the resource itself |\n| `external` | Connect to an endpoint you added to the catalog, by its ID (`endpoint_` and 26 characters) |\n| `enabled` | Turn an optional dependency on or off. `false` can't go with `resource` or `external` |\n\nSet `resource` or `external`, not both. Set nothing and you get a new one.\n\n```yaml\nresources:\n db:\n kind: postgres\n gateway:\n kind: sample\n target: conn_your_server\n uses:\n postgres:\n resource: db\n redis:\n external: endpoint_01jbz7q5mx8vh3k2r9t4w6y0ae\n falkordb:\n enabled: true\n```\n\n`sample` stands in for a catalog kind with those three dependencies, and `conn_your_server` for one of your checked connections. The manifest checks what it can see on its own: that `db` is in it and isn't `gateway` itself, and that the endpoint ID has the right form. The rest waits until you plan, when Loomplane finds out whether the kind has a dependency called `postgres`, whether `db` is a kind it accepts, and whether the endpoint answers from the target.\n\n## gateways\n\n| Field | Meaning |\n|---|---|\n| `provider`, `region` | Where it runs: `cloud-run` or `ecs-fargate` |\n| `routes` | Required. 1 to 50 routes |\n| `environments` | `provider`, `region` or `enabled` by environment name |\n\nA route is `{path, to, strip_prefix}`. `path` is a prefix such as `/api` that matches `/api` and anything under `/api/`. `to` is the service name. `strip_prefix` removes the prefix first, so `/api/users` arrives as `/users`. The longest matching path wins.\n\n## links\n\n| Field | Meaning |\n|---|---|\n| `between` | Required. The two clouds it joins: `gcp` and `aws` |\n| `region` | Where the Google Cloud side runs. Put it where the Cloud Run services that use it run |\n| `environments` | `region` or `enabled` by environment name |\n\nA link needs more than a connection check asks for. The Google Cloud key needs Compute Network Admin (`roles/compute.networkAdmin`). The AWS key needs `ec2:CreateVpnGateway`, `ec2:AttachVpnGateway`, `ec2:DetachVpnGateway`, `ec2:DeleteVpnGateway`, `ec2:DescribeVpnGateways`, `ec2:CreateCustomerGateway`, `ec2:DeleteCustomerGateway`, `ec2:CreateVpnConnection`, `ec2:DeleteVpnConnection`, `ec2:DescribeVpnConnections`, `ec2:DescribeRouteTables`, `ec2:EnableVgwRoutePropagation` and `ec2:CreateTags`. See [Gateways and networking](/docs/concepts/gateways-and-networking#links) for what a link builds and bills.\n\n## environments\n\n`environments..release` says how that environment's releases go live. An environment without a release block deploys the way it always has. The block is for version 1 manifests: a version 2 manifest that carries one is refused until federation and releases work together.\n\n| Field | Type | Meaning |\n|---|---|---|\n| `strategy` | `direct`, `blue_green` or `canary` | Required. `canary` moves traffic to the new version in steps |\n| `steps` | list of 1 to 10 integers | Canary only. Traffic percentages, strictly increasing, each 1 to 100, ending at 100. Default `[5, 25, 50, 100]` |\n| `hold` | duration | Canary only. How long to watch each step, in whole minutes from `1m` to `24h`, such as `10m` or `1h30m`. Default `10m` |\n| `thresholds.error_rate` | percentage | Highest share of failed requests a step may show. Above 0% and at most 100%. Default `1%` |\n| `thresholds.error_rate_delta` | percentage | How far above the current version's failure share a step may be. Above 0% and at most 100%. Default `0.5%` |\n| `thresholds.p95_latency_ratio` | number | How many times the current version's p95 latency a step may reach, from 1 to 10. Default `1.3` |\n| `min_requests` | integer | The fewest requests a step needs before its health counts, 1 to 1,000,000. Default `200` |\n| `watch` | duration | How long Loomplane watches a release's health after it deploys, in whole minutes up to `24h`, such as `15m` or `1h`. `0` turns it off. Default `15m` for `canary` and `blue_green`, and no watch for `direct`. A breach rolls the release back automatically |\n\nPercentages are written with a percent sign, such as `1%` or `0.5%`. Thresholds and `min_requests` are allowed with every strategy, because a canary and the post-deploy watch both read them, and a promotion's staging soak reads the error ceiling and `min_requests`. `steps` and `hold` are refused with any strategy but `canary`. Environment names follow the same rule as other names.\n\n```yaml\nenvironments:\n production:\n release:\n strategy: canary\n steps: [5, 25, 50, 100]\n hold: 10m\n thresholds:\n error_rate: 1%\n error_rate_delta: 0.5%\n p95_latency_ratio: 1.3\n min_requests: 200\n```\n\nSee [Canary releases](/docs/concepts/canary-releases) for what a canary does with these settings, and [Promotion and rollback](/docs/concepts/promotion-and-rollback#watch-a-release-after-it-deploys) for the watch.\n\n## ignore\n\n`ignore.resources` lists resource kinds analysis found that the application doesn't use, so plans stop asking about them.\n\n## held\n\n`held.same_address` decides what a scoped plan does when a held service uses a service that was deleted outside Loomplane and that the plan creates again. The held service isn't redeployed, so it keeps the old address.\n\nWith `block` (the default) that's a problem until you add the held repository to the scope. With `warn` it's a warning, but only when the planner can tell the address won't change: a Cloud Run service created again with the name, region and connection it had, which gets the same URL. Anything else, including a replacement, is still a problem.\n\n```yaml\nheld:\n same_address: warn\n```\n\n## Variables Loomplane adds\n\n| Needs | Variable |\n|---|---|\n| Postgres, MySQL, MariaDB | `DATABASE_URL` |\n| Redis, Valkey | `REDIS_URL` |\n| Memcached | `MEMCACHED_SERVERS` |\n| MongoDB | `MONGODB_URI` |\n| AMQP brokers | `AMQP_URL` |\n| Kafka | `KAFKA_BROKERS` |\n| NATS | `NATS_URL` |\n| Object storage | `STORAGE_URL` |\n| Search | `SEARCH_URL` |\n| ClickHouse | `CLICKHOUSE_URL` |\n| Another service | Its name in capitals plus `_URL` (`API_URL`) |\n\n## Provider names\n\n`vercel`, `cloud-run`, `cloud-sql`, `memorystore`, `cloud-storage`, `ecs-fargate`, `rds`, `elasticache`, `s3`, `cross-cloud-vpn`, `render`, `digitalocean`, `azure-container-apps`, `azure-database`, `azure-managed-redis`, `server`, `kubernetes`, plus any [provider plugin](/docs/extending/provider-plugins). The [Clouds overview](/docs/clouds) says what each runs and provisions.\n\n## Federation (version 2)\n\n Federation is still being built. Version 2 records federation proposals, and its plans stay blocked until destination agents, network drivers and policy enforcement pass qualification. Don't use it to try to get private traffic between clouds.\n\nTo convert a file, review its destinations and public exposure, change `version` explicitly, add the `federation` section and review the resulting blocked plan. Keep the original for rollback. The editor never upgrades it for you.\n\n| Map | Contents |\n|---|---|\n| `destinations` | Name to `{id: dest_..., environments: {env: dest_...}}`. IDs must resolve in the organization, project and environment |\n| `network_links` | `{from, to, transport}` where `transport` is `imported` or `ipsec` |\n| `service_exports` | `{service, destination, exposure: private, port, protocol, identity}`. `protocol` is `http`, `grpc` or `tcp`, and `identity` is `workload` or `gateway` |\n| `access_grants` | `{source_service, source_destination, export, methods, paths, grpc_methods, expires_at}` |\n| `placements` | `{service, destination}` |\n\nEach map allows 100 entries. A grant allows 16 HTTP methods, 32 paths of up to 1024 bytes, or 32 gRPC methods of up to 256 bytes (gRPC selectors look like `/package.Service/Method`). `expires_at` is RFC 3339, and an expired grant is rejected at execution even if the manifest still parses. Exports need `public: false` and an explicit service `port` that matches. Every export and source grant needs a matching placement. `needs` still controls configuration and startup order and grants no access.\n\nConnections supply credentials through Vault, so manifests contain no tokens, kubeconfigs or certificate keys. Management is off by default and turned on with `federation.enabled`. See [Configuration](/docs/reference/configuration)." }, { "path": "reference/roles-and-permissions", diff --git a/internal/cloudinfra/cluster_reconcile_test.go b/internal/cloudinfra/cluster_reconcile_test.go index 6c272f2fb..033aa090a 100644 --- a/internal/cloudinfra/cluster_reconcile_test.go +++ b/internal/cloudinfra/cluster_reconcile_test.go @@ -137,10 +137,14 @@ func (clusterClouds) GetProfile(_ context.Context, org, _, id string) (*cloudpro func (clusterClouds) GetProjectGrant(_ context.Context, org, cloud, project string) (*cloudprofiles.ProjectGrant, error) { return &cloudprofiles.ProjectGrant{OrgID: org, CloudID: cloud, ProjectID: project, Revision: 1}, nil } -func (clusterClouds) SetProjectGrant(context.Context, string, string, string, []string, bool) (int64, error) { - return 0, ErrInvalid +func (clusterClouds) SetProjectGrant(context.Context, string, string, string, []string, bool) (*cloudprofiles.ProjectGrant, error) { + return nil, ErrInvalid } +// The code under test finds grants by asserting GrantStore at run time, so a +// signature drift here would surface as a permission error, not a build one. +var _ cloudprofiles.GrantStore = clusterClouds{} + type clusterProvider struct { observations int observeErr error diff --git a/internal/cloudprofiles/change.go b/internal/cloudprofiles/change.go index fca48414c..da7f096f3 100644 --- a/internal/cloudprofiles/change.go +++ b/internal/cloudprofiles/change.go @@ -11,22 +11,25 @@ import ( // ErrBusy identifies an environment or target with unfinished release work. var ErrBusy = errors.New("environment has unfinished deployment or Cloud sync work") -// ChangeInput selects a target placement, a Cloud's default placement or an -// environment assignment. Revision is the target revision, the Cloud revision -// for a default switch, or the assignment generation (zero initially). A -// default switch with no provider clears the default. +// ChangeInput selects exactly one change: a target's placement (TargetID), a +// Cloud's default placement (Default), or the project's default Cloud +// (ProjectDefault). Revision is the target revision, the Cloud revision for a +// default placement switch, or the current default Cloud's grant revision for +// a project default change (zero when the project has none). A default +// placement switch with no provider clears it; a project default change with +// no CloudID leaves the project without a default Cloud. type ChangeInput struct { - Runtime string `json:"runtime,omitempty"` - PoolID string `json:"pool_id,omitempty"` - Default bool `json:"default,omitempty"` - - Revision int64 `json:"revision"` - CloudID string `json:"cloud_id"` - TargetID string `json:"target_id,omitempty"` - EnvironmentID string `json:"environment_id,omitempty"` - Provider string `json:"provider,omitempty"` - ConnectionID string `json:"connection_id,omitempty"` - Region string `json:"region,omitempty"` + Runtime string `json:"runtime,omitempty"` + PoolID string `json:"pool_id,omitempty"` + Default bool `json:"default,omitempty"` + ProjectDefault bool `json:"project_default,omitempty"` + + Revision int64 `json:"revision"` + CloudID string `json:"cloud_id"` + TargetID string `json:"target_id,omitempty"` + Provider string `json:"provider,omitempty"` + ConnectionID string `json:"connection_id,omitempty"` + Region string `json:"region,omitempty"` } // EnvironmentChange describes the reviewed work in one environment. @@ -75,21 +78,23 @@ type PlanSummary struct { // Preview is immutable. Snapshot references and actor identity remain server-side. type Preview struct { - ID string `json:"id" forge:"id"` - OrgID string `json:"org_id"` - ProjectID string `json:"project_id"` - Revision string `json:"revision"` - Input ChangeInput `json:"input"` - Before *Target `json:"before,omitempty"` - After *Target `json:"after,omitempty"` - BeforeDefault *DefaultPlacement `json:"before_default,omitempty"` - AfterDefault *DefaultPlacement `json:"after_default,omitempty"` - BeforeAssignment *Assignment `json:"before_assignment,omitempty"` - AfterAssignment *Assignment `json:"after_assignment,omitempty"` - Environments []EnvironmentChange `json:"environments"` - Blockers []string `json:"blockers"` - Reverts string `json:"reverts,omitempty"` - CreatedAt time.Time `json:"created_at"` + ID string `json:"id" forge:"id"` + OrgID string `json:"org_id"` + ProjectID string `json:"project_id"` + Revision string `json:"revision"` + Input ChangeInput `json:"input"` + Before *Target `json:"before,omitempty"` + After *Target `json:"after,omitempty"` + BeforeDefault *DefaultPlacement `json:"before_default,omitempty"` + AfterDefault *DefaultPlacement `json:"after_default,omitempty"` + // BeforeCloud and AfterCloud are the project's default Cloud either side + // of a project default change. + BeforeCloud *ProjectCloud `json:"before_cloud,omitempty"` + AfterCloud *ProjectCloud `json:"after_cloud,omitempty"` + Environments []EnvironmentChange `json:"environments"` + Blockers []string `json:"blockers"` + Reverts string `json:"reverts,omitempty"` + CreatedAt time.Time `json:"created_at"` } // Sync statuses retain guards until cleanup or compensation finishes. @@ -158,15 +163,17 @@ type EnvironmentSnapshot struct { Routes json.RawMessage `json:"routes,omitempty"` AcceptedPlan *AcceptedPlan `json:"accepted_plan,omitempty"` - ProjectID string `json:"project_id,omitempty"` - EnvironmentID string `json:"environment_id"` - AssignmentRevision int64 `json:"assignment_revision"` - Bindings json.RawMessage `json:"bindings"` - Plan json.RawMessage `json:"plan"` + ProjectID string `json:"project_id,omitempty"` + EnvironmentID string `json:"environment_id"` + // DefaultCloud is the project's default Cloud as reviewed, "" for none. + // Acceptance refuses the review once it has changed. + DefaultCloud string `json:"default_cloud"` + Bindings json.RawMessage `json:"bindings"` + Plan json.RawMessage `json:"plan"` } // Shared reports whether a change reaches every environment using the Cloud, -// rather than one environment's assignment. +// in every project, rather than one project's default Cloud. func (in ChangeInput) Shared() bool { return in.TargetID != "" || in.Default } // ParticipantProject preserves the original scope of legacy operation snapshots. diff --git a/internal/cloudprofiles/events.go b/internal/cloudprofiles/events.go index d06813299..0b4c554f7 100644 --- a/internal/cloudprofiles/events.go +++ b/internal/cloudprofiles/events.go @@ -17,11 +17,10 @@ type CloudSyncEvent struct { UpdatedAt time.Time `json:"updated_at"` } -// EnvironmentCloudEvent invalidates the environment's nullable assignment. -type EnvironmentCloudEvent struct { - OrgID string `json:"org_id"` - ProjectID string `json:"project_id"` - EnvironmentID string `json:"environment_id"` - CloudID *string `json:"cloud_id" nullable:"true" required:"true"` - Revision int64 `json:"revision"` +// ProjectCloudEvent says a project's default Cloud changed. CloudID is the +// new default, or null when the project has none. +type ProjectCloudEvent struct { + OrgID string `json:"org_id"` + ProjectID string `json:"project_id"` + CloudID *string `json:"cloud_id" nullable:"true" required:"true"` } diff --git a/internal/cloudprofiles/grants.go b/internal/cloudprofiles/grants.go index 1263eb817..3ea13c5b7 100644 --- a/internal/cloudprofiles/grants.go +++ b/internal/cloudprofiles/grants.go @@ -16,6 +16,8 @@ import ( // ProjectGrant allows new placements on listed targets. An empty list allows all // targets in this Cloud. Revocation retains the row and advances its revision. +// Default marks the project's default Cloud; at most one live grant per +// project carries it, and changing it is a reviewed Cloud change. type ProjectGrant struct { OrgID string `json:"org_id"` CloudID string `json:"cloud_id"` @@ -23,11 +25,13 @@ type ProjectGrant struct { TargetIDs []string `json:"target_ids"` Revision int64 `json:"revision"` Revoked bool `json:"revoked"` + Default bool `json:"default"` } -// GrantStore persists authorization independently of environment assignments. +// GrantStore persists which projects may use a Cloud. Environments play no +// part: every environment of a granted project may use it. type GrantStore interface { - SetProjectGrant(context.Context, string, string, string, []string, bool) (int64, error) + SetProjectGrant(ctx context.Context, orgID, cloudID, projectID string, targetIDs []string, revoked bool) (*ProjectGrant, error) GetProjectGrant(context.Context, string, string, string) (*ProjectGrant, error) } @@ -79,12 +83,12 @@ func (s *Service) setGrant(ctx context.Context, p security.Principal, cloudID, p targets := append([]string{}, targetIDs...) slices.Sort(targets) targets = slices.Compact(targets) - revision, err := st.SetProjectGrant(ctx, p.OrgID, cloudID, projectID, targets, revoked) + grant, err := st.SetProjectGrant(ctx, p.OrgID, cloudID, projectID, targets, revoked) if err != nil { return nil, err } - s.record(ctx, p, projectID, "cloud.grant", map[string]any{"cloud_id": cloudID, "revision": revision, "revoked": revoked}) - return &ProjectGrant{OrgID: p.OrgID, CloudID: cloudID, ProjectID: projectID, TargetIDs: targets, Revision: revision, Revoked: revoked}, nil + s.record(ctx, p, projectID, "cloud.grant", map[string]any{"cloud_id": cloudID, "revision": grant.Revision, "revoked": revoked, "default": grant.Default}) + return grant, nil } // LockOrganization orders Cloud acceptance, metadata changes and grant updates. @@ -123,39 +127,49 @@ func LockWaitError(err error, lock string) error { func (s *PgStore) GetProjectGrant(ctx context.Context, org, cloud, project string) (*ProjectGrant, error) { g := &ProjectGrant{OrgID: org, CloudID: cloud, ProjectID: project} - err := s.db.QueryRow(ctx, `SELECT target_ids,revision,revoked FROM loomplane_cloud_project_grants WHERE org_id=$1 AND cloud_id=$2 AND project_id=$3`, org, cloud, project).Scan(&g.TargetIDs, &g.Revision, &g.Revoked) + err := s.db.QueryRow(ctx, `SELECT target_ids,revision,revoked,is_default FROM loomplane_cloud_project_grants WHERE org_id=$1 AND cloud_id=$2 AND project_id=$3`, org, cloud, project).Scan(&g.TargetIDs, &g.Revision, &g.Revoked, &g.Default) return g, storeError(err) } -func (s *PgStore) SetProjectGrant(ctx context.Context, org, cloud, project string, targets []string, revoked bool) (int64, error) { +func (s *PgStore) SetProjectGrant(ctx context.Context, org, cloud, project string, targets []string, revoked bool) (*ProjectGrant, error) { tx, err := s.db.BeginTx(ctx, nil) if err != nil { - return 0, err + return nil, err } defer rollbackSync(tx) if lockErr := LockOrganization(ctx, tx, org); lockErr != nil { - return 0, lockErr + return nil, lockErr } for _, id := range targets { var found string if err = tx.QueryRow(ctx, `SELECT id FROM loomplane_cloud_targets WHERE org_id=$1 AND cloud_id=$2 AND id=$3`, org, cloud, id).Scan(&found); err != nil { - return 0, storeError(err) + return nil, storeError(err) } } if targets == nil { targets = []string{} } - var revision int64 - err = tx.QueryRow(ctx, `INSERT INTO loomplane_cloud_project_grants(org_id,cloud_id,project_id,target_ids,revoked) VALUES($1,$2,$3,$4,$5) - ON CONFLICT(org_id,cloud_id,project_id) DO UPDATE SET target_ids=EXCLUDED.target_ids,revoked=EXCLUDED.revoked,revision=loomplane_cloud_project_grants.revision+1,updated_at=now() RETURNING revision`, org, cloud, project, targets, revoked).Scan(&revision) + // A project's first live grant becomes its default Cloud: nothing runs + // there yet, so there is nothing to review. Not while a shared change on + // the Cloud is unfinished, though: that change reaches only the + // environments it reviewed, so the project waits and makes it its default + // once the change settles. Revoking a grant ends its default; the + // project's services keep running where they are. + g := &ProjectGrant{OrgID: org, CloudID: cloud, ProjectID: project, TargetIDs: targets, Revoked: revoked} + err = tx.QueryRow(ctx, `INSERT INTO loomplane_cloud_project_grants(org_id,cloud_id,project_id,target_ids,revoked,is_default) + VALUES($1,$2,$3,$4,$5,NOT $5 AND NOT EXISTS(SELECT 1 FROM loomplane_cloud_project_grants WHERE org_id=$1 AND project_id=$3 AND is_default AND NOT revoked) + AND NOT EXISTS(SELECT 1 FROM loomplane_cloud_syncs WHERE org_id=$1 AND cloud_id=$2 AND (target_id<>'' OR body->>'default'='true') AND status NOT IN ('succeeded','reverted'))) + ON CONFLICT(org_id,cloud_id,project_id) DO UPDATE SET target_ids=EXCLUDED.target_ids,revoked=EXCLUDED.revoked,is_default=loomplane_cloud_project_grants.is_default AND NOT EXCLUDED.revoked,revision=loomplane_cloud_project_grants.revision+1,updated_at=now() RETURNING revision,is_default`, org, cloud, project, targets, revoked).Scan(&g.Revision, &g.Default) if err != nil { - return 0, storeError(err) + return nil, storeError(err) } - return revision, tx.Commit() + return g, tx.Commit() } -// AssignedEnvironments includes every project affected by an organization change. -func (s *PgStore) AssignedEnvironments(ctx context.Context, org, cloud string) ([]*projects.Environment, error) { - rows, err := s.db.Query(ctx, `SELECT e.id,e.project_id,e.name FROM loomplane_environments e JOIN loomplane_cloud_assignments a ON a.org_id=e.org_id AND a.project_id=e.project_id AND a.environment_id=e.id WHERE a.org_id=$1 AND a.cloud_id=$2 ORDER BY e.project_id,e.id`, org, cloud) +// EnvironmentsUsing lists every environment, in every project, a shared +// change to cloud reaches: each environment of a project whose default +// Cloud it is, and each environment running a service it placed. +func (s *PgStore) EnvironmentsUsing(ctx context.Context, org, cloud string) ([]*projects.Environment, error) { + rows, err := s.db.Query(ctx, environmentsUsingSQL, org, cloud) if err != nil { return nil, storeError(err) } @@ -171,6 +185,14 @@ func (s *PgStore) AssignedEnvironments(ctx context.Context, org, cloud string) ( return out, rows.Err() } +// environmentsUsingSQL is shared with acceptance, which compares the +// reviewed environments against it inside the accepting transaction. +const environmentsUsingSQL = `SELECT e.id,e.project_id,e.name FROM loomplane_environments e + WHERE e.org_id=$1 AND ( + EXISTS(SELECT 1 FROM loomplane_cloud_project_grants g WHERE g.org_id=e.org_id AND g.project_id=e.project_id AND g.cloud_id=$2 AND g.is_default AND NOT g.revoked) + OR EXISTS(SELECT 1 FROM loomplane_bindings b WHERE b.org_id=e.org_id AND b.environment_id=e.id AND b.subject='service' AND b.config->'cloud_placement'->>'cloud_id'=$2)) + ORDER BY e.project_id,e.id` + // SyncForParticipant is an internal execution lookup, not a project API view. func (s *PgStore) SyncForParticipant(ctx context.Context, org, project, env, id string) (*Sync, *Snapshot, error) { sync, snapshot, err := readSync(s.db.QueryRow(ctx, `SELECT body,snapshot,version FROM loomplane_cloud_syncs WHERE org_id=$1 AND id=$2`, org, id)) @@ -213,7 +235,7 @@ func (s *Service) ListProjectGrants(ctx context.Context, p security.Principal, c return st.ListProjectGrants(ctx, p.OrgID, cloud) } func (s *PgStore) ListProjectGrants(ctx context.Context, org, cloud string) ([]*ProjectGrant, error) { - rows, err := s.db.Query(ctx, `SELECT project_id,target_ids,revision,revoked FROM loomplane_cloud_project_grants WHERE org_id=$1 AND cloud_id=$2 ORDER BY project_id`, org, cloud) + rows, err := s.db.Query(ctx, `SELECT project_id,target_ids,revision,revoked,is_default FROM loomplane_cloud_project_grants WHERE org_id=$1 AND cloud_id=$2 ORDER BY project_id`, org, cloud) if err != nil { return nil, storeError(err) } @@ -221,7 +243,7 @@ func (s *PgStore) ListProjectGrants(ctx context.Context, org, cloud string) ([]* out := []*ProjectGrant{} for rows.Next() { g := &ProjectGrant{OrgID: org, CloudID: cloud} - if scanErr := rows.Scan(&g.ProjectID, &g.TargetIDs, &g.Revision, &g.Revoked); scanErr != nil { + if scanErr := rows.Scan(&g.ProjectID, &g.TargetIDs, &g.Revision, &g.Revoked, &g.Default); scanErr != nil { return nil, scanErr } out = append(out, g) diff --git a/internal/cloudprofiles/model.go b/internal/cloudprofiles/model.go index 2f5b9d15f..94295d4c2 100644 --- a/internal/cloudprofiles/model.go +++ b/internal/cloudprofiles/model.go @@ -13,7 +13,7 @@ var ( ErrInvalid = errors.New("invalid cloud configuration") ErrExists = errors.New("a cloud or target with that name already exists") ErrConflict = errors.New("cloud configuration changed; reload and try again") - ErrInUse = errors.New("this cloud or target is assigned to an environment") + ErrInUse = errors.New("this Cloud or target is in use by a project or a running service") // ErrPlatformOwned refuses any change to the Loomplane Cloud an instance // projects into a workspace. Only the platform control plane writes it. ErrPlatformOwned = errors.New("Loomplane Cloud is run by this instance and can't be changed here.") //nolint:revive,staticcheck // the message is shown as written @@ -74,23 +74,40 @@ type Target struct { UpdatedAt time.Time `json:"updated_at"` } -// Assignment resolves an environment's desired Cloud and all of its targets. -type Assignment struct { - GrantRevision int64 `json:"grant_revision"` - CloudRevision int64 `json:"cloud_revision"` - OrgID string `json:"org_id"` - ProjectID string `json:"project_id"` - EnvironmentID string `json:"environment_id"` - CloudID string `json:"cloud_id"` - Revision int64 `json:"revision"` - Targets []Target `json:"targets"` +// ProjectCloud is one Cloud as one project may use it: the targets the +// project's grant allows and, when the grant covers the whole Cloud, the +// Cloud's default placement. Every environment of the project sees the same +// view; environments differ only in what their manifest asks for. +type ProjectCloud struct { + GrantRevision int64 `json:"grant_revision"` + CloudRevision int64 `json:"cloud_revision"` + OrgID string `json:"org_id"` + ProjectID string `json:"project_id"` + CloudID string `json:"cloud_id"` + // Name is the Cloud's name, what a manifest's cloud field says. + Name string `json:"name"` + // Default marks the project's default Cloud, the one a manifest reaches + // without naming a Cloud. + Default bool `json:"default"` + Targets []Target `json:"targets"` // DefaultPlacement is the Cloud's default when the project's grant covers // the whole Cloud. A grant limited to chosen targets never reaches it. DefaultPlacement *DefaultPlacement `json:"default_placement,omitempty"` } -// Resolver reads placement without changing it. A valid unassigned environment -// returns nil; an environment outside the requested scope returns ErrNotFound. +// Resolver reads placement without changing it. type Resolver interface { - Resolve(ctx context.Context, orgID, projectID, environmentID string) (*Assignment, error) + // ResolveCloud reads the project's view of cloud, or of the project's + // default Cloud when cloud is "". A project with no default Cloud + // returns nil for "". A Cloud the project holds no live grant on, or a + // project outside the organization, returns ErrNotFound. + ResolveCloud(ctx context.Context, orgID, projectID, cloudID string) (*ProjectCloud, error) +} + +// NamedResolver reads a Cloud the project names in its manifest. +type NamedResolver interface { + // ResolveNamedCloud reads the project's view of the organization's + // Cloud called name. A name no Cloud has, or a Cloud the project holds + // no live grant on, returns ErrNotFound. + ResolveNamedCloud(ctx context.Context, orgID, projectID, name string) (*ProjectCloud, error) } diff --git a/internal/cloudprofiles/pgstore.go b/internal/cloudprofiles/pgstore.go index 4cc0dda95..ab516179b 100644 --- a/internal/cloudprofiles/pgstore.go +++ b/internal/cloudprofiles/pgstore.go @@ -10,6 +10,8 @@ import ( "github.com/jackc/pgx/v5/pgconn" "github.com/xraph/grove/driver" "github.com/xraph/grove/drivers/pgdriver" + + "github.com/xraph/loomplane/internal/projects" ) // PgStore persists scoped Cloud configuration in Postgres. @@ -153,17 +155,18 @@ func (s *PgStore) UpdateProfile(ctx context.Context, p *Profile, previousRevisio } defer rollbackSync(tx) provider, connection, region := defaultColumns(p.DefaultPlacement) - // The organization lock is held, so no assignment can begin while this - // runs. Setting a first default is safe: services it places had none. + // The organization lock is held, so no default Cloud can change while + // this runs. Setting a first default is safe: services it places had none. var redirects bool err = tx.QueryRow(ctx, `SELECT default_provider IS NOT NULL AND (default_provider IS DISTINCT FROM $3 OR default_connection_id IS DISTINCT FROM $4 OR default_region<>$5) - AND EXISTS(SELECT 1 FROM loomplane_cloud_assignments a WHERE a.org_id=c.org_id AND a.cloud_id=c.id) + AND (EXISTS(SELECT 1 FROM loomplane_cloud_project_grants g WHERE g.org_id=c.org_id AND g.cloud_id=c.id AND g.is_default AND NOT g.revoked) + OR EXISTS(SELECT 1 FROM loomplane_bindings b WHERE b.org_id=c.org_id AND b.subject='service' AND b.config->'cloud_placement'->>'cloud_id'=c.id AND (b.config->'cloud_placement'->>'default')::boolean)) FROM loomplane_cloud_profiles c WHERE org_id=$1 AND id=$2`, p.OrgID, p.ID, provider, connection, region).Scan(&redirects) if err != nil { return storeError(err) } if redirects { - return fmt.Errorf("%w: this Cloud is in use; review the default change as a Cloud change with default set, which moves its services, or unassign it first", ErrInUse) + return fmt.Errorf("%w: this Cloud is in use; review the default placement change as a Cloud change with default set, which moves its services", ErrInUse) } tag, err := tx.Exec(ctx, `UPDATE loomplane_cloud_profiles SET name=$4,revision=$5,updated_at=$6,default_provider=$8,default_connection_id=$9,default_region=$10 WHERE org_id=$1 AND ($2='' OR project_id=$2) AND id=$3 AND revision=$7`, p.OrgID, p.ProjectID, p.ID, p.Name, p.Revision, p.UpdatedAt, previousRevision, provider, connection, region) if err != nil { @@ -273,74 +276,94 @@ func (s *PgStore) DeleteTarget(ctx context.Context, orgID, projectID, cloudID, i return nil } -// Resolve reads the environment, assignment and targets in a single snapshot. -// No assignment returns nil only when the environment exists in this scope. -func (s *PgStore) Resolve(ctx context.Context, orgID, projectID, environmentID string) (*Assignment, error) { - assignment, _, err := s.EnvironmentCloud(ctx, orgID, projectID, environmentID) - return assignment, err +// ResolveCloud reads the project's view of one Cloud, or of its default +// Cloud when cloud is "", in a single snapshot. +func (s *PgStore) ResolveCloud(ctx context.Context, orgID, projectID, cloudID string) (*ProjectCloud, error) { + return s.projectCloud(ctx, orgID, projectID, cloudID, false) +} + +// RetainedCloud reads a Cloud the project placed services on, for reviewed +// removal and compensation. It answers after the grant is revoked, with +// every target, since cleanup must reach what the grant once allowed. +func (s *PgStore) RetainedCloud(ctx context.Context, orgID, projectID, cloudID string) (*ProjectCloud, error) { + return s.projectCloud(ctx, orgID, projectID, cloudID, true) } -// EnvironmentCloud reads the nullable assignment and its generation atomically. -func (s *PgStore) EnvironmentCloud(ctx context.Context, orgID, projectID, environmentID string) (*Assignment, int64, error) { - return s.environmentCloud(ctx, orgID, projectID, environmentID, false) +// DefaultCloud reads the project's default Cloud and its grant revision: +// "" and 0 when the project has none. +func (s *PgStore) DefaultCloud(ctx context.Context, orgID, projectID string) (cloudID string, grantRevision int64, err error) { + var cloud *string + var revision *int64 + err = s.db.QueryRow(ctx, `SELECT g.cloud_id,g.revision FROM loomplane_projects p + LEFT JOIN loomplane_cloud_project_grants g ON g.org_id=p.org_id AND g.project_id=p.id AND g.is_default AND NOT g.revoked + WHERE p.org_id=$1 AND p.id=$2`, orgID, projectID).Scan(&cloud, &revision) + if err != nil { + return "", 0, storeError(err) + } + if cloud == nil { + return "", 0, nil + } + return *cloud, *revision, nil } -// RetainedAssignment reads an existing placement for reviewed removal or reassignment. -func (s *PgStore) RetainedAssignment(ctx context.Context, org, project, env string) (*Assignment, error) { - a, _, err := s.environmentCloud(ctx, org, project, env, true) - return a, err +// ResolveNamedCloud reads the project's view of the Cloud called name. +func (s *PgStore) ResolveNamedCloud(ctx context.Context, orgID, projectID, name string) (*ProjectCloud, error) { + var id string + if err := s.db.QueryRow(ctx, `SELECT id FROM loomplane_cloud_profiles WHERE org_id=$1 AND name=$2`, orgID, name).Scan(&id); err != nil { + return nil, storeError(err) + } + return s.projectCloud(ctx, orgID, projectID, id, false) } -func (s *PgStore) environmentCloud(ctx context.Context, orgID, projectID, environmentID string, retained bool) (*Assignment, int64, error) { - var cloudID *string - var revision, cloudRevision, grantRevision *int64 + +func (s *PgStore) projectCloud(ctx context.Context, orgID, projectID, cloudID string, retained bool) (*ProjectCloud, error) { + var id, name *string + var cloudRevision, grantRevision *int64 + var isDefault bool var targets []byte - var defaultProvider, defaultConnection *string - var defaultRegion *string + var defaultProvider, defaultConnection, defaultRegion *string var wholeCloud *bool - err := s.db.QueryRow(ctx, `SELECT a.cloud_id,a.revision,c.revision,g.revision,c.default_provider,c.default_connection_id,c.default_region,cardinality(g.target_ids)=0,coalesce(jsonb_agg(to_jsonb(t) ORDER BY t.name,t.id) FILTER(WHERE t.id IS NOT NULL),'[]'::jsonb) - FROM loomplane_environments e - JOIN loomplane_projects p ON p.org_id=e.org_id AND p.id=e.project_id - LEFT JOIN loomplane_cloud_assignments a ON a.org_id=e.org_id AND a.project_id=e.project_id AND a.environment_id=e.id - LEFT JOIN loomplane_cloud_profiles c ON c.org_id=a.org_id AND c.id=a.cloud_id - LEFT JOIN loomplane_cloud_project_grants g ON g.org_id=a.org_id AND g.cloud_id=a.cloud_id AND g.project_id=a.project_id AND NOT g.revoked - LEFT JOIN loomplane_cloud_targets t ON t.org_id=a.org_id AND t.cloud_id=a.cloud_id AND ($4 OR (g.revision IS NOT NULL AND (cardinality(g.target_ids)=0 OR t.id=ANY(g.target_ids)))) - AND ($4 OR t.managed_resource_id IS NULL OR (t.project_id=e.project_id AND EXISTS(SELECT 1 FROM loomplane_runtime_attachments ra JOIN loomplane_managed_resources mr ON mr.org_id=ra.org_id AND mr.id=ra.cluster_id WHERE ra.org_id=t.org_id AND ra.cloud_id=t.cloud_id AND ra.cluster_id=t.managed_resource_id AND ra.project_id=e.project_id AND ra.runtime_connection_id=t.connection_id AND ra.deleted_at IS NULL AND mr.deleted_at IS NULL))) - WHERE e.org_id=$1 AND e.project_id=$2 AND e.id=$3 - GROUP BY e.id,a.cloud_id,a.revision,c.revision,g.revision,c.default_provider,c.default_connection_id,c.default_region,g.target_ids`, orgID, projectID, environmentID, retained).Scan(&cloudID, &revision, &cloudRevision, &grantRevision, &defaultProvider, &defaultConnection, &defaultRegion, &wholeCloud, &targets) + err := s.db.QueryRow(ctx, `SELECT c.id,c.name,c.revision,g.revision,coalesce(g.is_default,false),c.default_provider,c.default_connection_id,c.default_region,cardinality(g.target_ids)=0,coalesce(jsonb_agg(to_jsonb(t) ORDER BY t.name,t.id) FILTER(WHERE t.id IS NOT NULL),'[]'::jsonb) + FROM loomplane_projects p + LEFT JOIN loomplane_cloud_profiles c ON c.org_id=p.org_id AND c.id=CASE WHEN $3='' THEN (SELECT d.cloud_id FROM loomplane_cloud_project_grants d WHERE d.org_id=p.org_id AND d.project_id=p.id AND d.is_default AND NOT d.revoked) ELSE $3 END + LEFT JOIN loomplane_cloud_project_grants g ON g.org_id=c.org_id AND g.cloud_id=c.id AND g.project_id=p.id AND NOT g.revoked + LEFT JOIN loomplane_cloud_targets t ON t.org_id=c.org_id AND t.cloud_id=c.id AND ($4 OR (g.revision IS NOT NULL AND (cardinality(g.target_ids)=0 OR t.id=ANY(g.target_ids)))) + AND ($4 OR t.managed_resource_id IS NULL OR (t.project_id=p.id AND EXISTS(SELECT 1 FROM loomplane_runtime_attachments ra JOIN loomplane_managed_resources mr ON mr.org_id=ra.org_id AND mr.id=ra.cluster_id WHERE ra.org_id=t.org_id AND ra.cloud_id=t.cloud_id AND ra.cluster_id=t.managed_resource_id AND ra.project_id=p.id AND ra.runtime_connection_id=t.connection_id AND ra.deleted_at IS NULL AND mr.deleted_at IS NULL))) + WHERE p.org_id=$1 AND p.id=$2 + GROUP BY c.id,c.name,c.revision,g.revision,g.is_default,c.default_provider,c.default_connection_id,c.default_region,g.target_ids`, orgID, projectID, cloudID, retained).Scan(&id, &name, &cloudRevision, &grantRevision, &isDefault, &defaultProvider, &defaultConnection, &defaultRegion, &wholeCloud, &targets) if err != nil { - return nil, 0, storeError(err) + return nil, storeError(err) } - if cloudID == nil { - if revision != nil { - return nil, *revision, nil + if id == nil { + if cloudID == "" { + return nil, nil } - return nil, 0, nil + return nil, ErrNotFound } if grantRevision == nil { if !retained { - return nil, *revision, ErrNotFound + return nil, ErrNotFound } zero := int64(0) grantRevision = &zero } - a := &Assignment{GrantRevision: *grantRevision, OrgID: orgID, ProjectID: projectID, EnvironmentID: environmentID, CloudID: *cloudID, Revision: *revision, CloudRevision: *cloudRevision} - if err = json.Unmarshal(targets, &a.Targets); err != nil { - return nil, 0, fmt.Errorf("decode assigned targets: %w", err) + c := &ProjectCloud{GrantRevision: *grantRevision, OrgID: orgID, ProjectID: projectID, CloudID: *id, Name: *name, CloudRevision: *cloudRevision, Default: isDefault} + if err = json.Unmarshal(targets, &c.Targets); err != nil { + return nil, fmt.Errorf("decode granted targets: %w", err) } - for i := range a.Targets { - if a.Targets[i].Tags == nil { - a.Targets[i].Tags = []string{} + for i := range c.Targets { + if c.Targets[i].Tags == nil { + c.Targets[i].Tags = []string{} } } // Cleanup keeps the default it placed with; fresh placement needs a grant // covering the whole Cloud, not just chosen targets. if defaultProvider != nil && defaultConnection != nil && (retained || wholeCloud != nil && *wholeCloud) { - a.DefaultPlacement = &DefaultPlacement{Provider: *defaultProvider, ConnectionID: *defaultConnection} + c.DefaultPlacement = &DefaultPlacement{Provider: *defaultProvider, ConnectionID: *defaultConnection} if defaultRegion != nil { - a.DefaultPlacement.Region = *defaultRegion + c.DefaultPlacement.Region = *defaultRegion } } - return a, *revision, nil + return c, nil } // metadataTransaction serializes edits with acceptance. Retained syncs pin both @@ -393,3 +416,18 @@ func IsStaleCleanupReview(err error) bool { var pg *pgconn.PgError return errors.As(err, &pg) && pg.Code == "23514" && (pg.Message == "cleanup target changed; review again" || pg.Message == "cleanup target is unresolved or untrusted") } + +// Planning, deployment and the Cloud infrastructure service reach these +// through run-time assertions, where a drifted signature would read as a +// missing capability rather than fail the build. +var ( + _ GrantStore = (*PgStore)(nil) + _ NamedResolver = (*PgStore)(nil) + _ SyncStore = (*PgStore)(nil) + _ interface { + RetainedCloud(ctx context.Context, orgID, projectID, cloudID string) (*ProjectCloud, error) + } = (*PgStore)(nil) + _ interface { + EnvironmentsUsing(ctx context.Context, orgID, cloudID string) ([]*projects.Environment, error) + } = (*PgStore)(nil) +) diff --git a/internal/cloudprofiles/service.go b/internal/cloudprofiles/service.go index e3c41c267..a2773ee7d 100644 --- a/internal/cloudprofiles/service.go +++ b/internal/cloudprofiles/service.go @@ -501,18 +501,18 @@ func (s *Service) DeleteTarget(ctx context.Context, p security.Principal, projec return nil } -// EnvironmentCloud returns the assignment and generation, including tombstones. -func (s *Service) EnvironmentCloud(ctx context.Context, p security.Principal, projectID, environmentID string) (*Assignment, int64, error) { +// DefaultCloud returns the project's default Cloud as the project sees it, +// or nil when it has none. Its GrantRevision is the token a reviewed change +// of the default compares against. +func (s *Service) DefaultCloud(ctx context.Context, p security.Principal, projectID string) (*ProjectCloud, error) { if err := s.scope(ctx, p, projectID, security.CloudAccountRead); err != nil { - return nil, 0, err + return nil, err } - reader, ok := s.store.(interface { - EnvironmentCloud(context.Context, string, string, string) (*Assignment, int64, error) - }) + resolver, ok := s.store.(Resolver) if !ok { - return nil, 0, fmt.Errorf("%w: assignment storage unavailable", ErrInvalid) + return nil, fmt.Errorf("%w: Cloud resolution unavailable", ErrInvalid) } - return reader.EnvironmentCloud(ctx, p.OrgID, projectID, environmentID) + return resolver.ResolveCloud(ctx, p.OrgID, projectID, "") } // refusePlatformProvider refuses a Loomplane Cloud target or default on a diff --git a/internal/cloudprofiles/service_test.go b/internal/cloudprofiles/service_test.go index d16552b1d..5a5c30802 100644 --- a/internal/cloudprofiles/service_test.go +++ b/internal/cloudprofiles/service_test.go @@ -290,9 +290,9 @@ type grantingStore struct { grants int } -func (g *grantingStore) SetProjectGrant(context.Context, string, string, string, []string, bool) (int64, error) { +func (g *grantingStore) SetProjectGrant(_ context.Context, org, cloud, project string, targets []string, revoked bool) (*ProjectGrant, error) { g.grants++ - return int64(g.grants), nil + return &ProjectGrant{OrgID: org, CloudID: cloud, ProjectID: project, TargetIDs: targets, Revision: int64(g.grants), Revoked: revoked, Default: !revoked && g.grants == 1}, nil } func (g *grantingStore) GetProjectGrant(context.Context, string, string, string) (*ProjectGrant, error) { return nil, ErrNotFound diff --git a/internal/cloudprofiles/sync_store.go b/internal/cloudprofiles/sync_store.go index 55071bc3b..ee424c108 100644 --- a/internal/cloudprofiles/sync_store.go +++ b/internal/cloudprofiles/sync_store.go @@ -21,7 +21,7 @@ type SyncStore interface { Store Resolver SnapshotBindings(context.Context, string, string) (json.RawMessage, error) - AssignmentGeneration(context.Context, string, string, string) (int64, error) + DefaultCloud(ctx context.Context, orgID, projectID string) (string, int64, error) SavePreview(context.Context, *Preview, *Snapshot) error GetPreview(context.Context, string, string, string) (*Preview, *Snapshot, error) Accept(context.Context, *Preview, *Snapshot, *Sync, string) (*Sync, error) @@ -32,13 +32,6 @@ type SyncStore interface { SaveSync(context.Context, *Sync, *Snapshot) error } -// AssignmentGeneration includes unassignment tombstones, preventing ABA replay. -func (s *PgStore) AssignmentGeneration(ctx context.Context, org, project, env string) (int64, error) { - var revision int64 - err := s.db.QueryRow(ctx, `SELECT coalesce(a.revision,0) FROM loomplane_environments e LEFT JOIN loomplane_cloud_assignments a ON a.org_id=e.org_id AND a.project_id=e.project_id AND a.environment_id=e.id WHERE e.org_id=$1 AND e.project_id=$2 AND e.id=$3`, org, project, env).Scan(&revision) - return revision, storeError(err) -} - // SavePreview inserts a review once; updates are deliberately unsupported. func (s *PgStore) SavePreview(ctx context.Context, p *Preview, snapshot *Snapshot) error { body, err := json.Marshal(p) @@ -262,11 +255,12 @@ func (s *PgStore) Accept(ctx context.Context, p *Preview, snapshot *Snapshot, sy if active { return nil, ErrBusy } - var generation int64 - if queryErr := tx.QueryRow(ctx, `SELECT coalesce((SELECT revision FROM loomplane_cloud_assignments WHERE org_id=$1 AND project_id=$2 AND environment_id=$3),0)`, p.OrgID, ParticipantProject(env.ProjectID, p.ProjectID), env.EnvironmentID).Scan(&generation); queryErr != nil { + // The plan moved services relying on the default Cloud as it was. + var defaultCloud string + if queryErr := tx.QueryRow(ctx, `SELECT coalesce((SELECT cloud_id FROM loomplane_cloud_project_grants WHERE org_id=$1 AND project_id=$2 AND is_default AND NOT revoked FOR SHARE),'')`, p.OrgID, ParticipantProject(env.ProjectID, p.ProjectID)).Scan(&defaultCloud); queryErr != nil { return nil, queryErr } - if generation != env.AssignmentRevision { + if defaultCloud != env.DefaultCloud { return nil, ErrConflict } if _, lockErr := tx.Exec(ctx, `SELECT id FROM loomplane_bindings WHERE org_id=$1 AND environment_id=$2 ORDER BY id FOR UPDATE`, p.OrgID, env.EnvironmentID); lockErr != nil { @@ -309,15 +303,16 @@ func (s *PgStore) Accept(ctx context.Context, p *Preview, snapshot *Snapshot, sy } } if p.Input.Shared() { - // Check the full assignment set too, including a newly assigned empty environment. + // The change must reach exactly the environments it reviewed, + // including one that took this Cloud as its default since. var ids []string - rows, qerr := tx.Query(ctx, `SELECT environment_id FROM loomplane_cloud_assignments WHERE org_id=$1 AND $2::text IS NOT NULL AND cloud_id=$3 ORDER BY environment_id`, p.OrgID, p.ProjectID, p.Input.CloudID) + rows, qerr := tx.Query(ctx, environmentsUsingSQL, p.OrgID, p.Input.CloudID) if qerr != nil { return nil, qerr } for rows.Next() { - var id string - if qerr = rows.Scan(&id); qerr != nil { + var id, project, name string + if qerr = rows.Scan(&id, &project, &name); qerr != nil { rows.Close() return nil, qerr } @@ -328,6 +323,7 @@ func (s *PgStore) Accept(ctx context.Context, p *Preview, snapshot *Snapshot, sy if qerr != nil { return nil, qerr } + slices.Sort(ids) reviewed := make([]string, 0, len(envs)) for _, env := range envs { reviewed = append(reviewed, env.EnvironmentID) @@ -336,6 +332,21 @@ func (s *PgStore) Accept(ctx context.Context, p *Preview, snapshot *Snapshot, sy return nil, ErrConflict } } + if p.Input.ProjectDefault { + // A project with no environments has no per-environment pin above. + var current string + var revision int64 + if qerr := tx.QueryRow(ctx, `SELECT coalesce(cloud_id,''),coalesce(revision,0) FROM (SELECT 1) one LEFT JOIN loomplane_cloud_project_grants ON org_id=$1 AND project_id=$2 AND is_default AND NOT revoked`, p.OrgID, p.ProjectID).Scan(¤t, &revision); qerr != nil { + return nil, qerr + } + before := "" + if p.BeforeCloud != nil { + before = p.BeforeCloud.CloudID + } + if current != before || revision != p.Input.Revision { + return nil, ErrConflict + } + } switch { case p.Input.Default: provider, connection, region := defaultColumns(p.AfterDefault) @@ -343,7 +354,14 @@ func (s *PgStore) Accept(ctx context.Context, p *Preview, snapshot *Snapshot, sy case p.Input.TargetID != "": _, err = tx.Exec(ctx, `UPDATE loomplane_cloud_targets SET provider=$5,connection_id=nullif($6,''),region=$7,revision=revision+1,updated_at=$8,runtime=$9,pool_id=nullif($10,''),managed_resource_id=nullif($11,''),location_id=nullif($12,'') WHERE org_id=$1 AND $2::text IS NOT NULL AND cloud_id=$3 AND id=$4`, p.OrgID, p.ProjectID, p.Input.CloudID, p.Input.TargetID, p.After.Provider, p.After.ConnectionID, p.After.Region, sync.CreatedAt, cmp.Or(p.After.Runtime, "managed"), p.After.PoolID, p.After.ManagedResourceID, p.After.LocationID) default: - _, err = tx.Exec(ctx, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES($1,$2,$3,nullif($4,''),1) ON CONFLICT(org_id,project_id,environment_id) DO UPDATE SET cloud_id=EXCLUDED.cloud_id,revision=loomplane_cloud_assignments.revision+1`, p.OrgID, p.ProjectID, p.Input.EnvironmentID, p.Input.CloudID) + err = setDefaultCloud(ctx, tx, p.OrgID, p.ProjectID, p.Input.CloudID) + // Both grants just advanced. The stored snapshot is what the sync's + // runs validate against, so it records them as they now stand. + for i := range snapshot.Grants { + if snapshot.Grants[i].ProjectID == p.ProjectID { + snapshot.Grants[i].Revision++ + } + } } if err != nil { return nil, storeError(err) @@ -587,7 +605,7 @@ func (s *PgStore) ListSyncPage(ctx context.Context, org, project, cloud string, if limit < 1 || limit > page.Max { return nil, page.Cursor{}, page.ErrBadLimit } - rows, err := s.listSyncRows(ctx, `SELECT body,snapshot,version FROM loomplane_cloud_syncs s WHERE org_id=$1 AND `+syncViewScope+` AND ($3='' OR (created_at,id)<($4,$3)) AND ($6='' OR s.cloud_id=$6 OR EXISTS(SELECT 1 FROM loomplane_cloud_previews r WHERE r.org_id=s.org_id AND r.id=s.preview_id AND r.body->'before_assignment'->>'cloud_id'=$6)) ORDER BY created_at DESC,id DESC LIMIT $5`, org, project, before.ID, before.At, limit+1, cloud) + rows, err := s.listSyncRows(ctx, `SELECT body,snapshot,version FROM loomplane_cloud_syncs s WHERE org_id=$1 AND `+syncViewScope+` AND ($3='' OR (created_at,id)<($4,$3)) AND ($6='' OR s.cloud_id=$6 OR EXISTS(SELECT 1 FROM loomplane_cloud_previews r WHERE r.org_id=s.org_id AND r.id=s.preview_id AND r.body->'before_cloud'->>'cloud_id'=$6)) ORDER BY created_at DESC,id DESC LIMIT $5`, org, project, before.ID, before.At, limit+1, cloud) if err != nil { return nil, page.Cursor{}, err } @@ -689,3 +707,31 @@ func checkSyncTarget(target Target, revision int64, before *Target) error { } return nil } + +// setDefaultCloud makes cloud the project's default, or leaves the project +// without one when cloud is "". Both grants it touches advance their +// revision, so every plan resolved against the old default goes stale. +func setDefaultCloud(ctx context.Context, tx driver.Tx, org, project, cloud string) error { + if _, err := tx.Exec(ctx, `UPDATE loomplane_cloud_project_grants SET is_default=false,revision=revision+1,updated_at=now() WHERE org_id=$1 AND project_id=$2 AND is_default AND cloud_id<>$3`, org, project, cloud); err != nil { + return err + } + if cloud == "" { + return nil + } + tag, err := tx.Exec(ctx, `UPDATE loomplane_cloud_project_grants SET is_default=true,revision=revision+1,updated_at=now() WHERE org_id=$1 AND project_id=$2 AND cloud_id=$3 AND NOT revoked AND NOT is_default`, org, project, cloud) + if err != nil { + return err + } + if n, countErr := tag.RowsAffected(); countErr != nil { + return countErr + } else if n == 0 { + var already bool + if checkErr := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM loomplane_cloud_project_grants WHERE org_id=$1 AND project_id=$2 AND cloud_id=$3 AND NOT revoked AND is_default)`, org, project, cloud).Scan(&already); checkErr != nil { + return checkErr + } + if !already { + return ErrNotFound + } + } + return nil +} diff --git a/internal/cloudprofiles/usage.go b/internal/cloudprofiles/usage.go index 395d41a85..176853aac 100644 --- a/internal/cloudprofiles/usage.go +++ b/internal/cloudprofiles/usage.go @@ -7,23 +7,26 @@ import ( "github.com/xraph/loomplane/internal/security" ) -// Usage is what a Cloud carries now: the environments that chose it, and the -// running services it placed, by target or by its default. +// Usage is what a Cloud carries now: the environments of projects whose +// default Cloud it is, and the running services it placed, by target or by +// its default placement. type Usage struct { CloudID string `json:"cloud_id"` Environments []EnvironmentUsage `json:"environments"` } -// EnvironmentUsage is one environment that uses the Cloud, or still runs -// services it placed after choosing another. +// EnvironmentUsage is one environment that uses the Cloud, through its +// project's default or through services that name it, or still runs +// services it placed. type EnvironmentUsage struct { ProjectID string `json:"project_id"` ProjectName string `json:"project_name"` EnvironmentID string `json:"environment_id"` EnvironmentName string `json:"environment_name"` - // Assigned is false when the environment chose another Cloud, or none, - // and services this one placed are still running there. - Assigned bool `json:"assigned"` + // Default is true when the Cloud is the project's default Cloud. False + // means only services placed on it, or still running there, tie the + // environment to it. + Default bool `json:"default"` Placements []PlacementUsage `json:"placements"` } @@ -59,13 +62,15 @@ func (s *Service) Usage(ctx context.Context, p security.Principal, projectID, id var _ UsageStore = (*PgStore)(nil) -// CloudUsage joins assignments with the placement each live service binding -// recorded when it was applied. +// CloudUsage joins the projects whose default the Cloud is with the +// placement each live service binding recorded when it was applied. func (s *PgStore) CloudUsage(ctx context.Context, org, project, cloud string) (*Usage, error) { out := &Usage{CloudID: cloud, Environments: []EnvironmentUsage{}} - rows, err := s.db.Query(ctx, `SELECT u.project_id,p.name,u.environment_id,e.name,bool_or(u.assigned) + rows, err := s.db.Query(ctx, `SELECT u.project_id,p.name,u.environment_id,e.name,bool_or(u.is_default) FROM ( - SELECT project_id,environment_id,true AS assigned FROM loomplane_cloud_assignments WHERE org_id=$1 AND cloud_id=$2 AND ($3='' OR project_id=$3) + SELECT e.project_id,e.id AS environment_id,true AS is_default FROM loomplane_environments e + JOIN loomplane_cloud_project_grants g ON g.org_id=e.org_id AND g.project_id=e.project_id AND g.cloud_id=$2 AND g.is_default AND NOT g.revoked + WHERE e.org_id=$1 AND ($3='' OR e.project_id=$3) UNION ALL SELECT project_id,environment_id,false FROM loomplane_bindings WHERE org_id=$1 AND subject='service' AND config->'cloud_placement'->>'cloud_id'=$2 AND ($3='' OR project_id=$3) ) u @@ -79,7 +84,7 @@ func (s *PgStore) CloudUsage(ctx context.Context, org, project, cloud string) (* index := map[string]int{} for rows.Next() { var e EnvironmentUsage - if scanErr := rows.Scan(&e.ProjectID, &e.ProjectName, &e.EnvironmentID, &e.EnvironmentName, &e.Assigned); scanErr != nil { + if scanErr := rows.Scan(&e.ProjectID, &e.ProjectName, &e.EnvironmentID, &e.EnvironmentName, &e.Default); scanErr != nil { rows.Close() return nil, scanErr } diff --git a/internal/ctl/clouds.go b/internal/ctl/clouds.go index 069fb8690..08440c922 100644 --- a/internal/ctl/clouds.go +++ b/internal/ctl/clouds.go @@ -32,7 +32,7 @@ func cloudOrganizationFlag() cli.Flag { } func cloudRevisionFlag() cli.Flag { - return cloudFlag("revision", "Expected target, Cloud or assignment revision") + return cloudFlag("revision", "Expected target revision, Cloud revision, or default Cloud revision (0 when the project has none)") } func cloudExecutionFlags() []cli.Flag { return append(recoveryFlags(), cli.NewBoolFlag("yes", "y", "Apply the displayed preview", false), cloudFlag("request-id", "Stable idempotency key to reuse after a lost response")) @@ -42,9 +42,9 @@ func (a *App) cloudsCommand() cli.Command { cli.WithSubcommand(cli.NewCommand("create", "Create a Cloud", a.createCloud, cli.WithFlag(cloudOrganizationFlag()), cli.WithUsage("clouds create --name production"), cli.WithFlags(jsonFlag, cloudFlag("name", "Cloud name")))), cli.WithSubcommand(cli.NewCommand("show", "Show a Cloud", a.showCloud, cli.WithFlag(cloudOrganizationFlag()), cli.WithUsage("clouds show "), cli.WithFlag(jsonFlag))), cli.WithSubcommand(cli.NewCommand("update", "Rename a Cloud at its expected revision", a.updateCloud, cli.WithFlag(cloudOrganizationFlag()), cli.WithUsage("clouds update --name name --revision 1"), cli.WithFlags(jsonFlag, cloudFlag("name", "Cloud name"), cloudRevisionFlag()))), - cli.WithSubcommand(cli.NewCommand("delete", "Delete an unassigned Cloud", a.deleteCloud, cli.WithFlag(cloudOrganizationFlag()), cli.WithUsage("clouds delete "), cli.WithFlag(jsonFlag))), - cli.WithSubcommand(cli.NewCommand("assignment", "Show an environment's Cloud and assignment generation", a.cloudAssignment, cli.WithFlag(cloudOrganizationFlag()), cli.WithUsage("clouds assignment "), cli.WithFlag(jsonFlag))), - cli.WithSubcommand(cli.NewCommand("assign", "Review an environment assignment, then apply with --yes", a.assignCloud, cli.WithFlag(cloudOrganizationFlag()), cli.WithUsage("clouds assign --cloud cloud-id --revision 0 [--yes --wait]"), cli.WithFlags(append(cloudExecutionFlags(), cloudFlag("cloud", "Cloud ID; empty to unassign"), cloudRevisionFlag())...))), + cli.WithSubcommand(cli.NewCommand("delete", "Delete a Cloud no project uses", a.deleteCloud, cli.WithFlag(cloudOrganizationFlag()), cli.WithUsage("clouds delete "), cli.WithFlag(jsonFlag))), + cli.WithSubcommand(cli.NewCommand("default", "Show the project's default Cloud, which every environment uses", a.defaultCloud, cli.WithFlag(cloudOrganizationFlag()), cli.WithUsage("clouds default "), cli.WithFlag(jsonFlag))), + cli.WithSubcommand(cli.NewCommand("make-default", "Review making a Cloud the project's default, then apply with --yes", a.makeDefaultCloud, cli.WithFlag(cloudOrganizationFlag()), cli.WithUsage("clouds make-default --revision N [--yes --wait]"), cli.WithFlags(append(cloudExecutionFlags(), cloudRevisionFlag())...))), cli.WithSubcommand(cli.NewCommand("switch-default", "Review a change to a Cloud's default provider and account, then apply with --yes", a.switchCloudDefault, cli.WithFlag(cloudOrganizationFlag()), cli.WithUsage("clouds switch-default --provider vercel --connection conn-id --revision 3 [--clear] [--yes --wait]"), cli.WithFlags(append(cloudExecutionFlags(), cloudFlag("provider", "Destination provider"), cloudFlag("connection", "Destination connection ID"), cloudFlag("region", "Destination region"), cli.NewBoolFlag("clear", "", "Remove the default", false), cloudRevisionFlag())...)))) } func (a *App) cloudTargetsCommand() cli.Command { @@ -215,21 +215,21 @@ func (a *App) deleteCloudTarget(ctx cli.CommandContext) error { } return c.DeleteCloudTarget(ctxOf(ctx), p.ID, cloudArg(ctx, 1), cloudArg(ctx, 2)) } -func (a *App) cloudAssignment(ctx cli.CommandContext) error { +func (a *App) defaultCloud(ctx cli.CommandContext) error { if ctx.Bool("organization") { return errors.New("this command requires a project; omit --organization") } - c, p, err := a.cloudClient(ctx, 2) + c, p, err := a.cloudClient(ctx, 1) if err != nil { return err } - v, err := c.EnvironmentCloud(ctxOf(ctx), p.ID, cloudArg(ctx, 1)) + v, err := c.DefaultCloud(ctxOf(ctx), p.ID) if err != nil { return err } return a.json(v) } -func (a *App) assignCloud(ctx cli.CommandContext) error { +func (a *App) makeDefaultCloud(ctx cli.CommandContext) error { if ctx.Bool("organization") { return errors.New("this command requires a project; omit --organization") } @@ -241,7 +241,11 @@ func (a *App) assignCloud(ctx cli.CommandContext) error { if err != nil { return err } - preview, err := c.PreviewEnvironmentCloud(ctxOf(ctx), p.ID, cloudArg(ctx, 1), client.EnvironmentCloudInput{CloudID: ctx.String("cloud"), Revision: revision}) + cloud := cloudArg(ctx, 1) + if cloud == "none" { + cloud = "" + } + preview, err := c.PreviewDefaultCloud(ctxOf(ctx), p.ID, client.DefaultCloudInput{CloudID: cloud, Revision: revision}) if err != nil { return err } diff --git a/internal/ctl/clouds_test.go b/internal/ctl/clouds_test.go index 6b53ffc93..521bc3421 100644 --- a/internal/ctl/clouds_test.go +++ b/internal/ctl/clouds_test.go @@ -126,7 +126,7 @@ func TestCloudCommandsRejectInvalidTimeoutBeforeMutation(t *testing.T) { t.Fatal("contacted API before timeout validation") } } -func TestCloudAssignmentRevertAndRoutingRequestContracts(t *testing.T) { +func TestCloudDefaultRevertAndRoutingRequestContracts(t *testing.T) { var path string var body map[string]any var out bytes.Buffer @@ -146,7 +146,7 @@ func TestCloudAssignmentRevertAndRoutingRequestContracts(t *testing.T) { w.WriteHeader(http.StatusAccepted) _, _ = w.Write([]byte(`{"id":"compensation","status":"pending"}`)) default: - _, _ = w.Write([]byte(`{"assignment":null,"revision":2}`)) + _, _ = w.Write([]byte(`{"project_id":"p","cloud":null,"revision":2}`)) } })) defer srv.Close() @@ -156,11 +156,17 @@ func TestCloudAssignmentRevertAndRoutingRequestContracts(t *testing.T) { } return "lp_test" }}) - if err := app.Run([]string{"clouds", "assign", "app", "env", "--cloud", "cloud", "--revision", "2"}); err != nil { + if err := app.Run([]string{"clouds", "make-default", "app", "cloud", "--revision", "2"}); err != nil { t.Fatal(err) } - if path != "/api/v1/projects/p/environments/env/cloud/preview" || body["revision"] != float64(2) || body["cloud_id"] != "cloud" { - t.Fatalf("assignment %s %#v", path, body) + if path != "/api/v1/projects/p/default-cloud/preview" || body["revision"] != float64(2) || body["cloud_id"] != "cloud" { + t.Fatalf("make-default %s %#v", path, body) + } + if err := app.Run([]string{"clouds", "make-default", "app", "none", "--revision", "2"}); err != nil { + t.Fatal(err) + } + if path != "/api/v1/projects/p/default-cloud/preview" || body["cloud_id"] != "" { + t.Fatalf("make-default none %s %#v", path, body) } if err := app.Run([]string{"cloud-syncs", "revert", "app", "original", "--yes", "--request-id", "compensate"}); err != nil { t.Fatal(err) diff --git a/internal/ctl/services_add.go b/internal/ctl/services_add.go index 13588c4ad..045c98688 100644 --- a/internal/ctl/services_add.go +++ b/internal/ctl/services_add.go @@ -24,13 +24,16 @@ func (a *App) addServiceCommand() cli.Command { services add --source # your code: a directory, Dockerfile or Procfile process services add --kind # postgres, redis and the rest of the catalog [--name ] [--env production] [--only] [--needs a,b] [--needed-by a,b] - [--provider ] [--target ] [--dry-run] [--no-plan] [--json]`), + [--cloud-target [--cloud ] | --provider [--target ]] + [--dry-run] [--no-plan] [--json]`), cli.WithFlags(jsonFlag, cli.NewStringFlag("suggested", "", "A service analysis found that the manifest doesn't run yet, by the name services suggest gives it", ""), cli.NewStringFlag("source", "", "Where the service's code is: a directory, a Dockerfile or a Procfile process", ""), cli.NewStringFlag("repo", "", "The repository --source is in, when the project has several", ""), cli.NewStringFlag("kind", "", "A catalog kind, such as postgres or redis. With --source, what the service is: http-service, web-app, static-site or worker", ""), cli.NewStringFlag("name", "", "Its name in the manifest. Defaults to the suggestion's, the kind's or the source's last directory, numbered when taken", ""), + cli.NewStringFlag("cloud-target", "", "A service runs on this Cloud target, in the project's default Cloud unless --cloud names another", ""), + cli.NewStringFlag("cloud", "", "The Cloud --cloud-target is in, by name, when it isn't the project's default", ""), cli.NewStringFlag("provider", "", "Where it runs. A catalog kind runs on server or kubernetes, and takes it from --target when left out", ""), cli.NewStringFlag("target", "", "The checked server or Kubernetes connection it runs on. A catalog kind defaults to the only ready one", ""), cli.NewStringFlag("region", "", "The region it runs in, on a provider that has regions", ""), @@ -162,6 +165,15 @@ func (a *App) addService(ctx cli.CommandContext) error { set(&s.Kind, "kind") set(&s.Provider, "provider") set(&s.Target, "target") + if cloudTarget := strings.TrimSpace(ctx.String("cloud-target")); cloudTarget != "" { + if strings.TrimSpace(ctx.String("provider")) != "" || strings.TrimSpace(ctx.String("target")) != "" { + return errors.New("a service runs on --cloud-target or on --provider and --target, not both") + } + // A Cloud target replaces the provider a suggestion came with. + s.CloudTarget, s.Cloud, s.Provider, s.Target = cloudTarget, strings.TrimSpace(ctx.String("cloud")), "", "" + } else if strings.TrimSpace(ctx.String("cloud")) != "" { + return errors.New("--cloud names the Cloud a --cloud-target is in; pass the target too") + } set(&s.Region, "region") if port := ctx.Int("port"); port > 0 { s.Port = port diff --git a/internal/ctl/services_add_test.go b/internal/ctl/services_add_test.go index 19c5ba7fd..f56e01c4f 100644 --- a/internal/ctl/services_add_test.go +++ b/internal/ctl/services_add_test.go @@ -166,3 +166,27 @@ func TestServiceNames(t *testing.T) { t.Errorf("freeName = %q", got) } } + +// A Cloud target replaces the provider the suggestion came with. +func TestServicesAddOnACloudTarget(t *testing.T) { + var edits []map[string]any + var plans []string + app, _ := recipesCLI(t, recipestest.Registry(t), servicesFake(t, "", "", &edits, &plans)) + if err := app.Run([]string{"services", "add", "shop", "--suggested", "worker", "--cloud", "GPU Lab", "--cloud-target", "a100", "--no-plan"}); err != nil { + t.Fatal(err) + } + want := map[string]any{"add_service": map[string]any{ + "name": "worker", "source": "go:cmd/worker", "cloud": "GPU Lab", "cloud_target": "a100", "needs": []any{"db"}, + }} + if len(edits) != 1 || !reflect.DeepEqual(edits[0], want) { + t.Fatalf("edits %+v", edits) + } + for _, args := range [][]string{ + {"services", "add", "shop", "--suggested", "worker", "--cloud-target", "a100", "--provider", "cloud-run"}, + {"services", "add", "shop", "--suggested", "worker", "--cloud", "GPU Lab"}, + } { + if err := app.Run(args); err == nil { + t.Errorf("%v was accepted", args) + } + } +} diff --git a/internal/currentauthority/fleet_schema_test.go b/internal/currentauthority/fleet_schema_test.go index 71c00e6de..39d66684e 100644 --- a/internal/currentauthority/fleet_schema_test.go +++ b/internal/currentauthority/fleet_schema_test.go @@ -379,5 +379,6 @@ const fleetSchemaSourceJSON = `{ "20261223001100_fleet_scaling_policy_journal.go": "6587066485d751fcb3b4a842f4f49a00c0ebdaf30095c98ebd5d48c94fb76daa", "20261223001300_fleet_metric_history.go": "13515507f71ebc40dce21d5ab5948a16dbc889d186ff2aa83c47bba38d28ca8b", "20261223001600_fleet_adoption_journal.go": "72f33bcad9eb8eb2aae16827cac73dcb9e75c0a64aec054df241f4eed6bb1c36", - "20261225000500_provider_environments.go": "2d94baf8102cd013ba1cc31d915bbb046378098f8bc812ff85f28cb5b2726760" + "20261225000500_provider_environments.go": "2d94baf8102cd013ba1cc31d915bbb046378098f8bc812ff85f28cb5b2726760", + "20261228000100_project_default_cloud.go": "757c6dfe7dc847ea21077f3a099826bcd64d4797b34c0107ba8e654373d8460f" }` diff --git a/internal/currentauthority/testdata/project_schema_sources.json b/internal/currentauthority/testdata/project_schema_sources.json index d2706136a..4962b25b1 100644 --- a/internal/currentauthority/testdata/project_schema_sources.json +++ b/internal/currentauthority/testdata/project_schema_sources.json @@ -16,5 +16,6 @@ "20261216000600_node_public_address.go": "56a1856d4c362a8227ed798ecd7a0d4aefd30cbb84686969d3b86c64ce8c1c99", "20261220000200_agent_foundation.go": "47d2bd061b410f43bcfc721e20ed763fb6bce62c88c1889b96af4c7a24ddae4f", "20261220000600_agent_reports.go": "02e431efff63ae45bad478465d9db5752a72e6ee920109bb45bee05445916d09", - "20261220000700_release_reports.go": "59d526f065279a5aca569b8703cbe0991628bec2763a32bd04c671a14b4a4391" + "20261220000700_release_reports.go": "59d526f065279a5aca569b8703cbe0991628bec2763a32bd04c671a14b4a4391", + "20261228000100_project_default_cloud.go": "757c6dfe7dc847ea21077f3a099826bcd64d4797b34c0107ba8e654373d8460f" } diff --git a/internal/deployments/cloud_targets.go b/internal/deployments/cloud_targets.go index 3b6e91609..c5d760009 100644 --- a/internal/deployments/cloud_targets.go +++ b/internal/deployments/cloud_targets.go @@ -46,30 +46,33 @@ func (r *Runner) validateCloudPlacementAuthority(ctx context.Context, plan *plan if platform && (a.Provider != platformProvider || pin.Provider != platformProvider || pin.Default || pin.ConnectionID != "" || a.ConnectionID != "" || pin.PoolID != "" || pin.Platform.Region != pin.Region) { return stale("is not a Loomplane Cloud placement") } - if pin.AccountIdentity == "" && !platform || pin.CloudRevision < 1 || pin.AssignmentRevision < 1 || !pin.Default && pin.TargetRevision < 1 { + if pin.AccountIdentity == "" && !platform || pin.CloudRevision < 1 || !pin.Default && pin.TargetRevision < 1 { return stale("has no verified identity or revision") } if pin.Provider != a.Provider || reviewed.provider != a.Provider || pin.ConnectionID != a.ConnectionID || pin.Region != a.Region || reviewed.region != a.Region { return stale("differs from the reviewed action") } - var assignment *cloudprofiles.Assignment + var assignment *cloudprofiles.ProjectCloud var err error if retained { reader, ok := r.cloudProfiles.(interface { - RetainedAssignment(context.Context, string, string, string) (*cloudprofiles.Assignment, error) + RetainedCloud(context.Context, string, string, string) (*cloudprofiles.ProjectCloud, error) }) if !ok { return stale("has no retained cleanup resolver") } - assignment, err = reader.RetainedAssignment(ctx, plan.OrgID, plan.ProjectID, plan.EnvironmentID) + assignment, err = reader.RetainedCloud(ctx, plan.OrgID, plan.ProjectID, pin.CloudID) } else { - assignment, err = r.cloudProfiles.Resolve(ctx, plan.OrgID, plan.ProjectID, plan.EnvironmentID) + // The pinned Cloud as the project sees it now. A default switched + // since review advanced this grant's revision, so the check below + // catches it. + assignment, err = r.cloudProfiles.ResolveCloud(ctx, plan.OrgID, plan.ProjectID, pin.CloudID) } if err != nil { return fmt.Errorf("revalidate Cloud target for %s: %w", a.Name, err) } - if assignment == nil || assignment.OrgID != plan.OrgID || assignment.ProjectID != plan.ProjectID || assignment.EnvironmentID != plan.EnvironmentID || assignment.CloudID != pin.CloudID || assignment.CloudRevision != pin.CloudRevision || assignment.Revision != pin.AssignmentRevision || !retained && (pin.GrantRevision > 0 && assignment.GrantRevision != pin.GrantRevision || pin.GrantRevision == 0 && assignment.GrantRevision > 1) { - return stale("assignment changed since review or is outside this scope") + if assignment == nil || assignment.OrgID != plan.OrgID || assignment.ProjectID != plan.ProjectID || assignment.CloudID != pin.CloudID || assignment.CloudRevision != pin.CloudRevision || !retained && (pin.GrantRevision > 0 && assignment.GrantRevision != pin.GrantRevision || pin.GrantRevision == 0 && assignment.GrantRevision > 1) { + return stale("Cloud or grant changed since review or is outside this scope") } if !retained && pin.LocationReview != nil { reader, ok := r.cloudProfiles.(interface { @@ -91,7 +94,7 @@ func (r *Runner) validateCloudPlacementAuthority(ctx context.Context, plan *plan } else { i := slices.IndexFunc(assignment.Targets, func(t cloudprofiles.Target) bool { return t.ID == pin.TargetID }) if i < 0 { - return stale("is missing from the assigned Cloud") + return stale("is missing from its Cloud") } target := assignment.Targets[i] if target.OrgID != plan.OrgID || target.CloudID != pin.CloudID || target.Revision != pin.TargetRevision || target.Name != pin.TargetName || target.Provider != pin.Provider || (pin.PoolID == "" && target.ConnectionID != pin.ConnectionID) || target.PoolID != pin.PoolID || target.LocationID != pin.LocationID || target.ManagedResourceID != pin.ManagedResourceID { diff --git a/internal/deployments/cloud_targets_test.go b/internal/deployments/cloud_targets_test.go index 00dd55242..767443150 100644 --- a/internal/deployments/cloud_targets_test.go +++ b/internal/deployments/cloud_targets_test.go @@ -16,9 +16,9 @@ import ( "github.com/xraph/loomplane/internal/providers" ) -type cloudResolver struct{ assignment *cloudprofiles.Assignment } +type cloudResolver struct{ assignment *cloudprofiles.ProjectCloud } -func (c *cloudResolver) Resolve(context.Context, string, string, string) (*cloudprofiles.Assignment, error) { +func (c *cloudResolver) ResolveCloud(context.Context, string, string, string) (*cloudprofiles.ProjectCloud, error) { return c.assignment, nil } @@ -29,13 +29,13 @@ func cloudRunner(t *testing.T) (*Runner, *planning.Plan, *fakePlans, *recorder, a := &plan.Actions[0] a.Service.Public = false a.ConnectionID = "cloud-account" - a.Service.CloudPlacement = &planning.CloudPlacement{GrantRevision: 1, CloudID: "cloud", CloudRevision: 2, AssignmentRevision: 3, TargetID: "target", TargetRevision: 4, TargetName: "frontend", Provider: a.Provider, ConnectionID: a.ConnectionID} + a.Service.CloudPlacement = &planning.CloudPlacement{GrantRevision: 1, CloudID: "cloud", CloudRevision: 2, TargetID: "target", TargetRevision: 4, TargetName: "frontend", Provider: a.Provider, ConnectionID: a.ConnectionID} c := &connections.Connection{ID: a.ConnectionID, Cloud: "vercel", Status: connections.StatusReady, Details: map[string]string{"team_id": "team-a"}} a.Service.CloudPlacement.AccountIdentity = connections.AccountIdentity(c.Cloud, c.Account, c.Details) exec := &recorder{} r, _, plans := newRunner(t, plan, exec, nil) r.credentials = targetCredentials{a.ConnectionID: c} - resolved := &cloudResolver{assignment: &cloudprofiles.Assignment{OrgID: plan.OrgID, ProjectID: plan.ProjectID, EnvironmentID: plan.EnvironmentID, GrantRevision: 1, CloudID: "cloud", CloudRevision: 2, Revision: 3, Targets: []cloudprofiles.Target{{ID: "target", OrgID: plan.OrgID, ProjectID: plan.ProjectID, CloudID: "cloud", Name: "frontend", Provider: a.Provider, ConnectionID: a.ConnectionID, Revision: 4}}}} + resolved := &cloudResolver{assignment: &cloudprofiles.ProjectCloud{OrgID: plan.OrgID, ProjectID: plan.ProjectID, GrantRevision: 1, CloudID: "cloud", CloudRevision: 2, Targets: []cloudprofiles.Target{{ID: "target", OrgID: plan.OrgID, ProjectID: plan.ProjectID, CloudID: "cloud", Name: "frontend", Provider: a.Provider, ConnectionID: a.ConnectionID, Revision: 4}}}} r.cloudProfiles = resolved return r, plan, plans, exec, resolved } @@ -46,11 +46,10 @@ func TestRunnerCloudTargetRevalidatesBeforeStartAndRun(t *testing.T) { change func(*Runner, *cloudResolver) }{ {"grant", func(_ *Runner, c *cloudResolver) { c.assignment.GrantRevision++ }}, - {"assignment", func(_ *Runner, c *cloudResolver) { c.assignment.Revision++ }}, + {"another cloud", func(_ *Runner, c *cloudResolver) { c.assignment.CloudID = "other" }}, {"cloud", func(_ *Runner, c *cloudResolver) { c.assignment.CloudRevision++ }}, {"target", func(_ *Runner, c *cloudResolver) { c.assignment.Targets[0].Revision++ }}, {"project scope", func(_ *Runner, c *cloudResolver) { c.assignment.ProjectID = "other" }}, - {"environment scope", func(_ *Runner, c *cloudResolver) { c.assignment.EnvironmentID = "other" }}, {"target scope", func(_ *Runner, c *cloudResolver) { c.assignment.Targets[0].OrgID = "other" }}, {"account identity", func(r *Runner, _ *cloudResolver) { r.credentials.(targetCredentials)["cloud-account"].Details["team_id"] = "team-b" @@ -407,14 +406,14 @@ func componentAdoptionRunner(t *testing.T) (*Runner, *planning.Plan, *fakePlans, t.Helper() plan := webAndAPI() c := &connections.Connection{ID: "conn_s", Cloud: "server", Status: connections.StatusReady, Details: map[string]string{"host": "edge.example.com", "user": "deploy", "docker_socket": "/var/run/docker.sock", "docker_id": "daemon-a"}} - pin := &planning.CloudPlacement{GrantRevision: 1, CloudID: "cloud", CloudRevision: 2, AssignmentRevision: 3, TargetID: "target", TargetRevision: 4, TargetName: "edge-host", Provider: "server", ConnectionID: c.ID, AccountIdentity: connections.AccountIdentity(c.Cloud, c.Account, c.Details), RegionSource: "default"} + pin := &planning.CloudPlacement{GrantRevision: 1, CloudID: "cloud", CloudRevision: 2, TargetID: "target", TargetRevision: 4, TargetName: "edge-host", Provider: "server", ConnectionID: c.ID, AccountIdentity: connections.AccountIdentity(c.Cloud, c.Account, c.Details), RegionSource: "default"} cfg := &planning.ResourceConfig{Provider: "server", Target: c.ID, TargetSettings: planning.ReviewedConnectionSettings(c.Cloud, c.Details), Kind: "sample", CloudPlacement: pin} plan.Actions = []planning.Action{{ID: "resource:edge--api", Op: planning.Keep, Subject: planning.ResourceSubject, Name: "edge--api", Provider: "server", ConnectionID: c.ID, Engine: "loomplane", Step: 1, Resource: cfg, AdoptCloudPlacement: true}} exec := &recorder{} r, _, plans := newRunner(t, plan, exec, nil) r.providers = providers.Registry() r.credentials = targetCredentials{c.ID: c} - r.cloudProfiles = &cloudResolver{assignment: &cloudprofiles.Assignment{OrgID: plan.OrgID, ProjectID: plan.ProjectID, EnvironmentID: plan.EnvironmentID, GrantRevision: 1, CloudID: "cloud", CloudRevision: 2, Revision: 3, Targets: []cloudprofiles.Target{{ID: "target", OrgID: plan.OrgID, ProjectID: plan.ProjectID, CloudID: "cloud", Name: "edge-host", Provider: "server", ConnectionID: c.ID, Revision: 4}}}} + r.cloudProfiles = &cloudResolver{assignment: &cloudprofiles.ProjectCloud{OrgID: plan.OrgID, ProjectID: plan.ProjectID, GrantRevision: 1, CloudID: "cloud", CloudRevision: 2, Targets: []cloudprofiles.Target{{ID: "target", OrgID: plan.OrgID, ProjectID: plan.ProjectID, CloudID: "cloud", Name: "edge-host", Provider: "server", ConnectionID: c.ID, Revision: 4}}}} applied := *cfg applied.CloudPlacement = nil raw, err := json.Marshal(applied) diff --git a/internal/deployments/platform_test.go b/internal/deployments/platform_test.go index 71feabd0a..f9bbefbd8 100644 --- a/internal/deployments/platform_test.go +++ b/internal/deployments/platform_test.go @@ -874,13 +874,13 @@ func platformRunner(t *testing.T) (*Runner, *planning.Plan, *fakePlans, *recorde a.Provider, a.Region, a.ConnectionID = "platform", "fra", "" a.Service.Provider, a.Service.Region, a.Service.Public = "platform", "fra", false a.Service.BuildTarget = &planning.BuildTarget{BuilderCloud: "platform", Builder: "platform", Image: platformImage} - a.Service.CloudPlacement = &planning.CloudPlacement{GrantRevision: 1, CloudID: "cloud_platform", CloudRevision: 1, AssignmentRevision: 1, TargetID: "target_fra", TargetRevision: 1, TargetName: "fra", + a.Service.CloudPlacement = &planning.CloudPlacement{GrantRevision: 1, CloudID: "cloud_platform", CloudRevision: 1, TargetID: "target_fra", TargetRevision: 1, TargetName: "fra", Provider: "platform", Region: "fra", RegionSource: "default", Platform: &platformcloud.Ref{Region: "fra", VCPUs: 1, MemoryMiB: 512, DiskMiB: 4096}} exec := &recorder{} r, _, plans := newRunner(t, plan, exec, nil) r.executors["platform"] = exec r.credentials = failingCredentials{t} - resolved := &cloudResolver{assignment: &cloudprofiles.Assignment{OrgID: plan.OrgID, ProjectID: plan.ProjectID, EnvironmentID: plan.EnvironmentID, GrantRevision: 1, CloudID: "cloud_platform", CloudRevision: 1, Revision: 1, + resolved := &cloudResolver{assignment: &cloudprofiles.ProjectCloud{OrgID: plan.OrgID, ProjectID: plan.ProjectID, GrantRevision: 1, CloudID: "cloud_platform", CloudRevision: 1, Targets: []cloudprofiles.Target{{ID: "target_fra", OrgID: plan.OrgID, CloudID: "cloud_platform", Name: "fra", Runtime: "platform", Provider: "platform", Region: "fra", Revision: 1}}}} r.cloudProfiles = resolved return r, plan, plans, exec, resolved @@ -907,7 +907,7 @@ func TestRunnerRevalidatesPlatformTarget(t *testing.T) { "target revision": func(_ *planning.Plan, c *cloudResolver) { c.assignment.Targets[0].Revision++ }, "target runtime": func(_ *planning.Plan, c *cloudResolver) { c.assignment.Targets[0].Runtime = "managed" }, "target region": func(_ *planning.Plan, c *cloudResolver) { c.assignment.Targets[0].Region = "ams" }, - "assignment": func(_ *planning.Plan, c *cloudResolver) { c.assignment.Revision++ }, + "grant": func(_ *planning.Plan, c *cloudResolver) { c.assignment.GrantRevision++ }, "named connection": func(p *planning.Plan, _ *cloudResolver) { p.Actions[0].ConnectionID = "conn_v" }, "room in elsewhere": func(p *planning.Plan, _ *cloudResolver) { p.Actions[0].Service.CloudPlacement.Platform.Region = "ams" }, } { diff --git a/internal/deployments/route_runtime_integration_test.go b/internal/deployments/route_runtime_integration_test.go index c7e0f82ce..1bce98ade 100644 --- a/internal/deployments/route_runtime_integration_test.go +++ b/internal/deployments/route_runtime_integration_test.go @@ -163,8 +163,8 @@ func (releaseCloudAuthority) ValidateCloudSyncSourceCleanup(context.Context, *pl type retainedRuntimeCloud struct{ *cloudResolver } -func (c retainedRuntimeCloud) RetainedAssignment(ctx context.Context, org, project, env string) (*cloudprofiles.Assignment, error) { - return c.Resolve(ctx, org, project, env) +func (c retainedRuntimeCloud) RetainedCloud(ctx context.Context, org, project, cloud string) (*cloudprofiles.ProjectCloud, error) { + return c.ResolveCloud(ctx, org, project, cloud) } func testRetainedRuntime(t *testing.T, shared bool) { @@ -194,7 +194,7 @@ func testRetainedRuntime(t *testing.T, shared bool) { cfg := &planning.ServiceConfig{Provider: "server", Target: "runtime", Service: "api", Port: 80, Workload: provider.Worker, BuildTarget: &planning.BuildTarget{Image: image}, CloudPlacement: &planning.CloudPlacement{CloudID: "cloud"}} conn := &connections.Connection{ID: "runtime", OrgID: "org", Cloud: "server", Status: "ready", Account: "fixture", Details: map[string]string{"docker_id": client.Config.Details["docker_id"]}} cfg.TargetSettings = planning.ReviewedConnectionSettings(conn.Cloud, conn.Details) - cfg.CloudPlacement = &planning.CloudPlacement{CloudID: "cloud", CloudRevision: 1, AssignmentRevision: 1, TargetID: "target", TargetRevision: 1, TargetName: "runtime", Provider: "server", ConnectionID: "runtime", AccountIdentity: connections.AccountIdentity(conn.Cloud, conn.Account, conn.Details)} + cfg.CloudPlacement = &planning.CloudPlacement{CloudID: "cloud", CloudRevision: 1, TargetID: "target", TargetRevision: 1, TargetName: "runtime", Provider: "server", ConnectionID: "runtime", AccountIdentity: connections.AccountIdentity(conn.Cloud, conn.Account, conn.Details)} job := &Job{Deployment: &Deployment{ID: "source-deployment", StartedBy: "usr", PlanID: "source", OrgID: "org", ProjectID: "proj", EnvironmentID: "env"}, Plan: &planning.Plan{ID: "source"}, Connection: &connections.Connection{ID: "runtime"}, Action: planning.Action{ID: "service:api", Name: "api", Subject: planning.ServiceSubject, Provider: "server", ConnectionID: "runtime", Service: cfg}, Progress: func(string, string) {}} var checkpoint []byte job.Checkpoint = func(raw []byte) error { checkpoint = append([]byte(nil), raw...); return nil } @@ -258,7 +258,7 @@ func testRetainedRuntime(t *testing.T, shared bool) { consumer.Replaced = nil plans.bindings["service:consumer"] = &consumer runner.cloudSyncAuth = releaseCloudAuthority{} - runner.cloudProfiles = retainedRuntimeCloud{&cloudResolver{assignment: &cloudprofiles.Assignment{OrgID: "org", ProjectID: "proj", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 1, Revision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", CloudID: "cloud", Name: "runtime", Provider: "server", ConnectionID: "runtime", Revision: 1}}}}} + runner.cloudProfiles = retainedRuntimeCloud{&cloudResolver{assignment: &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "proj", CloudID: "cloud", CloudRevision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", CloudID: "cloud", Name: "runtime", Provider: "server", ConnectionID: "runtime", Revision: 1}}}}} finalize = func() error { if routeErr := runner.ReconcileCloudPlanRoutes(ctx, "org", plan.ID, nil, nil); routeErr != nil { return routeErr diff --git a/internal/manifests/add_test.go b/internal/manifests/add_test.go index b2c57ca48..c3d7f8f15 100644 --- a/internal/manifests/add_test.go +++ b/internal/manifests/add_test.go @@ -83,13 +83,14 @@ func TestAddServiceWritesItWithItsNeeds(t *testing.T) { func TestAddServiceRefusesWhatIsntThere(t *testing.T) { for name, in := range map[string]*NewServiceInput{ - "a taken name": {Name: "db", Source: "cmd/db"}, - "a bad name": {Name: "Worker", Source: "cmd/worker"}, - "no source": {Name: "worker"}, - "an unknown need": {Name: "worker", Source: "cmd/worker", Needs: []string{"cache"}}, - "an unknown env": {Name: "worker", Source: "cmd/worker", EnabledIn: "qa"}, - "only without env": {Name: "worker", Source: "cmd/worker", Only: true}, - "an unknown service": {Name: "worker", Source: "cmd/worker", NeededBy: []string{"web"}}, + "a taken name": {Name: "db", Source: "cmd/db"}, + "a bad name": {Name: "Worker", Source: "cmd/worker"}, + "no source": {Name: "worker"}, + "an unknown need": {Name: "worker", Source: "cmd/worker", Needs: []string{"cache"}}, + "an unknown env": {Name: "worker", Source: "cmd/worker", EnabledIn: "qa"}, + "only without env": {Name: "worker", Source: "cmd/worker", Only: true}, + "an unknown service": {Name: "worker", Source: "cmd/worker", NeededBy: []string{"web"}}, + "a target and a provider": {Name: "worker", Source: "cmd/worker", CloudTarget: "eu-run", Provider: "cloud-run"}, } { t.Run(name, func(t *testing.T) { _, store, err := addEdit(t, appYAML, EditInput{AddService: in}) @@ -176,3 +177,22 @@ func TestAddDryRunSavesNothing(t *testing.T) { t.Fatalf("rev=%+v\n%s", rev, rev.YAML) } } + +func TestAddServiceOnACloudTarget(t *testing.T) { + rev, _, err := addEdit(t, appYAML, EditInput{AddService: &NewServiceInput{ + Name: "trainer", Source: "python:trainer", Cloud: "GPU Lab", CloudTarget: "a100", + }}) + if err != nil { + t.Fatal(err) + } + got := rev.Manifest.Services["trainer"] + if got.Cloud != "GPU Lab" || got.CloudTarget != "a100" || got.Provider != "" { + t.Fatalf("trainer = %+v\n%s", got, rev.YAML) + } + rev, _, err = addEdit(t, appYAML, EditInput{AddService: &NewServiceInput{ + Name: "web", Source: "node:web", CloudTarget: "frontend", + }}) + if err != nil || rev.Manifest.Services["web"].CloudTarget != "frontend" || rev.Manifest.Services["web"].Cloud != "" { + t.Fatalf("web on the default Cloud: %v\n%s", err, rev.YAML) + } +} diff --git a/internal/manifests/manifests.go b/internal/manifests/manifests.go index 193dddf78..f2430322e 100644 --- a/internal/manifests/manifests.go +++ b/internal/manifests/manifests.go @@ -203,9 +203,14 @@ type NewServiceInput struct { Repo string `json:"repo,omitempty"` // Kind corrects what analysis decides the service is: http-service, // web-app, static-site or worker. - Kind string `json:"kind,omitempty"` - Provider string `json:"provider,omitempty"` - Region string `json:"region,omitempty"` + Kind string `json:"kind,omitempty"` + // CloudTarget puts the service on a Cloud target, in the Cloud that + // Cloud names or the project's default. Neither goes with Provider or + // Target. + Cloud string `json:"cloud,omitempty"` + CloudTarget string `json:"cloud_target,omitempty"` + Provider string `json:"provider,omitempty"` + Region string `json:"region,omitempty"` // Target is the checked server or cluster connection it runs on. Target string `json:"target,omitempty"` Port int `json:"port,omitempty"` @@ -315,7 +320,7 @@ func (s *Service) addService(ctx context.Context, orgID, projectID string, doc [ name := strings.TrimSpace(in.Name) needs := trimmed(in.Needs) out, err := manifest.WithService(doc, name, manifest.NewService{ - Repo: in.Repo, Source: in.Source, Kind: in.Kind, Provider: in.Provider, Region: in.Region, + Repo: in.Repo, Source: in.Source, Kind: in.Kind, Cloud: in.Cloud, CloudTarget: in.CloudTarget, Provider: in.Provider, Region: in.Region, Target: in.Target, Port: in.Port, Public: in.Public, Needs: needs, }) if err != nil { diff --git a/internal/models/server_first.go b/internal/models/server_first.go index f9ca4b3e9..894c8afbc 100644 --- a/internal/models/server_first.go +++ b/internal/models/server_first.go @@ -33,10 +33,10 @@ type Servers interface { ListServers(ctx context.Context, p security.Principal, cloud string) ([]*cloudinfra.Server, error) } -// Clouds says which cloud an environment deploys to, with its targets. +// Clouds says which Cloud a project deploys to by default, with its targets. // *cloudprofiles.Service is the real one. type Clouds interface { - EnvironmentCloud(ctx context.Context, p security.Principal, projectID, environmentID string) (*cloudprofiles.Assignment, int64, error) + DefaultCloud(ctx context.Context, p security.Principal, projectID string) (*cloudprofiles.ProjectCloud, error) } var ( @@ -253,19 +253,19 @@ func (s *Service) reviewServer(ctx context.Context, p security.Principal, projec name := serverNameFor(project.Slug, pv.Resource, env.Name) pv.TargetName = name - assignment, _, err := s.d.Clouds.EnvironmentCloud(ctx, p, projectID, env.ID) + assignment, err := s.d.Clouds.DefaultCloud(ctx, p, projectID) switch { case errors.Is(err, cloudprofiles.ErrNotFound) || err == nil && assignment == nil: - problem(ProblemNoCloud, "Add this DigitalOcean account to %s's cloud first.", env.Name) + problem(ProblemNoCloud, "Add this DigitalOcean account to the project's Cloud first.") return case err != nil: - problem(ProblemTarget, "Loomplane couldn't read %s's cloud. Try again.", env.Name) + problem(ProblemTarget, "Loomplane couldn't read the project's Cloud. Try again.") return } if !slices.ContainsFunc(assignment.Targets, func(t cloudprofiles.Target) bool { return t.Provider == connections.DigitalOcean && t.ConnectionID == in.Target.ConnectionID }) { - problem(ProblemNoCloud, "Add this DigitalOcean account to %s's cloud first.", env.Name) + problem(ProblemNoCloud, "Add this DigitalOcean account to the project's Cloud first.") return } // A model moving off a server Loomplane made for it, or a name the diff --git a/internal/models/server_first_test.go b/internal/models/server_first_test.go index 8b48bd9f6..33a0a4dd8 100644 --- a/internal/models/server_first_test.go +++ b/internal/models/server_first_test.go @@ -241,17 +241,17 @@ func (f *fakeServers) calls() (previews, applies, reads int) { return len(f.previews), len(f.applies), f.reads } -// fakeClouds assigns every environment of the project to one cloud. +// fakeClouds gives the project one default Cloud. type fakeClouds struct { - assignment *cloudprofiles.Assignment + assignment *cloudprofiles.ProjectCloud } -func (f fakeClouds) EnvironmentCloud(_ context.Context, _ security.Principal, _, _ string) (*cloudprofiles.Assignment, int64, error) { +func (f fakeClouds) DefaultCloud(_ context.Context, _ security.Principal, _ string) (*cloudprofiles.ProjectCloud, error) { if f.assignment == nil { - return nil, 0, nil + return nil, nil } a := *f.assignment - return &a, a.Revision, nil + return &a, nil } // Waiting and Stranded make memDeployments the cron's WaitingLister. @@ -299,7 +299,7 @@ func newServerFirst(t *testing.T, authz Authorizer) *serverFirstSetup { {ID: gpuImageID, Regions: []string{"tor1"}, Bootstrap: true, Accelerators: []string{provider.VendorNVIDIA}}, }, }}, - clouds: &fakeClouds{assignment: &cloudprofiles.Assignment{ + clouds: &fakeClouds{assignment: &cloudprofiles.ProjectCloud{ OrgID: "org", ProjectID: projectID, CloudID: cloudID, CloudRevision: 7, Targets: []cloudprofiles.Target{{ID: "tgt_do", CloudID: cloudID, Provider: connections.DigitalOcean, ConnectionID: doConn, Region: "tor1"}}, }}, @@ -441,7 +441,7 @@ func TestServerFirstNeedsTheAccountInTheCloud(t *testing.T) { sf := newServerFirst(t, cloudAdmin) sf.clouds.assignment.Targets = []cloudprofiles.Target{{ID: "tgt_k", Provider: connections.Kubernetes, ConnectionID: kubeConn}} pv, err := sf.svc.Preview(context.Background(), member, projectID, stagingID, DeployInput{EntryID: qwen7B, Target: onSize()}) - if err != nil || !slices.Equal(codes(pv), []string{ProblemNoCloud}) || pv.Problems[0].Message != "Add this DigitalOcean account to staging's cloud first." { + if err != nil || !slices.Equal(codes(pv), []string{ProblemNoCloud}) || pv.Problems[0].Message != "Add this DigitalOcean account to the project's Cloud first." { t.Errorf("account outside the cloud: %+v, %v", pv.Problems, err) } sf.clouds.assignment = nil diff --git a/internal/planning/capacity_intent.go b/internal/planning/capacity_intent.go index 48118438c..efe509839 100644 --- a/internal/planning/capacity_intent.go +++ b/internal/planning/capacity_intent.go @@ -20,16 +20,19 @@ import ( // CapacityIntent pins the workload you approve before a runtime exists. // The admitted CloudPlacement is persisted separately from this review. type CapacityIntent struct { - Demand cloudinfra.CapacityDemand `json:"demand"` - ProviderPin cloudinfra.CapacityTemplatePin `json:"provider_pin"` - Template cloudinfra.PoolExpansionPolicy `json:"template"` - TemplateHash string `json:"template_hash"` - CommitSHA string `json:"commit_sha"` - AssignmentRevision int64 `json:"assignment_revision"` - CloudRevision int64 `json:"cloud_revision"` - TargetRevision int64 `json:"target_revision"` - GrantRevision int64 `json:"grant_revision"` - TargetName string `json:"target_name"` + Demand cloudinfra.CapacityDemand `json:"demand"` + ProviderPin cloudinfra.CapacityTemplatePin `json:"provider_pin"` + Template cloudinfra.PoolExpansionPolicy `json:"template"` + TemplateHash string `json:"template_hash"` + CommitSHA string `json:"commit_sha"` + // AssignmentRevision pinned the environment's Cloud assignment before + // Clouds became per project. Nothing checks it now and new intents leave + // it zero, but stored intents are re-hashed on load, so it stays. + AssignmentRevision int64 `json:"assignment_revision"` + CloudRevision int64 `json:"cloud_revision"` + TargetRevision int64 `json:"target_revision"` + GrantRevision int64 `json:"grant_revision"` + TargetName string `json:"target_name"` } type capacityPolicyReader interface { @@ -46,7 +49,7 @@ func capacityTemplateHash(p cloudinfra.PoolExpansionPolicy) (string, error) { return Digest(p) } -func newCapacityIntent(plan *Plan, a *cloudprofiles.Assignment, target cloudprofiles.Target, req cloudinfra.PlacementRequest, policy *cloudinfra.CapacityPolicy, repo string) (*CapacityIntent, error) { +func newCapacityIntent(plan *Plan, a *cloudprofiles.ProjectCloud, target cloudprofiles.Target, req cloudinfra.PlacementRequest, policy *cloudinfra.CapacityPolicy, repo string) (*CapacityIntent, error) { if policy == nil || !policy.Enabled || policy.Revision < 1 || req.LocalData || req.StickyServerID != "" || req.Replicas != 1 || req.CPUMillis <= 0 || req.MemoryBytes <= 0 { return nil, fmt.Errorf("%w: future capacity needs an enabled pool and one bounded stateless replica", ErrInvalid) } @@ -75,7 +78,7 @@ func newCapacityIntent(plan *Plan, a *cloudprofiles.Assignment, target cloudprof if err != nil { return nil, err } - intent := &CapacityIntent{Template: template, Demand: cloudinfra.CapacityDemand{OrgID: plan.OrgID, CloudID: a.CloudID, PoolID: target.PoolID, TargetID: target.ID, ProjectID: plan.ProjectID, EnvironmentID: plan.EnvironmentID, PlanID: plan.ID, Service: req.Service, Architecture: template.Architecture, Resources: cloudinfra.ResourceVector{CPUMillis: req.CPUMillis, MemoryBytes: req.MemoryBytes, GPUKind: req.GPUKind, GPUs: req.GPUs}, PolicyRevision: policy.Revision}, TemplateHash: hash, CommitSHA: commit, AssignmentRevision: a.Revision, CloudRevision: a.CloudRevision, TargetRevision: target.Revision, GrantRevision: a.GrantRevision, TargetName: target.Name} + intent := &CapacityIntent{Template: template, Demand: cloudinfra.CapacityDemand{OrgID: plan.OrgID, CloudID: a.CloudID, PoolID: target.PoolID, TargetID: target.ID, ProjectID: plan.ProjectID, EnvironmentID: plan.EnvironmentID, PlanID: plan.ID, Service: req.Service, Architecture: template.Architecture, Resources: cloudinfra.ResourceVector{CPUMillis: req.CPUMillis, MemoryBytes: req.MemoryBytes, GPUKind: req.GPUKind, GPUs: req.GPUs}, PolicyRevision: policy.Revision}, TemplateHash: hash, CommitSHA: commit, CloudRevision: a.CloudRevision, TargetRevision: target.Revision, GrantRevision: a.GrantRevision, TargetName: target.Name} intent.Demand.IntentHash, err = Digest(intent) return intent, err } @@ -95,7 +98,7 @@ func templateTakesGPUs(poolKind, kind string, gpus int64) error { return nil } -func (s *Service) futureCapacity(ctx context.Context, plan *Plan, a *cloudprofiles.Assignment, target cloudprofiles.Target, req cloudinfra.PlacementRequest, repo string, original error) (*CapacityIntent, error) { +func (s *Service) futureCapacity(ctx context.Context, plan *Plan, a *cloudprofiles.ProjectCloud, target cloudprofiles.Target, req cloudinfra.PlacementRequest, repo string, original error) (*CapacityIntent, error) { reader, ok := s.store.(capacityPolicyReader) // Loomplane Cloud adds hosts itself; a workspace never asks it for // future capacity, so a refusal there stays a refusal. @@ -398,7 +401,7 @@ func (s *PgStore) admitCapacityPlacement(ctx context.Context, plan *Plan, a Acti if identity == "" || details["architecture"] != d.Architecture { return capacityReview(d) } - pin := CloudPlacement{LocationReview: d.LocationReview, Allocation: candidate.Allocation, PoolID: candidate.PoolID, PoolRevision: candidate.PoolRevision, ServerID: candidate.ServerID, ServerRevision: candidate.ServerRevision, ConnectionID: candidate.ConnectionID, ConnectionGeneration: candidate.ConnectionGeneration, CPUMillis: candidate.CPUMillis, MemoryBytes: candidate.MemoryBytes, GPUKind: candidate.GPUKind, GPUs: candidate.GPUs, CloudID: d.CloudID, CloudRevision: intent.CloudRevision, AssignmentRevision: intent.AssignmentRevision, GrantRevision: intent.GrantRevision, TargetID: d.TargetID, TargetRevision: intent.TargetRevision, TargetName: intent.TargetName, Provider: "server", AccountIdentity: identity} + pin := CloudPlacement{LocationReview: d.LocationReview, Allocation: candidate.Allocation, PoolID: candidate.PoolID, PoolRevision: candidate.PoolRevision, ServerID: candidate.ServerID, ServerRevision: candidate.ServerRevision, ConnectionID: candidate.ConnectionID, ConnectionGeneration: candidate.ConnectionGeneration, CPUMillis: candidate.CPUMillis, MemoryBytes: candidate.MemoryBytes, GPUKind: candidate.GPUKind, GPUs: candidate.GPUs, CloudID: d.CloudID, CloudRevision: intent.CloudRevision, GrantRevision: intent.GrantRevision, TargetID: d.TargetID, TargetRevision: intent.TargetRevision, TargetName: intent.TargetName, Provider: "server", AccountIdentity: identity} if d.LocationReview != nil { for _, reviewed := range d.LocationReview.Candidates { if reviewed.TargetID == d.TargetID { diff --git a/internal/planning/capacity_intent_test.go b/internal/planning/capacity_intent_test.go index 363976686..dd7e3acd6 100644 --- a/internal/planning/capacity_intent_test.go +++ b/internal/planning/capacity_intent_test.go @@ -13,9 +13,9 @@ import ( "github.com/xraph/loomplane/internal/security" ) -func intentFixture() (*Plan, *cloudprofiles.Assignment, cloudprofiles.Target, cloudinfra.PlacementRequest, *cloudinfra.CapacityPolicy) { +func intentFixture() (*Plan, *cloudprofiles.ProjectCloud, cloudprofiles.Target, cloudinfra.PlacementRequest, *cloudinfra.CapacityPolicy) { p := &Plan{ID: "plan", OrgID: "org", ProjectID: "project", EnvironmentID: "env", Sources: []PlanSource{{Alias: "app", CommitSHA: "commit"}}} - a := &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", Revision: 2, CloudRevision: 3, GrantRevision: 4} + a := &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 3, GrantRevision: 4} target := cloudprofiles.Target{ID: "target", OrgID: "org", CloudID: "cloud", PoolID: "pool", Revision: 5, Provider: "server"} req := cloudinfra.PlacementRequest{PlanID: p.ID, OrgID: p.OrgID, ProjectID: p.ProjectID, EnvironmentID: p.EnvironmentID, CloudID: a.CloudID, TargetID: target.ID, PoolID: target.PoolID, Service: "web", CPUMillis: 1000, MemoryBytes: 512 << 20, Replicas: 1} policy := &cloudinfra.CapacityPolicy{Enabled: true, Revision: 1, Pools: []cloudinfra.PoolExpansionPolicy{{PoolID: "pool", ConnectionID: "provider", Region: "region", Architecture: "amd64", Image: "image", AllowedSizes: []string{"size"}, MaxServers: 3}}} @@ -27,7 +27,7 @@ func TestCapacityIntentApproval(t *testing.T) { if err != nil { t.Fatal(err) } - if got.CommitSHA != "commit" || got.Demand.Resources.CPUMillis != 1000 || got.TemplateHash == "" || got.Demand.IntentHash == "" || got.AssignmentRevision != 2 { + if got.CommitSHA != "commit" || got.Demand.Resources.CPUMillis != 1000 || got.TemplateHash == "" || got.Demand.IntentHash == "" || got.GrantRevision != a.GrantRevision { t.Fatalf("unbounded intent: %+v", got) } policy.Enabled = false @@ -160,6 +160,9 @@ func TestStoredCPUIntentDigestUnchanged(t *testing.T) { t.Fatal(err) } fresh.ProviderPin = cloudinfra.CapacityTemplatePin{AccountID: "account", ConnectionGeneration: 1} + // The stored intent predates per-project Clouds and pinned an + // assignment revision; a fresh one leaves it zero. + fresh.AssignmentRevision = 2 fresh.Demand.IntentHash = "" if hash, hashErr := Digest(fresh); hashErr != nil || hash != saved { t.Fatalf("fresh CPU intent digest moved: %s, want %s (%v)", hash, saved, hashErr) diff --git a/internal/planning/cloud_default_switch.go b/internal/planning/cloud_default_switch.go index 88e1f425d..7f1083f74 100644 --- a/internal/planning/cloud_default_switch.go +++ b/internal/planning/cloud_default_switch.go @@ -34,8 +34,8 @@ func (s *Service) previewDefaultSwitch(ctx context.Context, st cloudprofiles.Syn case in.Runtime == platformRuntime || strings.TrimSpace(in.Provider) == platformRuntime: // Loomplane Cloud is reached through its own targets, never a // Cloud default, which names a connection it doesn't have. - return fmt.Errorf("%w: Loomplane Cloud can't be a Cloud default; assign the environment to Loomplane Cloud and name its target with cloud_target", cloudprofiles.ErrInvalid) - case in.TargetID != "" || in.EnvironmentID != "" || in.Runtime != "" && in.Runtime != "managed" || in.PoolID != "": + return fmt.Errorf("%w: Loomplane Cloud can't be a Cloud default; grant the project Loomplane Cloud and name its target with cloud_target", cloudprofiles.ErrInvalid) + case in.TargetID != "" || in.ProjectDefault || in.Runtime != "" && in.Runtime != "managed" || in.PoolID != "": return fmt.Errorf("%w: a default placement is one managed provider and connection", cloudprofiles.ErrInvalid) } profile, err := st.GetProfile(ctx, p.OrgID, "", in.CloudID) diff --git a/internal/planning/cloud_default_switch_test.go b/internal/planning/cloud_default_switch_test.go index 61b1f5f07..08d67cd03 100644 --- a/internal/planning/cloud_default_switch_test.go +++ b/internal/planning/cloud_default_switch_test.go @@ -38,10 +38,10 @@ func TestSelectsPlacement(t *testing.T) { func TestRepinCloudPlacement(t *testing.T) { a := appliedAssignment("old") - a.CloudRevision, a.Revision, a.GrantRevision = 7, 3, 2 + a.CloudRevision, a.GrantRevision = 7, 2 a.DefaultPlacement = &cloudprofiles.DefaultPlacement{Provider: "vercel", ConnectionID: "default"} pin, ok := repinCloudPlacement(CloudPlacement{CloudID: "cloud", CloudRevision: 1, TargetID: "target", TargetRevision: 1, Provider: "vercel", ConnectionID: "old"}, a) - if !ok || pin.CloudRevision != 7 || pin.AssignmentRevision != 3 || pin.GrantRevision != 2 || pin.TargetRevision != 2 || pin.TargetName != "frontend" { + if !ok || pin.CloudRevision != 7 || pin.GrantRevision != 2 || pin.TargetRevision != 2 || pin.TargetName != "frontend" { t.Fatalf("target pin: %+v %v", pin, ok) } if pin, ok = repinCloudPlacement(CloudPlacement{Default: true, CloudID: "cloud", Provider: "vercel", ConnectionID: "default"}, a); !ok || pin.CloudRevision != 7 { @@ -65,7 +65,7 @@ func TestAppliedCloudPlanDefaultSwitchRepinsDependents(t *testing.T) { api := appliedTestBinding(t, "api", "commit") var cfg ServiceConfig _ = json.Unmarshal(api.Config, &cfg) - cfg.CloudPlacement = &CloudPlacement{Default: true, CloudID: "cloud", CloudRevision: 1, AssignmentRevision: 1, Provider: "vercel", ConnectionID: "old", AccountIdentity: "vercel:old"} + cfg.CloudPlacement = &CloudPlacement{Default: true, CloudID: "cloud", CloudRevision: 1, Provider: "vercel", ConnectionID: "old", AccountIdentity: "vercel:old"} api.Config, _ = json.Marshal(cfg) web := appliedTestBinding(t, "web", "commit") var webCfg ServiceConfig @@ -98,7 +98,7 @@ func platformBinding(t *testing.T) *Binding { t.Helper() cfg := ServiceConfig{Provider: "platform", Region: "fra", Repo: "app", CommitSHA: "commit", Service: "web", Ecosystem: "go", Image: "Dockerfile", Workload: provider.WebApp, Execution: provider.Container, Public: true, BuildTarget: &BuildTarget{BuilderCloud: platformBuilder, Builder: platformBuilder}, - CloudPlacement: &CloudPlacement{CloudID: "cloud_platform", CloudRevision: 1, AssignmentRevision: 1, GrantRevision: 1, TargetID: "target_fra", TargetRevision: 1, TargetName: "fra", Provider: "platform", Region: "fra", RegionSource: "default", Platform: &platformcloud.Ref{Region: "fra", VCPUs: 1, MemoryMiB: 512, DiskMiB: platformServiceDiskMiB}}, + CloudPlacement: &CloudPlacement{CloudID: "cloud_platform", CloudRevision: 1, GrantRevision: 1, TargetID: "target_fra", TargetRevision: 1, TargetName: "fra", Provider: "platform", Region: "fra", RegionSource: "default", Platform: &platformcloud.Ref{Region: "fra", VCPUs: 1, MemoryMiB: 512, DiskMiB: platformServiceDiskMiB}}, AppliedInputs: &AppliedInputs{Variables: "org/env/applied-inputs/dep/web", Source: &PlanSource{SourceID: "src", Alias: "app", Repository: "owner/app", CommitSHA: "commit"}, ArtifactKey: "sources/org/project/app/commit.tar.gz"}} raw, err := json.Marshal(cfg) if err != nil { @@ -114,7 +114,7 @@ func platformBinding(t *testing.T) *Binding { func TestDefaultSwitchOffPlatformCloud(t *testing.T) { registry := providers.Registry() options := []ConnectionOption{{ID: "new", Cloud: "vercel", Ready: true, Account: "new", Details: map[string]string{"team_id": "new"}}} - mine := &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 1, Revision: 2, DefaultPlacement: &cloudprofiles.DefaultPlacement{Provider: "vercel", ConnectionID: "new"}} + mine := &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 1, GrantRevision: 2, DefaultPlacement: &cloudprofiles.DefaultPlacement{Provider: "vercel", ConnectionID: "new"}} off := AppliedCloudPlan([]*Binding{platformBinding(t)}, mine, "", options, registry) if !off.Executable { @@ -129,7 +129,7 @@ func TestDefaultSwitchOffPlatformCloud(t *testing.T) { var cfg ServiceConfig _ = json.Unmarshal(platformBinding(t).Config, &cfg) cfg.Provider, cfg.Execution, cfg.BuildTarget = "vercel", provider.Serverless, nil - cfg.CloudPlacement = &CloudPlacement{CloudID: "cloud", CloudRevision: 1, AssignmentRevision: 2, TargetID: "target_mine", TargetRevision: 1, TargetName: "fra", Provider: "vercel", ConnectionID: "new", AccountIdentity: "vercel:new"} + cfg.CloudPlacement = &CloudPlacement{CloudID: "cloud", CloudRevision: 1, TargetID: "target_mine", TargetRevision: 1, TargetName: "fra", Provider: "vercel", ConnectionID: "new", AccountIdentity: "vercel:new"} back := platformBinding(t) back.Provider, back.ConnectionID, back.Region = "vercel", "new", "" back.Config, _ = json.Marshal(cfg) diff --git a/internal/planning/cloud_locations_test.go b/internal/planning/cloud_locations_test.go index 696348e08..451c8997e 100644 --- a/internal/planning/cloud_locations_test.go +++ b/internal/planning/cloud_locations_test.go @@ -10,7 +10,7 @@ import ( ) func TestCloudLocationLegacyTarget(t *testing.T) { - p := targetPlacement(&cloudprofiles.Assignment{}, cloudprofiles.Target{Name: "eu-independent"}, ConnectionOption{}, "", "", "") + p := targetPlacement(&cloudprofiles.ProjectCloud{}, cloudprofiles.Target{Name: "eu-independent"}, ConnectionOption{}, "", "", "") raw, err := json.Marshal(p) if err != nil { t.Fatal(err) @@ -18,7 +18,7 @@ func TestCloudLocationLegacyTarget(t *testing.T) { if strings.Contains(string(raw), "location_id") || strings.Contains(string(raw), "managed_resource_id") { t.Fatalf("legacy wire shape changed: %s", raw) } - p = targetPlacement(&cloudprofiles.Assignment{}, cloudprofiles.Target{LocationID: "location_1", ManagedResourceID: "resource_1"}, ConnectionOption{}, "", "", "") + p = targetPlacement(&cloudprofiles.ProjectCloud{}, cloudprofiles.Target{LocationID: "location_1", ManagedResourceID: "resource_1"}, ConnectionOption{}, "", "", "") if p.LocationID != "location_1" || p.ManagedResourceID != "resource_1" { t.Fatal("explicit target membership lost") } diff --git a/internal/planning/cloud_named.go b/internal/planning/cloud_named.go new file mode 100644 index 000000000..ef3dd10a2 --- /dev/null +++ b/internal/planning/cloud_named.go @@ -0,0 +1,116 @@ +package planning + +import ( + "context" + "errors" + "fmt" + "maps" + "slices" + + "github.com/xraph/loomplane/internal/cloudinfra" + "github.com/xraph/loomplane/internal/cloudprofiles" + "github.com/xraph/loomplane/internal/platformcloud" + "github.com/xraph/loomplane/pkg/manifest" +) + +// namedClouds resolves every Cloud a service names with cloud. A Cloud the +// project can't use is a finding on the first service that names it. +func (s *Service) namedClouds(ctx context.Context, plan *Plan, needs cloudNeeds) (map[string]*cloudprofiles.ProjectCloud, error) { + if len(needs.Named) == 0 { + return nil, nil + } + resolver, ok := s.cloudProfiles.(cloudprofiles.NamedResolver) + if !ok { + return nil, errors.New("services name a Cloud, and this planner can't resolve Clouds by name") + } + out := map[string]*cloudprofiles.ProjectCloud{} + for _, name := range slices.Sorted(maps.Keys(needs.Named)) { + c, err := resolver.ResolveNamedCloud(ctx, plan.OrgID, plan.ProjectID, name) + if errors.Is(err, cloudprofiles.ErrNotFound) { + return nil, &CloudPlacementError{Code: "cloud-unknown", Path: "services." + needs.Named[name][0] + ".cloud", Message: fmt.Sprintf("No Cloud named %s is granted to this project. Check the name, or ask an organization admin to grant it.", name)} + } + if err != nil { + return nil, err + } + if c.OrgID != plan.OrgID || c.ProjectID != plan.ProjectID { + return nil, fmt.Errorf("the Cloud named %s is outside this organization or project", name) + } + out[name] = c + } + return out, nil +} + +// resolveAcrossClouds places every service through its own Cloud: one pass +// for the project's default Cloud, then one for each Cloud a service names. +// Each pass holds every service of another Cloud, so the single-Cloud +// resolution runs unchanged and the passes' placements merge. +func (s *Service) resolveAcrossClouds(ctx context.Context, plan *Plan, m *manifest.Manifest, defaultCloud *cloudprofiles.ProjectCloud, named map[string]*cloudprofiles.ProjectCloud, needs cloudNeeds, bindings []*Binding, options []ConnectionOption, selections map[string]locationSelection, input Input, intents map[string]*CapacityIntent) (*manifest.Manifest, map[string]CloudPlacement, error) { + cloudOf := map[string]string{} + for name, services := range needs.Named { + for _, service := range services { + cloudOf[service] = name + } + } + passes := append([]string{""}, slices.Sorted(maps.Keys(named))...) + // Each pass clears the default tags it resolved; the next still needs them. + tags := slices.Clone(m.Defaults.CloudTags) + out, placements := m, map[string]CloudPlacement{} + for i, name := range passes { + cloud := defaultCloud + if name != "" { + cloud = named[name] + } + held := maps.Clone(needs.Held) + constrained := false + for service, svc := range out.Services { + if cloudOf[service] != name { + held[service] = true + continue + } + constrained = constrained || svc.For(plan.Environment, out.Defaults).Placement != nil + } + var pools map[string]*cloudinfra.Placement + var err error + if constrained { + pools, err = s.resolvePoolsWithLocationInput(ctx, plan, out, cloud, bindings, options, held, selections, input, intents) + } else { + pools, err = s.resolvePools(ctx, plan, out, cloud, bindings, options, held, intents) + } + if err != nil { + return nil, nil, err + } + var platform map[string]*platformcloud.Ref + if platform, err = s.resolvePlatform(ctx, plan, out, cloud, held); err != nil { + return nil, nil, err + } + next, placed, err := resolveCloudPass(out, plan.Environment, cloud, options, pools, platform, held, cloudPass{gateway: name == "", named: name != ""}, intents) + if err != nil { + return nil, nil, err + } + if i < len(passes)-1 { + next.Defaults.CloudTags = slices.Clone(tags) + } + maps.Copy(placements, placed) + out = next + } + return out, placements, nil +} + +// cloudsByID chooses, for an applied pin, the view of the Cloud it pins: +// the default or a named one. A pin on a Cloud the plan doesn't use falls +// back to the default, as a single-Cloud plan always did. +func cloudsByID(defaultCloud *cloudprofiles.ProjectCloud, named map[string]*cloudprofiles.ProjectCloud) cloudChooser { + views := map[string]*cloudprofiles.ProjectCloud{} + for _, c := range named { + views[c.CloudID] = c + } + if defaultCloud != nil { + views[defaultCloud.CloudID] = defaultCloud + } + return func(pin *CloudPlacement) (*cloudprofiles.ProjectCloud, bool) { + if c := views[pin.CloudID]; c != nil { + return c, true + } + return defaultCloud, true + } +} diff --git a/internal/planning/cloud_named_test.go b/internal/planning/cloud_named_test.go new file mode 100644 index 000000000..32d7bb9ad --- /dev/null +++ b/internal/planning/cloud_named_test.go @@ -0,0 +1,111 @@ +package planning + +import ( + "context" + "encoding/json" + "testing" + + "github.com/xraph/loomplane/internal/cloudprofiles" + "github.com/xraph/loomplane/internal/providers" +) + +// namedTargetResolver adds Clouds a manifest can name to the default one. +type namedTargetResolver struct { + *targetResolver + named map[string]*cloudprofiles.ProjectCloud +} + +func (n namedTargetResolver) ResolveNamedCloud(_ context.Context, _, _, name string) (*cloudprofiles.ProjectCloud, error) { + if c := n.named[name]; c != nil { + return c, nil + } + return nil, cloudprofiles.ErrNotFound +} + +// gpuLab has a target called frontend too, so only the Cloud tells the two apart. +func gpuLab() *cloudprofiles.ProjectCloud { + return &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "lab", Name: "GPU Lab", CloudRevision: 1, GrantRevision: 2, Targets: []cloudprofiles.Target{ + {ID: "lab-frontend", OrgID: "org", ProjectID: "project", CloudID: "lab", Name: "frontend", Provider: "vercel", ConnectionID: "b", Revision: 7}, + }} +} + +func TestNamedCloudsPlaceEachServiceThroughItsOwnCloud(t *testing.T) { + s, p, r := targetPlanningService(t, "version: 1\nservices:\n web: {source: cmd/api, cloud_target: frontend}\n trainer: {source: cmd/api, cloud: GPU Lab, cloud_target: frontend}\n") + s.cloudProfiles = namedTargetResolver{r, map[string]*cloudprofiles.ProjectCloud{"GPU Lab": gpuLab()}} + result, _, err := s.compute(t.Context(), p) + if err != nil || !result.Executable { + t.Fatalf("plan: %+v %v", result.Problems, err) + } + for name, want := range map[string]CloudPlacement{ + "web": {CloudID: "cloud", TargetID: "target-a", ConnectionID: "a", GrantRevision: 4}, + "trainer": {CloudID: "lab", TargetID: "lab-frontend", ConnectionID: "b", GrantRevision: 2, Named: true}, + } { + var got *CloudPlacement + for _, a := range result.Actions { + if a.Name == name && a.Service != nil { + got = a.Service.CloudPlacement + } + } + if got == nil || got.CloudID != want.CloudID || got.TargetID != want.TargetID || got.ConnectionID != want.ConnectionID || got.GrantRevision != want.GrantRevision || got.Named != want.Named { + t.Errorf("%s placed %+v, want %+v", name, got, want) + } + } +} + +func TestNamedCloudsFindings(t *testing.T) { + for _, tc := range []struct { + name, doc, code, path string + }{ + {"unknown Cloud", "version: 1\nservices:\n trainer: {source: cmd/api, cloud: Nowhere, cloud_target: frontend}\n", "cloud-unknown", "services.trainer.cloud"}, + {"no default placement", "version: 1\nservices:\n trainer: {source: cmd/api, cloud: GPU Lab}\n", "cloud-default-missing", "services.trainer.cloud"}, + } { + t.Run(tc.name, func(t *testing.T) { + s, p, r := targetPlanningService(t, tc.doc) + s.cloudProfiles = namedTargetResolver{r, map[string]*cloudprofiles.ProjectCloud{"GPU Lab": gpuLab()}} + result, _, err := s.compute(t.Context(), p) + if err != nil || result.Executable || len(result.Problems) != 1 { + t.Fatalf("plan: %+v %v", result, err) + } + if f := result.Problems[0]; f.Code != tc.code || f.Path != tc.path || f.Name != "trainer" { + t.Fatalf("finding %+v, want %s at %s", f, tc.code, tc.path) + } + }) + } +} + +func TestMissingTargetSaysWhichCloud(t *testing.T) { + s, p, r := targetPlanningService(t, "version: 1\nservices:\n trainer: {source: cmd/api, cloud: GPU Lab, cloud_target: preview}\n") + s.cloudProfiles = namedTargetResolver{r, map[string]*cloudprofiles.ProjectCloud{"GPU Lab": gpuLab()}} + result, _, err := s.compute(t.Context(), p) + if err != nil || result.Executable || len(result.Problems) != 1 { + t.Fatalf("plan: %+v %v", result, err) + } + if got := result.Problems[0].Message; got != `services.trainer.cloud_target: target "preview" isn't in Cloud GPU Lab; choose one of its targets, or name another Cloud with cloud` { + t.Fatalf("message %q", got) + } +} + +// Changing the project's default moves services that reach their Cloud as +// the default, and keeps a service whose manifest names its Cloud. +func TestDefaultChangeKeepsServicesThatNameTheirCloud(t *testing.T) { + registry := providers.Registry() + follows := appliedTestBinding(t, "api", "older") + names := appliedTestBinding(t, "web", "older") + var cfg ServiceConfig + _ = json.Unmarshal(names.Config, &cfg) + cfg.CloudPlacement.Named = true + names.Config, _ = json.Marshal(cfg) + after := appliedAssignment("new") + choose := func(pin *CloudPlacement) (*cloudprofiles.ProjectCloud, bool) { return after, !pin.Named } + result := appliedCloudPlanChoosing([]*Binding{follows, names}, choose, "", []ConnectionOption{{ID: "new", Cloud: "vercel", Ready: true, Account: "new", Details: map[string]string{"team_id": "new"}}}, registry, nil, nil) + if !result.Executable { + t.Fatalf("blocked: %+v", result.Problems) + } + ops := map[string]Op{} + for _, a := range result.Actions { + ops[a.Name] = a.Op + } + if ops["api"] == Keep || ops["web"] != Keep { + t.Fatalf("api should move and web stay: %+v", ops) + } +} diff --git a/internal/planning/cloud_platform_owned_test.go b/internal/planning/cloud_platform_owned_test.go index 0ddf07973..6357dd46d 100644 --- a/internal/planning/cloud_platform_owned_test.go +++ b/internal/planning/cloud_platform_owned_test.go @@ -15,6 +15,7 @@ import ( // Loomplane Cloud and one user Cloud it could move to. Methods a preview // doesn't reach stay nil and panic. type platformSyncStore struct { + defaultCloud string cloudprofiles.SyncStore saved *cloudprofiles.Preview } @@ -44,11 +45,24 @@ func (st *platformSyncStore) GetTarget(_ context.Context, org, _, cloud, id stri func (st *platformSyncStore) ListTargets(context.Context, string, string, string) ([]*cloudprofiles.Target, error) { return []*cloudprofiles.Target{}, nil } -func (st *platformSyncStore) Resolve(_ context.Context, org, project, env string) (*cloudprofiles.Assignment, error) { - return &cloudprofiles.Assignment{OrgID: org, ProjectID: project, EnvironmentID: env, CloudID: platformProfile.ID, CloudRevision: 1, Revision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{*platformTarget}}, nil + +// ResolveCloud answers the platform Cloud, the project's default unless the +// test moved it, and an empty Cloud for any other ID. +func (st *platformSyncStore) ResolveCloud(_ context.Context, org, project, cloud string) (*cloudprofiles.ProjectCloud, error) { + current, _, _ := st.DefaultCloud(context.Background(), org, project) + if cloud == "" { + cloud = current + } + if cloud != platformProfile.ID { + return &cloudprofiles.ProjectCloud{OrgID: org, ProjectID: project, CloudID: cloud, CloudRevision: 1, GrantRevision: 1, Default: cloud == current, Targets: []cloudprofiles.Target{}}, nil + } + return &cloudprofiles.ProjectCloud{OrgID: org, ProjectID: project, CloudID: platformProfile.ID, CloudRevision: 1, GrantRevision: 1, Default: cloud == current, Targets: []cloudprofiles.Target{*platformTarget}}, nil } -func (st *platformSyncStore) AssignmentGeneration(context.Context, string, string, string) (int64, error) { - return 1, nil +func (st *platformSyncStore) DefaultCloud(context.Context, string, string) (string, int64, error) { + if st.defaultCloud != "" { + return st.defaultCloud, 1, nil + } + return platformProfile.ID, 1, nil } func (st *platformSyncStore) SnapshotBindings(context.Context, string, string) (json.RawMessage, error) { return json.RawMessage(`[]`), nil @@ -96,11 +110,11 @@ func TestPreviewCloudChangeOnPlatformOwnedCloud(t *testing.T) { t.Fatal("a refused change saved a preview") } - preview, err := s.PreviewCloudChange(ctx, p, "proj", cloudprofiles.ChangeInput{CloudID: "cloud_user", EnvironmentID: "env", Revision: 1}) + preview, err := s.PreviewCloudChange(ctx, p, "proj", cloudprofiles.ChangeInput{CloudID: "cloud_user", ProjectDefault: true, Revision: 1}) if err != nil { - t.Fatalf("moving an environment off the platform Cloud: %v", err) + t.Fatalf("moving a project off the platform Cloud: %v", err) } - if st.saved == nil || preview.BeforeAssignment == nil || preview.BeforeAssignment.CloudID != "cloud_platform" || preview.AfterAssignment == nil || preview.AfterAssignment.CloudID != "cloud_user" { + if st.saved == nil || preview.BeforeCloud == nil || preview.BeforeCloud.CloudID != "cloud_platform" || preview.AfterCloud == nil || preview.AfterCloud.CloudID != "cloud_user" { t.Fatalf("preview = %+v", preview) } } diff --git a/internal/planning/cloud_servers_test.go b/internal/planning/cloud_servers_test.go index 1e7494bc9..95bce2bdf 100644 --- a/internal/planning/cloud_servers_test.go +++ b/internal/planning/cloud_servers_test.go @@ -23,8 +23,8 @@ func edgeHostTarget() cloudprofiles.Target { return cloudprofiles.Target{ID: "t1", OrgID: "org", CloudID: "cloud_1", Name: "edge-host", Provider: "server", ConnectionID: targetA, Runtime: "server", Revision: 5} } -func edgeAssignment(targets ...cloudprofiles.Target) *cloudprofiles.Assignment { - return &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud_1", CloudRevision: 2, Revision: 3, GrantRevision: 4, Targets: targets} +func edgeAssignment(targets ...cloudprofiles.Target) *cloudprofiles.ProjectCloud { + return &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud_1", CloudRevision: 2, GrantRevision: 4, Targets: targets} } // hostedConnections are the composed fixtures with targetA the runtime @@ -348,7 +348,7 @@ func TestUnverifiedPlacementsNameResourcesOnTheCloud(t *testing.T) { unreviewedCloud := edgeAssignment(edgeHostTarget()) unreviewedCloud.CloudRevision = 0 for name, tt := range map[string]struct { - assignment *cloudprofiles.Assignment + assignment *cloudprofiles.ProjectCloud options []ConnectionOption want bool }{ diff --git a/internal/planning/cloud_sync.go b/internal/planning/cloud_sync.go index ae9dd7637..0925a940d 100644 --- a/internal/planning/cloud_sync.go +++ b/internal/planning/cloud_sync.go @@ -73,17 +73,12 @@ func (s *Service) previewCloudChange(ctx context.Context, p security.Principal, if err := s.authorizeCloudSync(ctx, p, project); err != nil { return nil, err } - if in.EnvironmentID != "" { - if guardErr := s.requireUnmanagedEnvironmentID(ctx, p.OrgID, project, in.EnvironmentID); guardErr != nil { - return nil, guardErr - } - } st, err := s.syncStore() if err != nil { return nil, err } selected := 0 - for _, set := range []bool{in.TargetID != "", in.EnvironmentID != "", in.Default} { + for _, set := range []bool{in.TargetID != "", in.ProjectDefault, in.Default} { if set { selected++ } @@ -116,7 +111,7 @@ func (s *Service) previewCloudChange(ctx context.Context, p security.Principal, } snapshot.Shared = true } - var desired *cloudprofiles.Assignment + var desired *cloudprofiles.ProjectCloud switch { case in.TargetID != "": before, e := st.GetTarget(ctx, p.OrgID, "", in.CloudID, in.TargetID) @@ -148,29 +143,50 @@ func (s *Service) previewCloudChange(ctx context.Context, p security.Principal, if switchErr := s.previewDefaultSwitch(ctx, st, p, in, preview, snapshot, options); switchErr != nil { return nil, switchErr } - case in.CloudID != "": - profile, e := st.GetProfile(ctx, p.OrgID, project, in.CloudID) + case in.ProjectDefault: + // The token is the current default's grant revision, zero for none. + current, revision, e := st.DefaultCloud(ctx, p.OrgID, project) if e != nil { return nil, e } - targets, e := st.ListTargets(ctx, p.OrgID, project, in.CloudID) - if e != nil { + if revision != in.Revision { + return nil, cloudprofiles.ErrConflict + } + if current == in.CloudID { + return nil, fmt.Errorf("%w: that is already the project's default Cloud", cloudprofiles.ErrInvalid) + } + if preview.BeforeCloud, e = st.ResolveCloud(ctx, p.OrgID, project, ""); e != nil { return nil, e } - desired = &cloudprofiles.Assignment{OrgID: p.OrgID, ProjectID: project, EnvironmentID: in.EnvironmentID, CloudID: profile.ID, CloudRevision: profile.Revision, Revision: in.Revision + 1, DefaultPlacement: profile.DefaultPlacement} - for _, t := range targets { - desired.Targets = append(desired.Targets, *t) + if in.CloudID != "" { + // Only a Cloud granted to the project can become its default. + if desired, e = st.ResolveCloud(ctx, p.OrgID, project, in.CloudID); e != nil { + return nil, e + } + desired.Default = true + } + preview.AfterCloud = desired + // Acceptance compares both grants as reviewed. Making a Cloud the + // default advances its grant's revision, and the plans this review + // materializes run after that, so they pin the revision they'll find. + for _, c := range []*cloudprofiles.ProjectCloud{preview.BeforeCloud, desired} { + if c != nil { + snapshot.Grants = append(snapshot.Grants, cloudprofiles.ProjectGrant{OrgID: p.OrgID, CloudID: c.CloudID, ProjectID: project, Revision: c.GrantRevision}) + } + } + if desired != nil { + desired.GrantRevision++ } } var environments []*projects.Environment if snapshot.Shared { shared, ok := st.(interface { - AssignedEnvironments(context.Context, string, string) ([]*projects.Environment, error) + EnvironmentsUsing(context.Context, string, string) ([]*projects.Environment, error) }) if !ok { return nil, cloudprofiles.ErrInvalid } - environments, err = shared.AssignedEnvironments(ctx, p.OrgID, in.CloudID) + environments, err = shared.EnvironmentsUsing(ctx, p.OrgID, in.CloudID) } else { environments, err = s.projects.ListEnvironments(ctx, p.OrgID, project) } @@ -190,27 +206,30 @@ func (s *Service) previewCloudChange(ctx context.Context, p security.Principal, environments = slices.DeleteFunc(environments, func(e *projects.Environment) bool { return !allowed[e.ProjectID+"/"+e.ID] }) } var planned []cloudinfra.PlannedPlacement - found := in.EnvironmentID == "" for _, env := range environments { project := env.ProjectID - assignment, e := st.Resolve(ctx, p.OrgID, project, env.ID) - if e != nil && in.TargetID == "" { - if retained, ok := st.(interface { - RetainedAssignment(context.Context, string, string, string) (*cloudprofiles.Assignment, error) - }); ok { - assignment, e = retained.RetainedAssignment(ctx, p.OrgID, project, env.ID) + // assignment is the Cloud the change is about, as this project sees + // it: the changed Cloud for a shared change, the current default for + // a project default change. + assignment := preview.BeforeCloud + if in.Shared() { + var e error + assignment, e = st.ResolveCloud(ctx, p.OrgID, project, in.CloudID) + if e != nil && in.TargetID == "" { + // A project whose grant was revoked still runs what it placed. + if retained, ok := st.(interface { + RetainedCloud(context.Context, string, string, string) (*cloudprofiles.ProjectCloud, error) + }); ok { + assignment, e = retained.RetainedCloud(ctx, p.OrgID, project, in.CloudID) + } + } + if e != nil { + return nil, e } } - if e != nil { - return nil, e - } - if in.Shared() && (assignment == nil || assignment.CloudID != in.CloudID) { - continue - } - if in.EnvironmentID != "" && env.ID != in.EnvironmentID { + if in.Shared() && assignment == nil { continue } - found = true if guardErr := s.requireUnmanagedEnvironmentID(ctx, p.OrgID, project, env.ID); guardErr != nil { if errors.Is(guardErr, projects.ErrFleetManaged) { preview.Blockers = append(preview.Blockers, "Manage instance placement through its fleet.") @@ -218,7 +237,7 @@ func (s *Service) previewCloudChange(ctx context.Context, p security.Principal, } return nil, guardErr } - generation, e := st.AssignmentGeneration(ctx, p.OrgID, project, env.ID) + defaultCloud, _, e := st.DefaultCloud(ctx, p.OrgID, project) if e != nil { return nil, e } @@ -243,13 +262,9 @@ func (s *Service) previewCloudChange(ctx context.Context, p security.Principal, copyAssignment.DefaultPlacement = &proposed } after = ©Assignment - default: - if generation != in.Revision { - return nil, cloudprofiles.ErrConflict - } - preview.BeforeAssignment, preview.AfterAssignment = assignment, after } - if after != nil { + // A project default change pinned its grants above, once. + if after != nil && !in.ProjectDefault { if grants, ok := st.(cloudprofiles.GrantStore); ok { g, grantErr := grants.GetProjectGrant(ctx, p.OrgID, after.CloudID, project) if grantErr != nil { @@ -275,7 +290,7 @@ func (s *Service) previewCloudChange(ctx context.Context, p security.Principal, snapshot.Grants = append(snapshot.Grants, *g) } } - for _, pin := range []*cloudprofiles.Assignment{assignment, after} { + for _, pin := range []*cloudprofiles.ProjectCloud{assignment, after} { if pin == nil { continue } @@ -394,7 +409,12 @@ func (s *Service) previewCloudChange(ctx context.Context, p security.Principal, if in.Default { selector = defaultPlacementSelector } - result := appliedCloudPlanWithIntents(planningBindings, after, selector, options, s.providers, poolPlacements, intents, routes) + choose := func(*CloudPlacement) (*cloudprofiles.ProjectCloud, bool) { return after, true } + if in.ProjectDefault { + // A service that names its Cloud doesn't follow the default. + choose = func(pin *CloudPlacement) (*cloudprofiles.ProjectCloud, bool) { return after, !pin.Named } + } + result := appliedCloudPlanChoosing(planningBindings, choose, selector, options, s.providers, poolPlacements, intents, routes) locationReviews := []*cloudprofiles.LocationReview{} priorLocations := map[string]locationSelection{} for i := range result.Actions { @@ -538,12 +558,9 @@ func (s *Service) previewCloudChange(ctx context.Context, p security.Principal, if string(routeSnapshot) == "null" { routeSnapshot = []byte("[]") } - snapshot.Environments = append(snapshot.Environments, cloudprofiles.EnvironmentSnapshot{LocationReviews: locationReviews, Routes: routeSnapshot, ProjectID: project, EnvironmentID: env.ID, AssignmentRevision: generation, Bindings: raw, Plan: encoded}) + snapshot.Environments = append(snapshot.Environments, cloudprofiles.EnvironmentSnapshot{LocationReviews: locationReviews, Routes: routeSnapshot, ProjectID: project, EnvironmentID: env.ID, DefaultCloud: defaultCloud, Bindings: raw, Plan: encoded}) preview.Environments = append(preview.Environments, change) } - if !found { - return nil, cloudprofiles.ErrNotFound - } snapshot.ConnectionIdentities = map[string]string{} for _, id := range snapshot.Connections { for _, option := range options { @@ -956,14 +973,15 @@ func (s *Service) CloudPreview(ctx context.Context, p security.Principal, projec return preview, err } -// Assignment references survive revocation for removal and compensation. Target -// configuration is visible only through the current grant; retained full state -// stays in the private comparison snapshot and cleanup resolver. +// The default Cloud either side of a change survives revocation for removal +// and compensation. Target configuration is visible only through the +// current grant; retained full state stays in the private comparison +// snapshot and cleanup resolver. func (s *Service) filterCloudPreviewAssignments(ctx context.Context, p security.Principal, preview *cloudprofiles.Preview) error { if s.authz.Require(ctx, p, security.OrganizationCloudManage, p.OrgID) == nil { return nil } - for _, field := range []**cloudprofiles.Assignment{&preview.BeforeAssignment, &preview.AfterAssignment} { + for _, field := range []**cloudprofiles.ProjectCloud{&preview.BeforeCloud, &preview.AfterCloud} { if *field == nil { continue } diff --git a/internal/planning/cloud_sync_plan.go b/internal/planning/cloud_sync_plan.go index 67c991683..8d3e10170 100644 --- a/internal/planning/cloud_sync_plan.go +++ b/internal/planning/cloud_sync_plan.go @@ -15,15 +15,26 @@ import ( // AppliedCloudPlan constructs migration actions from serving bindings only. // It never reads a current analysis, manifest, branch or environment variable. -func AppliedCloudPlan(bindings []*Binding, assignment *cloudprofiles.Assignment, targetID string, options []ConnectionOption, registry *provider.Registry, _ ...*cloudprofiles.Assignment) *Result { +func AppliedCloudPlan(bindings []*Binding, assignment *cloudprofiles.ProjectCloud, targetID string, options []ConnectionOption, registry *provider.Registry, _ ...*cloudprofiles.ProjectCloud) *Result { return appliedCloudPlan(bindings, assignment, targetID, options, registry, nil) } -func appliedCloudPlan(bindings []*Binding, assignment *cloudprofiles.Assignment, targetID string, options []ConnectionOption, registry *provider.Registry, pools map[string]CloudPlacement, routes ...[]cloudinfra.Route) *Result { +func appliedCloudPlan(bindings []*Binding, assignment *cloudprofiles.ProjectCloud, targetID string, options []ConnectionOption, registry *provider.Registry, pools map[string]CloudPlacement, routes ...[]cloudinfra.Route) *Result { return appliedCloudPlanWithIntents(bindings, assignment, targetID, options, registry, pools, nil, routes...) } -func appliedCloudPlanWithIntents(bindings []*Binding, assignment *cloudprofiles.Assignment, targetID string, options []ConnectionOption, registry *provider.Registry, pools map[string]CloudPlacement, intents map[string]*CapacityIntent, routes ...[]cloudinfra.Route) *Result { +// cloudChooser picks, for one applied pin, the Cloud it moves to, and +// whether it moves at all: a pin that doesn't is kept as it runs. +type cloudChooser func(pin *CloudPlacement) (cloud *cloudprofiles.ProjectCloud, moves bool) + +func appliedCloudPlanWithIntents(bindings []*Binding, assignment *cloudprofiles.ProjectCloud, targetID string, options []ConnectionOption, registry *provider.Registry, pools map[string]CloudPlacement, intents map[string]*CapacityIntent, routes ...[]cloudinfra.Route) *Result { + every := func(*CloudPlacement) (*cloudprofiles.ProjectCloud, bool) { return assignment, true } + return appliedCloudPlanChoosing(bindings, every, targetID, options, registry, pools, intents, routes...) +} + +// appliedCloudPlanChoosing moves each selected applied service to the Cloud +// choose names for its pin. +func appliedCloudPlanChoosing(bindings []*Binding, choose cloudChooser, targetID string, options []ConnectionOption, registry *provider.Registry, pools map[string]CloudPlacement, intents map[string]*CapacityIntent, routes ...[]cloudinfra.Route) *Result { p := &planner{in: Input{Providers: registry, Connections: options, CloudPlacements: map[string]CloudPlacement{}, Chosen: map[string]string{}}, services: map[string]*Action{}, resources: map[string]*Action{}, bindings: map[string]*Binding{}, clouds: map[string]bool{}, unready: map[string]string{}, held: map[string]string{}, removing: map[string]bool{}} if len(routes) > 0 { p.in.Routes = routes[0] @@ -51,8 +62,12 @@ func appliedCloudPlanWithIntents(bindings []*Binding, assignment *cloudprofiles. if pin == nil || !selectsPlacement(targetID, pin) { continue } + assignment, moves := choose(pin) + if !moves { + continue + } if assignment == nil { - blocked(b.Name, "This deployed service needs a named Cloud target; remove or adopt its reference before unassigning the Cloud.") + blocked(b.Name, "This deployed service needs a named Cloud target; remove or adopt its reference before the project leaves this Cloud.") continue } var t cloudprofiles.Target @@ -262,12 +277,16 @@ func appliedCloudPlanWithIntents(bindings []*Binding, assignment *cloudprofiles. // but deploys against the reviewed Cloud: a default switch advances the // Cloud revision its old pin recorded. for _, a := range p.actions { - if a.Op == Keep || a.Service == nil || a.Service.CloudPlacement == nil || assignment == nil { + if a.Op == Keep || a.Service == nil || a.Service.CloudPlacement == nil { continue } if _, moved := p.in.CloudPlacements[a.Name]; moved { continue } + assignment, _ := choose(a.Service.CloudPlacement) + if assignment == nil { + continue + } // A pin that no longer matches is left for the deploy-time check to refuse. if pin, ok := repinCloudPlacement(*a.Service.CloudPlacement, assignment); ok { a.Service.CloudPlacement = &pin @@ -359,7 +378,7 @@ func migrationPlanID(syncID, environmentID string) string { // repinCloudPlacement carries an unchanged placement onto a reviewed // assignment. It reports false when the default or target no longer matches. -func repinCloudPlacement(pin CloudPlacement, assignment *cloudprofiles.Assignment) (CloudPlacement, bool) { +func repinCloudPlacement(pin CloudPlacement, assignment *cloudprofiles.ProjectCloud) (CloudPlacement, bool) { if pin.CloudID != assignment.CloudID { return pin, false } @@ -379,7 +398,7 @@ func repinCloudPlacement(pin CloudPlacement, assignment *cloudprofiles.Assignmen } pin.TargetRevision, pin.TargetName = t.Revision, t.Name } - pin.CloudRevision, pin.AssignmentRevision, pin.GrantRevision = assignment.CloudRevision, assignment.Revision, assignment.GrantRevision + pin.CloudRevision, pin.GrantRevision = assignment.CloudRevision, assignment.GrantRevision return pin, true } diff --git a/internal/planning/cloud_sync_plan_test.go b/internal/planning/cloud_sync_plan_test.go index acc8402ea..46ba91e16 100644 --- a/internal/planning/cloud_sync_plan_test.go +++ b/internal/planning/cloud_sync_plan_test.go @@ -15,7 +15,7 @@ import ( func appliedTestBinding(t *testing.T, name, commit string) *Binding { t.Helper() cfg := ServiceConfig{Provider: "vercel", Repo: "app", CommitSHA: commit, Service: name, Workload: provider.WebApp, Execution: provider.Serverless, Public: true, - CloudPlacement: &CloudPlacement{CloudID: "cloud", CloudRevision: 1, AssignmentRevision: 1, TargetID: "target", TargetRevision: 1, TargetName: "frontend", Provider: "vercel", ConnectionID: "old", AccountIdentity: "vercel:old"}, + CloudPlacement: &CloudPlacement{CloudID: "cloud", CloudRevision: 1, TargetID: "target", TargetRevision: 1, TargetName: "frontend", Provider: "vercel", ConnectionID: "old", AccountIdentity: "vercel:old"}, AppliedInputs: &AppliedInputs{Variables: "org/env/applied-inputs/dep/" + name, Source: &PlanSource{SourceID: "src", Alias: "app", Repository: "owner/app", CommitSHA: commit}, ArtifactKey: "sources/org/project/app/" + commit + ".tar.gz"}} raw, err := json.Marshal(cfg) if err != nil { @@ -23,8 +23,8 @@ func appliedTestBinding(t *testing.T, name, commit string) *Binding { } return &Binding{ID: "bind_" + name, OrgID: "org", ProjectID: "project", EnvironmentID: "env", Name: name, Subject: ServiceSubject, Provider: "vercel", ConnectionID: "old", CommitSHA: commit, Config: raw, ExternalID: "ext_" + name, PlanID: "plan_" + name} } -func appliedAssignment(connection string) *cloudprofiles.Assignment { - return &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 1, Revision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", ProjectID: "project", CloudID: "cloud", Name: "frontend", Provider: "vercel", ConnectionID: connection, Revision: 2}}} +func appliedAssignment(connection string) *cloudprofiles.ProjectCloud { + return &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", ProjectID: "project", CloudID: "cloud", Name: "frontend", Provider: "vercel", ConnectionID: connection, Revision: 2}}} } func TestAppliedCloudPlanMixedSourceAndDependents(t *testing.T) { registry := providers.Registry() diff --git a/internal/planning/cloud_sync_revert.go b/internal/planning/cloud_sync_revert.go index 789a6daf5..01cf4e3db 100644 --- a/internal/planning/cloud_sync_revert.go +++ b/internal/planning/cloud_sync_revert.go @@ -238,18 +238,17 @@ func revertChangeInput(ctx context.Context, st cloudprofiles.SyncStore, p securi } in = cloudprofiles.ChangeInput{CloudID: sync.CloudID, TargetID: sync.TargetID, Revision: current.Revision, Provider: sync.Before.Provider, ConnectionID: sync.Before.ConnectionID, Region: sync.Before.Region, Runtime: sync.Before.Runtime, PoolID: sync.Before.PoolID} default: - env := previous.Input.EnvironmentID - generation, e := st.AssignmentGeneration(ctx, p.OrgID, project, env) + // Undo a project default change while the default it set still stands. + current, revision, e := st.DefaultCloud(ctx, p.OrgID, project) if e != nil { return in, e } - if generation != previous.Input.Revision+1 { + if current != previous.Input.CloudID { return in, cloudprofiles.ErrConflict } - in.EnvironmentID = env - in.Revision = generation - if previous.BeforeAssignment != nil { - in.CloudID = previous.BeforeAssignment.CloudID + in = cloudprofiles.ChangeInput{ProjectDefault: true, Revision: revision} + if previous.BeforeCloud != nil { + in.CloudID = previous.BeforeCloud.CloudID } } return in, nil diff --git a/internal/planning/cloud_sync_revert_test.go b/internal/planning/cloud_sync_revert_test.go index 2d6f53ea5..97d078482 100644 --- a/internal/planning/cloud_sync_revert_test.go +++ b/internal/planning/cloud_sync_revert_test.go @@ -105,15 +105,15 @@ func TestCloudCompensationMixedRuntimeAlwaysReviewsRecreation(t *testing.T) { } } -// A revert onto the Loomplane Cloud an environment left is the same -// environment move back. A target change on a Loomplane Cloud target never +// A revert onto the Loomplane Cloud a project left is the same default +// change back. A target change on a Loomplane Cloud target never // happened, so it has nothing to revert, and says so in its own branch. func TestCloudRevertPlatformTarget(t *testing.T) { - st := &platformSyncStore{} + st := &platformSyncStore{defaultCloud: "cloud_user"} p := security.Principal{OrgID: "org", UserID: "user"} - moved := &cloudprofiles.Preview{Input: cloudprofiles.ChangeInput{CloudID: "cloud_user", EnvironmentID: "env"}, BeforeAssignment: &cloudprofiles.Assignment{CloudID: "cloud_platform"}} + moved := &cloudprofiles.Preview{Input: cloudprofiles.ChangeInput{CloudID: "cloud_user", ProjectDefault: true}, BeforeCloud: &cloudprofiles.ProjectCloud{CloudID: "cloud_platform"}} in, err := revertChangeInput(t.Context(), st, p, "proj", &cloudprofiles.Sync{}, moved) - if err != nil || in.CloudID != "cloud_platform" || in.EnvironmentID != "env" || in.Revision != 1 { + if err != nil || in.CloudID != "cloud_platform" || !in.ProjectDefault || in.Revision != 1 { t.Fatalf("revert onto Loomplane Cloud: %+v %v", in, err) } before, after := *platformTarget, *platformTarget diff --git a/internal/planning/cloud_sync_routes.go b/internal/planning/cloud_sync_routes.go index 8c4af64a7..e3dc9e09c 100644 --- a/internal/planning/cloud_sync_routes.go +++ b/internal/planning/cloud_sync_routes.go @@ -56,7 +56,7 @@ func changedSyncTarget(before cloudprofiles.Target, in cloudprofiles.ChangeInput return after, nil } -func (s *Service) syncPoolPlacements(ctx context.Context, plan *Plan, bindings []*Binding, assignment *cloudprofiles.Assignment, before *cloudprofiles.Target, options []ConnectionOption, prior []cloudinfra.PlannedPlacement, future ...map[string]*CapacityIntent) (map[string]CloudPlacement, error) { +func (s *Service) syncPoolPlacements(ctx context.Context, plan *Plan, bindings []*Binding, assignment *cloudprofiles.ProjectCloud, before *cloudprofiles.Target, options []ConnectionOption, prior []cloudinfra.PlannedPlacement, future ...map[string]*CapacityIntent) (map[string]CloudPlacement, error) { result := map[string]CloudPlacement{} if assignment == nil { return result, nil @@ -117,7 +117,7 @@ func (s *Service) syncPoolPlacements(ctx context.Context, plan *Plan, bindings [ return nil, errors.New("selected pool connection is unavailable") } connection := options[ci] - result[b.Name] = CloudPlacement{LocationID: target.LocationID, ManagedResourceID: target.ManagedResourceID, Allocation: placed.Allocation, CloudID: assignment.CloudID, CloudRevision: assignment.CloudRevision, AssignmentRevision: assignment.Revision, GrantRevision: assignment.GrantRevision, TargetID: target.ID, TargetRevision: target.Revision, TargetName: target.Name, Provider: "server", ConnectionID: placed.ConnectionID, AccountIdentity: connections.AccountIdentity(connection.Cloud, connection.Account, connection.Details), RegionSource: old.CloudPlacement.RegionSource, PoolID: placed.PoolID, PoolRevision: placed.PoolRevision, ServerID: placed.ServerID, ServerRevision: placed.ServerRevision, ConnectionGeneration: placed.ConnectionGeneration, CPUMillis: placed.CPUMillis, MemoryBytes: placed.MemoryBytes, GPUKind: placed.GPUKind, GPUs: placed.GPUs} + result[b.Name] = CloudPlacement{LocationID: target.LocationID, ManagedResourceID: target.ManagedResourceID, Allocation: placed.Allocation, CloudID: assignment.CloudID, CloudRevision: assignment.CloudRevision, GrantRevision: assignment.GrantRevision, TargetID: target.ID, TargetRevision: target.Revision, TargetName: target.Name, Provider: "server", ConnectionID: placed.ConnectionID, AccountIdentity: connections.AccountIdentity(connection.Cloud, connection.Account, connection.Details), RegionSource: old.CloudPlacement.RegionSource, PoolID: placed.PoolID, PoolRevision: placed.PoolRevision, ServerID: placed.ServerID, ServerRevision: placed.ServerRevision, ConnectionGeneration: placed.ConnectionGeneration, CPUMillis: placed.CPUMillis, MemoryBytes: placed.MemoryBytes, GPUKind: placed.GPUKind, GPUs: placed.GPUs} planned = append(planned, cloudinfra.PlannedPlacement{OrgID: plan.OrgID, ProjectID: plan.ProjectID, EnvironmentID: plan.EnvironmentID, Service: b.Name, Placement: *placed}) } return result, nil diff --git a/internal/planning/cloud_tags_test.go b/internal/planning/cloud_tags_test.go index e88740f70..c4a18696c 100644 --- a/internal/planning/cloud_tags_test.go +++ b/internal/planning/cloud_tags_test.go @@ -11,7 +11,7 @@ import ( ) // taggedFixture has two Vercel targets: frontend (web, eu) and preview (web, us). -func taggedFixture() (*cloudprofiles.Assignment, []ConnectionOption) { +func taggedFixture() (*cloudprofiles.ProjectCloud, []ConnectionOption) { a, c := cloudTargetFixture() a.Targets[0].Tags = []string{"eu", "web"} a.Targets[1].Tags = []string{"us", "web"} @@ -117,7 +117,7 @@ func TestCloudTagsSkipHeldServices(t *testing.T) { } } -func cloudDefaultFixture() (*cloudprofiles.Assignment, []ConnectionOption) { +func cloudDefaultFixture() (*cloudprofiles.ProjectCloud, []ConnectionOption) { a, c := cloudTargetFixture() a.Targets = nil a.DefaultPlacement = &cloudprofiles.DefaultPlacement{Provider: "vercel", ConnectionID: "b", Region: "iad1"} @@ -204,7 +204,7 @@ func TestAppliedCloudPlanMovesDefaultPlacedServicesToTheNewDefault(t *testing.T) b := appliedTestBinding(t, "web", "commit") var cfg ServiceConfig _ = json.Unmarshal(b.Config, &cfg) - cfg.CloudPlacement = &CloudPlacement{Default: true, CloudID: "cloud", CloudRevision: 1, AssignmentRevision: 1, Provider: "vercel", ConnectionID: "old", AccountIdentity: "vercel:old"} + cfg.CloudPlacement = &CloudPlacement{Default: true, CloudID: "cloud", CloudRevision: 1, Provider: "vercel", ConnectionID: "old", AccountIdentity: "vercel:old"} b.Config, _ = json.Marshal(cfg) options := []ConnectionOption{{ID: "new", Cloud: "vercel", Ready: true, Account: "new", Details: map[string]string{"team_id": "new"}}} diff --git a/internal/planning/cloud_targets.go b/internal/planning/cloud_targets.go index 7a07f73f0..d83b7bb4d 100644 --- a/internal/planning/cloud_targets.go +++ b/internal/planning/cloud_targets.go @@ -33,15 +33,23 @@ type CloudPlacement struct { MemoryBytes int64 `json:"memory_bytes,omitempty"` // GPUKind and GPUs are what a pool reserves for a service that asks // for GPUs. A CPU pin leaves them out, so its stored shape is unchanged. - GPUKind string `json:"gpu_kind,omitempty"` - GPUs int64 `json:"gpus,omitempty"` - GrantRevision int64 `json:"grant_revision,omitempty"` - CloudID string `json:"cloud_id"` - CloudRevision int64 `json:"cloud_revision"` - AssignmentRevision int64 `json:"assignment_revision"` + GPUKind string `json:"gpu_kind,omitempty"` + GPUs int64 `json:"gpus,omitempty"` + GrantRevision int64 `json:"grant_revision,omitempty"` + CloudID string `json:"cloud_id"` + CloudRevision int64 `json:"cloud_revision"` + // AssignmentRevision pinned the environment's Cloud assignment before + // Clouds became per project. Nothing checks it now and new placements + // leave it zero; it stays so stored plans keep the digest they were + // approved under. + AssignmentRevision int64 `json:"assignment_revision"` // Default marks a service placed by the Cloud's default rather than a // target. It has no target ID, name or revision; the Cloud revision pins it. - Default bool `json:"default,omitempty"` + Default bool `json:"default,omitempty"` + // Named marks a service whose manifest names its Cloud with cloud, + // rather than reaching it as the project's default. Changing the + // project's default leaves it where it is. + Named bool `json:"named,omitempty"` TargetID string `json:"target_id"` TargetRevision int64 `json:"target_revision"` TargetName string `json:"target_name"` @@ -71,8 +79,8 @@ func (e *CloudPlacementError) Error() string { return e.Path + ": " + e.Message // reached through the target's own connection c. A direct target records // the Cloud server c runs, when it runs exactly one; a pool target's // server is its capacity resolution's to choose. -func targetPlacement(a *cloudprofiles.Assignment, t cloudprofiles.Target, c ConnectionOption, identity, region, regionSource string) CloudPlacement { - p := CloudPlacement{LocationID: t.LocationID, ManagedResourceID: t.ManagedResourceID, GrantRevision: a.GrantRevision, CloudID: a.CloudID, CloudRevision: a.CloudRevision, AssignmentRevision: a.Revision, TargetID: t.ID, TargetRevision: t.Revision, TargetName: t.Name, Provider: t.Provider, ConnectionID: t.ConnectionID, AccountIdentity: identity, Region: region, RegionSource: regionSource} +func targetPlacement(a *cloudprofiles.ProjectCloud, t cloudprofiles.Target, c ConnectionOption, identity, region, regionSource string) CloudPlacement { + p := CloudPlacement{LocationID: t.LocationID, ManagedResourceID: t.ManagedResourceID, GrantRevision: a.GrantRevision, CloudID: a.CloudID, CloudRevision: a.CloudRevision, TargetID: t.ID, TargetRevision: t.Revision, TargetName: t.Name, Provider: t.Provider, ConnectionID: t.ConnectionID, AccountIdentity: identity, Region: region, RegionSource: regionSource} if servers := c.cloudServers(a.CloudID); t.PoolID == "" && len(servers) == 1 { p.ServerID = servers[0] } @@ -142,9 +150,9 @@ func composedResources(m *manifest.Manifest, environment string, kinds *recipes. // that target is placed. Pool targets aren't matched. A placement pins // reviewed revisions and a verified account, as the runner checks it // before it records one; without them the resource isn't placed. -func composedPlacements(m *manifest.Manifest, environment string, names []string, assignment *cloudprofiles.Assignment, options []ConnectionOption) map[string]CloudPlacement { +func composedPlacements(m *manifest.Manifest, environment string, names []string, assignment *cloudprofiles.ProjectCloud, options []ConnectionOption) map[string]CloudPlacement { out := map[string]CloudPlacement{} - if assignment == nil || assignment.CloudRevision < 1 || assignment.Revision < 1 { + if assignment == nil || assignment.CloudRevision < 1 { return out } for _, name := range names { @@ -198,7 +206,7 @@ func composedPlacements(m *manifest.Manifest, environment string, names []string // still doesn't place: the Cloud's or the target's revision isn't // reviewed, or the target's connection is missing or has no verified // account. -func unverifiedPlacements(m *manifest.Manifest, environment string, names []string, assignment *cloudprofiles.Assignment, options []ConnectionOption) map[string]bool { +func unverifiedPlacements(m *manifest.Manifest, environment string, names []string, assignment *cloudprofiles.ProjectCloud, options []ConnectionOption) map[string]bool { out := map[string]bool{} if assignment == nil { return out @@ -221,14 +229,14 @@ func unverifiedPlacements(m *manifest.Manifest, environment string, names []stri // SelectCloudTarget returns the target a service's settings name or tag, or // nil when they select none. Tags match the targets the project's grant // allows; a service gets a target only when exactly one carries every tag. -func SelectCloudTarget(set manifest.Settings, assignment *cloudprofiles.Assignment, path string) (*cloudprofiles.Target, error) { +func SelectCloudTarget(set manifest.Settings, assignment *cloudprofiles.ProjectCloud, path string) (*cloudprofiles.Target, error) { if assignment == nil || set.CloudTarget == "" && len(set.CloudTags) == 0 { return nil, nil } if set.CloudTarget != "" { i := slices.IndexFunc(assignment.Targets, func(t cloudprofiles.Target) bool { return t.Name == set.CloudTarget }) if i < 0 { - return nil, fmt.Errorf("%s: target %q is missing from the assigned Cloud; choose an existing target", path, set.CloudTarget) + return nil, fmt.Errorf("%s: target %q isn't in %s; choose one of its targets, or name another Cloud with cloud", path, set.CloudTarget, cloudName(set, assignment)) } return &assignment.Targets[i], nil } @@ -243,7 +251,7 @@ func SelectCloudTarget(set manifest.Settings, assignment *cloudprofiles.Assignme case 1: return &assignment.Targets[matches[0]], nil case 0: - return nil, &CloudPlacementError{Code: "cloud-tag-unmatched", Path: path, Message: fmt.Sprintf("no target this project may use in the assigned Cloud carries %s. Tag a target, or ask an organization admin to grant this project one that does.", tags)} + return nil, &CloudPlacementError{Code: "cloud-tag-unmatched", Path: path, Message: fmt.Sprintf("no target this project may use in %s carries %s. Tag a target, or ask an organization admin to grant this project one that does.", cloudName(set, assignment), tags)} } names := make([]string, 0, len(matches)) for _, i := range matches { @@ -264,7 +272,7 @@ func carriesTags(have, want []string) bool { // usesCloudDefault reports whether a service with no placement of its own // goes to the assigned Cloud's default provider and account. Targets never // change this: adding one only places services that name or tag it. -func usesCloudDefault(set manifest.Settings, assignment *cloudprofiles.Assignment) bool { +func usesCloudDefault(set manifest.Settings, assignment *cloudprofiles.ProjectCloud) bool { return assignment != nil && assignment.DefaultPlacement != nil && set.CloudTarget == "" && len(set.CloudTags) == 0 && set.Provider == "" && set.Target == "" } @@ -274,13 +282,26 @@ func cloudPath(name string, set manifest.Settings) string { return "services." + name + ".cloud_target" case len(set.CloudTags) > 0: return "services." + name + ".cloud_tags" + case set.Cloud != "": + return "services." + name + ".cloud" } return "services." + name + ".provider" } +// cloudName says which Cloud a service's target was looked up in. +func cloudName(set manifest.Settings, c *cloudprofiles.ProjectCloud) string { + switch { + case set.Cloud != "": + return "Cloud " + set.Cloud + case c != nil && c.Name != "": + return "the default Cloud, " + c.Name + } + return "the project's default Cloud" +} + // ResolveCloudTargets returns an independent manifest with effective placement. // The caller checks the assignment's organization, project and environment. -func ResolveCloudTargets(m *manifest.Manifest, environment string, assignment *cloudprofiles.Assignment, options []ConnectionOption, pools ...map[string]*cloudinfra.Placement) (*manifest.Manifest, map[string]CloudPlacement, error) { +func ResolveCloudTargets(m *manifest.Manifest, environment string, assignment *cloudprofiles.ProjectCloud, options []ConnectionOption, pools ...map[string]*cloudinfra.Placement) (*manifest.Manifest, map[string]CloudPlacement, error) { var resolved map[string]*cloudinfra.Placement if len(pools) > 0 { resolved = pools[0] @@ -288,8 +309,22 @@ func ResolveCloudTargets(m *manifest.Manifest, environment string, assignment *c return resolveCloudPlacements(m, environment, assignment, options, resolved, nil, nil) } -// resolveCloudPlacements leaves held services exactly as their manifest says. -func resolveCloudPlacements(m *manifest.Manifest, environment string, assignment *cloudprofiles.Assignment, options []ConnectionOption, pools map[string]*cloudinfra.Placement, platform map[string]*platformcloud.Ref, held map[string]bool, future ...map[string]*CapacityIntent) (*manifest.Manifest, map[string]CloudPlacement, error) { +// cloudPass says what one Cloud's resolution pass covers. The default +// Cloud's pass also places the database gateway; a named Cloud's pass marks +// its placements as named. +type cloudPass struct { + gateway bool + named bool +} + +// resolveCloudPlacements resolves every service through one Cloud, the +// project's default, as a single pass. +func resolveCloudPlacements(m *manifest.Manifest, environment string, assignment *cloudprofiles.ProjectCloud, options []ConnectionOption, pools map[string]*cloudinfra.Placement, platform map[string]*platformcloud.Ref, held map[string]bool, future ...map[string]*CapacityIntent) (*manifest.Manifest, map[string]CloudPlacement, error) { + return resolveCloudPass(m, environment, assignment, options, pools, platform, held, cloudPass{gateway: true}, future...) +} + +// resolveCloudPass leaves held services exactly as their manifest says. +func resolveCloudPass(m *manifest.Manifest, environment string, assignment *cloudprofiles.ProjectCloud, options []ConnectionOption, pools map[string]*cloudinfra.Placement, platform map[string]*platformcloud.Ref, held map[string]bool, pass cloudPass, future ...map[string]*CapacityIntent) (*manifest.Manifest, map[string]CloudPlacement, error) { raw, err := json.Marshal(m) if err != nil { return nil, nil, err @@ -310,6 +345,9 @@ func resolveCloudPlacements(m *manifest.Manifest, environment string, assignment } fallback := usesCloudDefault(set, assignment) if set.CloudTarget == "" && len(set.CloudTags) == 0 && !fallback { + if pass.named { + return nil, nil, &CloudPlacementError{Code: "cloud-default-missing", Path: "services." + name + ".cloud", Message: fmt.Sprintf("Cloud %s has no default placement this project may use. Name one of its targets with cloud_target.", set.Cloud)} + } continue } path := cloudPath(name, set) @@ -326,12 +364,15 @@ func resolveCloudPlacements(m *manifest.Manifest, environment string, assignment if placeErr != nil { return nil, nil, placeErr } + placement.Named = pass.named placements[name] = placement s.Settings, s.Environments = resolvedSet, nil out.Services[name] = s } - if err := resolveDatabaseGatewayPlacement(&out, environment, assignment, options, pools, placements); err != nil { - return nil, nil, err + if pass.gateway { + if err := resolveDatabaseGatewayPlacement(&out, environment, assignment, options, pools, placements); err != nil { + return nil, nil, err + } } // Every service the default tags applied to is resolved above. out.Defaults.CloudTags = nil @@ -348,15 +389,15 @@ var errCapacityDeferred = errors.New("pool capacity deferred to a later plan") // is set and the target is a pool, it returns errCapacityDeferred with the // settings carrying only the target's provider. A Loomplane Cloud target // takes the room platform previewed for the service, and no connection. -func resolveCloudPlacement(name, path string, set manifest.Settings, fallback bool, assignment *cloudprofiles.Assignment, options []ConnectionOption, pools map[string]*cloudinfra.Placement, platform map[string]*platformcloud.Ref, deferred bool) (CloudPlacement, manifest.Settings, error) { +func resolveCloudPlacement(name, path string, set manifest.Settings, fallback bool, assignment *cloudprofiles.ProjectCloud, options []ConnectionOption, pools map[string]*cloudinfra.Placement, platform map[string]*platformcloud.Ref, deferred bool) (CloudPlacement, manifest.Settings, error) { if assignment == nil { - return CloudPlacement{}, set, fmt.Errorf("%s needs a Cloud assigned to this environment", path) + return CloudPlacement{}, set, &CloudPlacementError{Code: "cloud-none", Path: path, Message: "this project has no default Cloud. Grant it a Cloud under Clouds; its first Cloud becomes its default."} } - if assignment.CloudRevision < 1 || assignment.Revision < 1 { - return CloudPlacement{}, set, fmt.Errorf("%s has no reviewed Cloud or assignment revision", path) + if assignment.CloudRevision < 1 || assignment.GrantRevision < 1 { + return CloudPlacement{}, set, fmt.Errorf("%s has no reviewed Cloud or grant revision", path) } - if assignment.OrgID == "" || assignment.ProjectID == "" || assignment.EnvironmentID == "" || assignment.CloudID == "" { - return CloudPlacement{}, set, fmt.Errorf("%s has an invalid assignment scope", path) + if assignment.OrgID == "" || assignment.ProjectID == "" || assignment.CloudID == "" { + return CloudPlacement{}, set, fmt.Errorf("%s has an invalid Cloud scope", path) } var target cloudprofiles.Target if fallback { @@ -385,7 +426,7 @@ func resolveCloudPlacement(name, path string, set manifest.Settings, fallback bo var pool *cloudinfra.Placement if target.PoolID != "" { if deferred { - set.Provider, set.CloudTarget, set.CloudTags, set.Target = target.Provider, "", nil, "" + set.Provider, set.Cloud, set.CloudTarget, set.CloudTags, set.Target = target.Provider, "", "", nil, "" return CloudPlacement{}, set, errCapacityDeferred } if pools[name] == nil { @@ -430,7 +471,7 @@ func resolveCloudPlacement(name, path string, set manifest.Settings, fallback bo placement.MemoryBytes = pool.MemoryBytes placement.GPUKind, placement.GPUs = pool.GPUKind, pool.GPUs } - set.CloudTarget, set.CloudTags = "", nil + set.Cloud, set.CloudTarget, set.CloudTags = "", "", nil return placement, set, nil } @@ -511,11 +552,14 @@ type cloudNeeds struct { Explicit bool Fallback bool Held map[string]bool + // Named maps each Cloud a service names to the services naming it, in + // manifest order. Explicit and Fallback are about the default Cloud. + Named map[string][]string } // cloudResolutionManifest excludes held services from desired placement lookup. func cloudResolutionManifest(m *manifest.Manifest, in Input) (*manifest.Manifest, cloudNeeds, error) { - needs := cloudNeeds{Held: map[string]bool{}} + needs := cloudNeeds{Held: map[string]bool{}, Named: map[string][]string{}} raw, err := json.Marshal(m) if err != nil { return nil, needs, err @@ -541,9 +585,9 @@ func cloudResolutionManifest(m *manifest.Manifest, in Input) (*manifest.Manifest // A service the plan doesn't name stays as it runs, or isn't // created, so its Cloud target is settled no more than a held one's. if held || in.Held[repo] || (len(in.Only) > 0 && !in.Only[name]) { - s.CloudTarget, s.CloudTags = "", nil + s.Cloud, s.CloudTarget, s.CloudTags = "", "", nil for env, override := range s.Environments { - override.CloudTarget, override.CloudTags = "", nil + override.Cloud, override.CloudTarget, override.CloudTags = "", "", nil s.Environments[env] = override } out.Services[name] = s @@ -554,6 +598,10 @@ func cloudResolutionManifest(m *manifest.Manifest, in Input) (*manifest.Manifest if !manifest.On(set.Enabled) { continue } + if set.Cloud != "" { + needs.Named[set.Cloud] = append(needs.Named[set.Cloud], name) + continue + } needs.Explicit = needs.Explicit || set.Placement != nil || set.CloudTarget != "" || len(set.CloudTags) > 0 needs.Fallback = needs.Fallback || set.CloudTarget == "" && len(set.CloudTags) == 0 && set.Provider == "" && set.Target == "" } @@ -606,15 +654,15 @@ func (s *PgStore) PreviewPlacement(ctx context.Context, in cloudinfra.PlacementR func (s *PgStore) ValidatePlacement(ctx context.Context, org, project, env, plan, service string, p cloudinfra.Placement) error { return cloudinfra.NewPgStore(s.db).ValidatePlacement(ctx, org, project, env, plan, service, p) } -func (s *Service) resolvePools(ctx context.Context, plan *Plan, m *manifest.Manifest, a *cloudprofiles.Assignment, bindings []*Binding, options []ConnectionOption, held map[string]bool, future ...map[string]*CapacityIntent) (map[string]*cloudinfra.Placement, error) { +func (s *Service) resolvePools(ctx context.Context, plan *Plan, m *manifest.Manifest, a *cloudprofiles.ProjectCloud, bindings []*Binding, options []ConnectionOption, held map[string]bool, future ...map[string]*CapacityIntent) (map[string]*cloudinfra.Placement, error) { return s.resolvePoolsReviewed(ctx, plan, m, a, bindings, options, held, nil, future...) } -func (s *Service) resolvePoolsReviewed(ctx context.Context, plan *Plan, m *manifest.Manifest, a *cloudprofiles.Assignment, bindings []*Binding, options []ConnectionOption, held map[string]bool, selections map[string]locationSelection, future ...map[string]*CapacityIntent) (map[string]*cloudinfra.Placement, error) { +func (s *Service) resolvePoolsReviewed(ctx context.Context, plan *Plan, m *manifest.Manifest, a *cloudprofiles.ProjectCloud, bindings []*Binding, options []ConnectionOption, held map[string]bool, selections map[string]locationSelection, future ...map[string]*CapacityIntent) (map[string]*cloudinfra.Placement, error) { return s.resolvePoolsWithLocationInput(ctx, plan, m, a, bindings, options, held, selections, Input{}, future...) } -func (s *Service) resolvePoolsWithLocationInput(ctx context.Context, plan *Plan, m *manifest.Manifest, a *cloudprofiles.Assignment, bindings []*Binding, options []ConnectionOption, held map[string]bool, selections map[string]locationSelection, input Input, future ...map[string]*CapacityIntent) (map[string]*cloudinfra.Placement, error) { +func (s *Service) resolvePoolsWithLocationInput(ctx context.Context, plan *Plan, m *manifest.Manifest, a *cloudprofiles.ProjectCloud, bindings []*Binding, options []ConnectionOption, held map[string]bool, selections map[string]locationSelection, input Input, future ...map[string]*CapacityIntent) (map[string]*cloudinfra.Placement, error) { out := map[string]*cloudinfra.Placement{} if a == nil { for name, svc := range m.Services { diff --git a/internal/planning/cloud_targets_service_test.go b/internal/planning/cloud_targets_service_test.go index a52ae19e1..1fab203c2 100644 --- a/internal/planning/cloud_targets_service_test.go +++ b/internal/planning/cloud_targets_service_test.go @@ -25,11 +25,11 @@ func (c targetOptions) All(context.Context, string) ([]*connections.Connection, } type targetResolver struct { - assignment *cloudprofiles.Assignment + assignment *cloudprofiles.ProjectCloud calls int } -func (c *targetResolver) Resolve(context.Context, string, string, string) (*cloudprofiles.Assignment, error) { +func (c *targetResolver) ResolveCloud(context.Context, string, string, string) (*cloudprofiles.ProjectCloud, error) { c.calls++ return c.assignment, nil } @@ -48,7 +48,7 @@ func targetPlanningService(t *testing.T, doc string) (*Service, *Plan, *targetRe } func TestCloudTargetServiceScopeAndRevisionDigest(t *testing.T) { - for _, scope := range []string{"org", "project", "environment"} { + for _, scope := range []string{"org", "project"} { t.Run(scope, func(t *testing.T) { s, p, r := targetPlanningService(t, "version: 1\nservices:\n web: {source: cmd/api, cloud_target: frontend}\n") switch scope { @@ -56,8 +56,6 @@ func TestCloudTargetServiceScopeAndRevisionDigest(t *testing.T) { r.assignment.OrgID = "another" case "project": r.assignment.ProjectID = "another" - case "environment": - r.assignment.EnvironmentID = "another" } result, _, err := s.compute(t.Context(), p) if err != nil || result.Executable || len(result.Problems) == 0 { diff --git a/internal/planning/cloud_targets_test.go b/internal/planning/cloud_targets_test.go index 47701faca..4d1d749f6 100644 --- a/internal/planning/cloud_targets_test.go +++ b/internal/planning/cloud_targets_test.go @@ -16,8 +16,8 @@ import ( "github.com/xraph/loomplane/pkg/provider" ) -func cloudTargetFixture() (*cloudprofiles.Assignment, []ConnectionOption) { - return &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 3, Revision: 4, Targets: []cloudprofiles.Target{ +func cloudTargetFixture() (*cloudprofiles.ProjectCloud, []ConnectionOption) { + return &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 3, GrantRevision: 4, Targets: []cloudprofiles.Target{ {ID: "target-a", OrgID: "org", ProjectID: "project", CloudID: "cloud", Name: "frontend", Provider: "vercel", ConnectionID: "a", Revision: 5}, {ID: "target-b", OrgID: "org", ProjectID: "project", CloudID: "cloud", Name: "preview", Provider: "vercel", ConnectionID: "b", Revision: 6}, }}, []ConnectionOption{ @@ -85,19 +85,19 @@ func TestCloudTargetsTwoManagedAccountsAndMetadataAdoption(t *testing.T) { func TestCloudTargetsResolutionFailuresAndOverrides(t *testing.T) { for _, tc := range []struct { name, doc, message string - mutate func(*cloudprofiles.Assignment, []ConnectionOption) *cloudprofiles.Assignment + mutate func(*cloudprofiles.ProjectCloud, []ConnectionOption) *cloudprofiles.ProjectCloud }{ - {name: "missing assignment", message: "assigned", mutate: func(_ *cloudprofiles.Assignment, _ []ConnectionOption) *cloudprofiles.Assignment { return nil }}, + {name: "no default cloud", message: "default cloud", mutate: func(_ *cloudprofiles.ProjectCloud, _ []ConnectionOption) *cloudprofiles.ProjectCloud { return nil }}, {name: "missing target", doc: "cloud_target: missing", message: "missing"}, - {name: "wrong scope", message: "scope", mutate: func(a *cloudprofiles.Assignment, _ []ConnectionOption) *cloudprofiles.Assignment { + {name: "wrong scope", message: "scope", mutate: func(a *cloudprofiles.ProjectCloud, _ []ConnectionOption) *cloudprofiles.ProjectCloud { a.Targets[0].OrgID = "other" return a }}, - {name: "unready", message: "ready", mutate: func(a *cloudprofiles.Assignment, c []ConnectionOption) *cloudprofiles.Assignment { + {name: "unready", message: "ready", mutate: func(a *cloudprofiles.ProjectCloud, c []ConnectionOption) *cloudprofiles.ProjectCloud { c[0].Ready = false return a }}, - {name: "unverified", message: "verif", mutate: func(a *cloudprofiles.Assignment, c []ConnectionOption) *cloudprofiles.Assignment { + {name: "unverified", message: "verif", mutate: func(a *cloudprofiles.ProjectCloud, c []ConnectionOption) *cloudprofiles.ProjectCloud { c[0].Details = nil return a }}, @@ -152,10 +152,10 @@ func TestCloudTargetsResolvedCopyDoesNotShareSettings(t *testing.T) { func TestCloudTargetsRejectMissingRevisions(t *testing.T) { a, c := cloudTargetFixture() - a.Revision = 0 + a.GrantRevision = 0 _, _, err := ResolveCloudTargets(parse(t, "version: 1\nservices:\n web: {source: cmd/api, cloud_target: frontend}\n"), "production", a, c) if err == nil { - t.Fatal("unversioned assignment produced an unexecutable pin") + t.Fatal("an unreviewed grant produced an unexecutable pin") } } @@ -266,7 +266,7 @@ func TestServerGPUs(t *testing.T) { // reservation holds them, so planning neither fits them against the // connection's own GPUs nor gives the service a node selector. func TestPoolPinCarriesServiceGPUs(t *testing.T) { - assigned := &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 1, Revision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", CloudID: "cloud", Name: "shared", Provider: "server", Runtime: "server", PoolID: "pool", Revision: 1}}} + assigned := &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", CloudID: "cloud", Name: "shared", Provider: "server", Runtime: "server", PoolID: "pool", Revision: 1}}} options := []ConnectionOption{{ID: "runtime", Cloud: "server", Ready: true, Pooled: true, Details: map[string]string{"docker_id": "daemon", "architecture": "amd64"}}} m := parse(t, "version: 1\nservices:\n web: {source: cmd/api, cloud_target: shared, size: {cpu: 4, memory: 16384, gpu: {kind: nvidia-l4, count: 1}}}\n") pool := &cloudinfra.Placement{PoolID: "pool", PoolRevision: 3, ServerID: "host", ServerRevision: 2, ConnectionID: "runtime", ConnectionGeneration: 1, CPUMillis: 4000, MemoryBytes: 16384 << 20, GPUKind: "nvidia-l4", GPUs: 1} @@ -299,7 +299,7 @@ func TestPoolPinCarriesServiceGPUs(t *testing.T) { // pooledGPUBinding is a deployed service that ran on a GPU server with the // given size, holding a server GPU placement with a node selector that a // pool placement can't use. -func pooledGPUBinding(t *testing.T, size *manifest.Size) (*Binding, *cloudprofiles.Assignment, []ConnectionOption) { +func pooledGPUBinding(t *testing.T, size *manifest.Size) (*Binding, *cloudprofiles.ProjectCloud, []ConnectionOption) { t.Helper() binding := appliedTestBinding(t, "api", "original") var cfg ServiceConfig @@ -344,7 +344,7 @@ func TestCloudSyncOntoAPoolRecomputesGPUs(t *testing.T) { if err != nil { t.Fatal(err) } - pin := CloudPlacement{CloudID: "cloud", CloudRevision: 1, AssignmentRevision: 1, TargetID: "target", TargetRevision: 2, TargetName: "frontend", Provider: "server", ConnectionID: "new", AccountIdentity: "server:new", PoolID: "pool", ServerID: "host-new", CPUMillis: cpu, MemoryBytes: mem, GPUKind: kind, GPUs: gpus} + pin := CloudPlacement{CloudID: "cloud", CloudRevision: 1, TargetID: "target", TargetRevision: 2, TargetName: "frontend", Provider: "server", ConnectionID: "new", AccountIdentity: "server:new", PoolID: "pool", ServerID: "host-new", CPUMillis: cpu, MemoryBytes: mem, GPUKind: kind, GPUs: gpus} result := appliedCloudPlan([]*Binding{binding}, assigned, "", options, providers.Registry(), map[string]CloudPlacement{"api": pin}) moved := action(t, result, "service:api") if !reflect.DeepEqual(moved.Service.GPU, tc.want) { @@ -435,7 +435,7 @@ func TestAcceptedPoolMoveReservesTheNewGPURequest(t *testing.T) { // A pooled service whose reservation holds a different GPU count or kind // from its runtime request can't be applied. func TestPoolGPUMismatchIsAProblem(t *testing.T) { - assigned := &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 1, Revision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", CloudID: "cloud", Name: "shared", Provider: "server", Runtime: "server", PoolID: "pool", Revision: 1}}} + assigned := &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", CloudID: "cloud", Name: "shared", Provider: "server", Runtime: "server", PoolID: "pool", Revision: 1}}} options := []ConnectionOption{{ID: "runtime", Cloud: "server", Ready: true, Pooled: true, Details: map[string]string{"docker_id": "daemon", "architecture": "amd64"}}} for name, tc := range map[string]struct { manifest string diff --git a/internal/planning/composition_test.go b/internal/planning/composition_test.go index ef4a79edd..fecbb477e 100644 --- a/internal/planning/composition_test.go +++ b/internal/planning/composition_test.go @@ -697,7 +697,7 @@ func TestCompositionWithControlPortNeedsServiceProxy(t *testing.T) { const edgeApp = "version: 1\nresources:\n edge: {kind: sample, provider: server, target: " + targetA + "}\n" func edgePlacement() CloudPlacement { - return CloudPlacement{CloudID: "cloud_1", CloudRevision: 1, AssignmentRevision: 1, TargetID: "t1", TargetRevision: 1, TargetName: "edge-host", Provider: "server", ConnectionID: targetA, RegionSource: "default"} + return CloudPlacement{CloudID: "cloud_1", CloudRevision: 1, TargetID: "t1", TargetRevision: 1, TargetName: "edge-host", Provider: "server", ConnectionID: targetA, RegionSource: "default"} } func TestComposedComponentsCarryTheCloudPlacement(t *testing.T) { diff --git a/internal/planning/dbgateway.go b/internal/planning/dbgateway.go index 811631169..a126e4c03 100644 --- a/internal/planning/dbgateway.go +++ b/internal/planning/dbgateway.go @@ -502,7 +502,7 @@ func (p *planner) isDatabaseGateway(b *Binding) bool { // target the way a service's is: the target its Cloud tags select, or // the Cloud's default when nothing else places it. The manifest it // rewrites is resolveCloudPlacements' copy. -func resolveDatabaseGatewayPlacement(out *manifest.Manifest, env string, assignment *cloudprofiles.Assignment, options []ConnectionOption, pools map[string]*cloudinfra.Placement, placements map[string]CloudPlacement) error { +func resolveDatabaseGatewayPlacement(out *manifest.Manifest, env string, assignment *cloudprofiles.ProjectCloud, options []ConnectionOption, pools map[string]*cloudinfra.Placement, placements map[string]CloudPlacement) error { set, ok := dbGatewayToPlace(out, env) if !ok { return nil diff --git a/internal/planning/dbgateway_test.go b/internal/planning/dbgateway_test.go index 90475ad2a..7225ef582 100644 --- a/internal/planning/dbgateway_test.go +++ b/internal/planning/dbgateway_test.go @@ -407,8 +407,8 @@ func TestDatabaseGatewayLabels(t *testing.T) { // dbgwCloudFixture is a Cloud with a Cloud Run target tagged db, a Vercel // target tagged web, and a default placement on ECS. -func dbgwCloudFixture() (*cloudprofiles.Assignment, []ConnectionOption) { - return &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 3, Revision: 4, +func dbgwCloudFixture() (*cloudprofiles.ProjectCloud, []ConnectionOption) { + return &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 3, GrantRevision: 4, Targets: []cloudprofiles.Target{ {ID: "target-run", OrgID: "org", ProjectID: "project", CloudID: "cloud", Name: "run", Provider: cloudRun, ConnectionID: "g", Region: "us-east4", Revision: 5, Tags: []string{"db"}}, {ID: "target-web", OrgID: "org", ProjectID: "project", CloudID: "cloud", Name: "web", Provider: "vercel", ConnectionID: "v", Revision: 6, Tags: []string{"web"}}, @@ -723,7 +723,7 @@ func dbgwAppliedGateway(t *testing.T) *Binding { t.Helper() cfg := ServiceConfig{Provider: cloudRun, Region: "us-east1", Workload: "http-service", Execution: "container", Source: ".", Ecosystem: "go", Image: dbgateway.Dockerfile, Port: dbgateway.Port, Public: true, DatabaseGateway: &DatabaseGatewayConfig{Name: dbGatewayName, Suffix: "us-east1.db.example.com", Resources: []string{"db"}}, - CloudPlacement: &CloudPlacement{CloudID: "cloud", CloudRevision: 1, AssignmentRevision: 1, TargetID: "target", TargetRevision: 1, TargetName: "run", Provider: cloudRun, ConnectionID: "old", AccountIdentity: "gcp:old"}} + CloudPlacement: &CloudPlacement{CloudID: "cloud", CloudRevision: 1, TargetID: "target", TargetRevision: 1, TargetName: "run", Provider: cloudRun, ConnectionID: "old", AccountIdentity: "gcp:old"}} raw, err := json.Marshal(cfg) if err != nil { t.Fatal(err) @@ -732,8 +732,8 @@ func dbgwAppliedGateway(t *testing.T) *Binding { } func TestDatabaseGatewayInCloudSync(t *testing.T) { - assignment := func(connection string) *cloudprofiles.Assignment { - return &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 1, Revision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", ProjectID: "project", CloudID: "cloud", Name: "run", Provider: cloudRun, ConnectionID: connection, Revision: 2}}} + assignment := func(connection string) *cloudprofiles.ProjectCloud { + return &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", ProjectID: "project", CloudID: "cloud", Name: "run", Provider: cloudRun, ConnectionID: connection, Revision: 2}}} } gcp := func(id string) ConnectionOption { return ConnectionOption{ID: id, Cloud: "gcp", Ready: true, Details: map[string]string{"project_id": id}} @@ -810,7 +810,7 @@ func TestDatabaseGatewayHeldUserWhenItsResourceLeaves(t *testing.T) { func TestDatabaseGatewayMarkingClearsAdoption(t *testing.T) { live := deployed(t, dbgwCompute(t, dbgwSameCloud, exampleZone)) in := dbgwInput(t, strings.Replace(dbgwSameCloud, "provider: digitalocean}", "provider: digitalocean, gateway: true}", 1), exampleZone, live...) - in.CloudPlacements = map[string]CloudPlacement{"api": {CloudID: "cloud", CloudRevision: 1, AssignmentRevision: 1, TargetID: "target", TargetRevision: 1, TargetName: "apps", Provider: "digitalocean", ConnectionID: "conn_do", AccountIdentity: "digitalocean:team"}} + in.CloudPlacements = map[string]CloudPlacement{"api": {CloudID: "cloud", CloudRevision: 1, TargetID: "target", TargetRevision: 1, TargetName: "apps", Provider: "digitalocean", ConnectionID: "conn_do", AccountIdentity: "digitalocean:team"}} api := action(t, Compute(in), "service:api") if api.Op != Update || api.AdoptCloudPlacement || api.CloudAdoption != nil { t.Fatalf("api is %s, adopt %v %+v", api.Op, api.AdoptCloudPlacement, api.CloudAdoption) diff --git a/internal/planning/location_evidence.go b/internal/planning/location_evidence.go index 07eebb659..6a79bcdbe 100644 --- a/internal/planning/location_evidence.go +++ b/internal/planning/location_evidence.go @@ -33,7 +33,7 @@ type locationCapacityReview struct { type locationEvidenceStore interface { LocationPolicy(context.Context, string, string) (*cloudprofiles.LocationPolicy, error) - LocationCandidate(context.Context, *Plan, *cloudprofiles.Assignment, cloudprofiles.Target, manifest.Settings, cloudinfra.PlacementRequest, cloudinfra.ClusterWorkloadVector) (PlacementCandidate, error) + LocationCandidate(context.Context, *Plan, *cloudprofiles.ProjectCloud, cloudprofiles.Target, manifest.Settings, cloudinfra.PlacementRequest, cloudinfra.ClusterWorkloadVector) (PlacementCandidate, error) } func (s *PgStore) LocationPolicy(ctx context.Context, org, cloud string) (*cloudprofiles.LocationPolicy, error) { @@ -42,7 +42,7 @@ func (s *PgStore) LocationPolicy(ctx context.Context, org, cloud string) (*cloud // LocationCandidate loads authoritative location and scheduler evidence. Pool // previews retain the same cumulative workload accounting as ordinary planning. -func (s *PgStore) LocationCandidate(ctx context.Context, plan *Plan, a *cloudprofiles.Assignment, t cloudprofiles.Target, set manifest.Settings, request cloudinfra.PlacementRequest, cumulative cloudinfra.ClusterWorkloadVector) (PlacementCandidate, error) { +func (s *PgStore) LocationCandidate(ctx context.Context, plan *Plan, a *cloudprofiles.ProjectCloud, t cloudprofiles.Target, set manifest.Settings, request cloudinfra.PlacementRequest, cumulative cloudinfra.ClusterWorkloadVector) (PlacementCandidate, error) { c := PlacementCandidate{TargetID: t.ID, LocationID: t.LocationID, OrgID: t.OrgID, ProjectID: plan.ProjectID, EnvironmentID: plan.EnvironmentID, Provider: t.Provider, Runtime: t.Runtime, TargetRevision: t.Revision, GrantRevision: a.GrantRevision, Granted: true} if t.Runtime == platformRuntime { // Location policy doesn't apply to Loomplane Cloud, which chooses @@ -191,7 +191,7 @@ func (s *PgStore) LocationCandidate(ctx context.Context, plan *Plan, a *cloudpro return c, nil } -func (s *Service) selectLocation(ctx context.Context, plan *Plan, a *cloudprofiles.Assignment, set manifest.Settings, name string, bindings []*Binding, options []ConnectionOption, planned []cloudinfra.PlannedPlacement, repo string, prior map[string]locationSelection, reviewed *locationCapacityReview, requirements locationRequirements) (*cloudprofiles.Target, locationSelection, error) { +func (s *Service) selectLocation(ctx context.Context, plan *Plan, a *cloudprofiles.ProjectCloud, set manifest.Settings, name string, bindings []*Binding, options []ConnectionOption, planned []cloudinfra.PlannedPlacement, repo string, prior map[string]locationSelection, reviewed *locationCapacityReview, requirements locationRequirements) (*cloudprofiles.Target, locationSelection, error) { selected := locationSelection{} reader, ok := s.store.(locationEvidenceStore) if !ok || a == nil { diff --git a/internal/planning/location_migration.go b/internal/planning/location_migration.go index 7f9ac3896..1be15825f 100644 --- a/internal/planning/location_migration.go +++ b/internal/planning/location_migration.go @@ -5,13 +5,12 @@ import ( "fmt" "github.com/xraph/loomplane/internal/cloudinfra" - "github.com/xraph/loomplane/internal/cloudprofiles" "github.com/xraph/loomplane/pkg/provider" ) // appliedPoolMoves supplies only the unconstrained services changing hosts. // Their source, variables and runtime settings retain the existing move contract. -func appliedPoolMoves(bindings []*Binding, assignment *cloudprofiles.Assignment, options []ConnectionOption, registry *provider.Registry, placements map[string]CloudPlacement, routes []cloudinfra.Route, selections map[string]locationSelection) (map[string]Action, []Finding) { +func appliedPoolMoves(bindings []*Binding, clouds cloudChooser, options []ConnectionOption, registry *provider.Registry, placements map[string]CloudPlacement, routes []cloudinfra.Route, selections map[string]locationSelection) (map[string]Action, []Finding) { names := map[string]bool{} for _, b := range bindings { if b.Subject != ServiceSubject { @@ -29,7 +28,7 @@ func appliedPoolMoves(bindings []*Binding, assignment *cloudprofiles.Assignment, if len(names) == 0 { return nil, nil } - applied := appliedCloudPlan(bindings, assignment, "", options, registry, placements, routes) + applied := appliedCloudPlanChoosing(bindings, clouds, "", options, registry, placements, nil, routes) actions := map[string]Action{} for _, a := range applied.Actions { if names[a.Name] && a.Subject == ServiceSubject { diff --git a/internal/planning/location_placement_test.go b/internal/planning/location_placement_test.go index 34a7683d7..12e66612e 100644 --- a/internal/planning/location_placement_test.go +++ b/internal/planning/location_placement_test.go @@ -195,7 +195,7 @@ type locationTestStore struct { func (s locationTestStore) LocationPolicy(context.Context, string, string) (*cloudprofiles.LocationPolicy, error) { return &s.policy, nil } -func (s locationTestStore) LocationCandidate(_ context.Context, _ *Plan, _ *cloudprofiles.Assignment, target cloudprofiles.Target, _ manifest.Settings, _ cloudinfra.PlacementRequest, _ cloudinfra.ClusterWorkloadVector) (PlacementCandidate, error) { +func (s locationTestStore) LocationCandidate(_ context.Context, _ *Plan, _ *cloudprofiles.ProjectCloud, target cloudprofiles.Target, _ manifest.Settings, _ cloudinfra.PlacementRequest, _ cloudinfra.ClusterWorkloadVector) (PlacementCandidate, error) { for _, c := range s.candidates { if c.TargetID == target.ID { return c, nil @@ -214,7 +214,7 @@ func TestLocationPlacementPlannerSelection(t *testing.T) { s := NewService(Deps{Store: store, Providers: providers.Registry()}) s.now = func() time.Time { return in.Now } plan := &Plan{OrgID: "org", ProjectID: "project", EnvironmentID: "env", Environment: "production"} - assignment := &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "a", Name: "a", Provider: "vercel", Runtime: "managed", LocationID: "la"}, {ID: "b", Name: "b", Provider: "vercel", Runtime: "managed", LocationID: "lb"}}} + assignment := &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "a", Name: "a", Provider: "vercel", Runtime: "managed", LocationID: "la"}, {ID: "b", Name: "b", Provider: "vercel", Runtime: "managed", LocationID: "lb"}}} raw, err := json.Marshal(ServiceConfig{Workload: provider.WebApp, CloudPlacement: &CloudPlacement{TargetID: "b"}}) if err != nil { t.Fatal(err) @@ -289,7 +289,7 @@ func TestLocationPlacementMaterializationPreservesArchitecture(t *testing.T) { s := NewService(Deps{Store: store, Providers: providers.Registry()}) s.now = func() time.Time { return in.Now } m := &manifest.Manifest{Services: map[string]manifest.Service{"api": {Kind: "web-app", Settings: manifest.Settings{Placement: &manifest.PlacementConstraints{Architecture: "arm64"}}}}} - a := &cloudprofiles.Assignment{CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "b", Name: "pool", Provider: "server", PoolID: "mixed"}}} + a := &cloudprofiles.ProjectCloud{CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "b", Name: "pool", Provider: "server", PoolID: "mixed"}}} raw, err := json.Marshal(ServiceConfig{Workload: provider.WebApp, TargetSettings: map[string]string{"architecture": "amd64"}}) if err != nil { t.Fatal(err) @@ -311,7 +311,7 @@ func TestLocationPlacementDesiredWorkloadBeforeRank(t *testing.T) { s := NewService(Deps{Store: store, Providers: providers.Registry()}) s.now = func() time.Time { return in.Now } m := &manifest.Manifest{Services: map[string]manifest.Service{"api": {Source: "cmd/api", Settings: manifest.Settings{Placement: &manifest.PlacementConstraints{}}}}} - a := &cloudprofiles.Assignment{CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "a", Name: "a", Provider: "vercel"}, {ID: "b", Name: "b", Provider: "render"}}} + a := &cloudprofiles.ProjectCloud{CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "a", Name: "a", Provider: "vercel"}, {ID: "b", Name: "b", Provider: "render"}}} var bindings []*Binding if existing { raw, _ := json.Marshal(ServiceConfig{Workload: provider.WebApp, CloudPlacement: &CloudPlacement{TargetID: "a"}}) @@ -338,7 +338,7 @@ func TestLocationPlacementSavedDependencyBeforeRank(t *testing.T) { s := NewService(Deps{Store: store, Providers: providers.Registry()}) s.now = func() time.Time { return in.Now } m := &manifest.Manifest{Services: map[string]manifest.Service{"api": {Kind: "web-app", Needs: []string{"db"}, Settings: manifest.Settings{Placement: &manifest.PlacementConstraints{}}}}, Resources: map[string]manifest.Resource{"db": {Kind: "postgres", Provider: "server", Target: "b"}}} - a := &cloudprofiles.Assignment{CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "a", Name: "a", Provider: "server", ConnectionID: "a"}, {ID: "b", Name: "b", Provider: "server", ConnectionID: "b"}}} + a := &cloudprofiles.ProjectCloud{CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "a", Name: "a", Provider: "server", ConnectionID: "a"}, {ID: "b", Name: "b", Provider: "server", ConnectionID: "b"}}} raw := json.RawMessage(`{"provider":"server","target":"b","target_settings":{"docker_id":"b"},"catalog":{}}`) bindings := []*Binding{{Subject: ResourceSubject, Name: "db", Provider: "server", ConnectionID: "b", Config: raw}} options := []ConnectionOption{{ID: "a", Cloud: "server", Ready: true, Details: map[string]string{"docker_id": "a"}}, {ID: "b", Cloud: "server", Ready: true, Details: map[string]string{"docker_id": "b"}}} @@ -367,7 +367,7 @@ type locationComputeStore struct { func (s locationComputeStore) LocationPolicy(ctx context.Context, org, cloud string) (*cloudprofiles.LocationPolicy, error) { return s.mixed.LocationPolicy(ctx, org, cloud) } -func (s locationComputeStore) LocationCandidate(ctx context.Context, p *Plan, a *cloudprofiles.Assignment, target cloudprofiles.Target, set manifest.Settings, req cloudinfra.PlacementRequest, c cloudinfra.ClusterWorkloadVector) (PlacementCandidate, error) { +func (s locationComputeStore) LocationCandidate(ctx context.Context, p *Plan, a *cloudprofiles.ProjectCloud, target cloudprofiles.Target, set manifest.Settings, req cloudinfra.PlacementRequest, c cloudinfra.ClusterWorkloadVector) (PlacementCandidate, error) { return s.mixed.LocationCandidate(ctx, p, a, target, set, req, c) } func (s locationComputeStore) PreviewPlacement(ctx context.Context, req cloudinfra.PlacementRequest) (*cloudinfra.Placement, error) { @@ -380,7 +380,7 @@ func TestLocationPlacementSamePoolMoveKeepsDesiredConfiguration(t *testing.T) { c.Provider, c.ServerID, c.RuntimeConnectionID, c.ConnectionGeneration = "server", "arm", "arm", 1 s, plan, resolver := targetPlanningService(t, "version: 1\nservices:\n web: {source: cmd/api, kind: worker, placement: {architecture: arm64}}\n") s.now = func() time.Time { return in.Now } - resolver.assignment = &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 1, Revision: 1, GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "b", OrgID: "org", CloudID: "cloud", Name: "mixed", Provider: "server", Runtime: "server", PoolID: "mixed", Revision: 1}}} + resolver.assignment = &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 1, GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "b", OrgID: "org", CloudID: "cloud", Name: "mixed", Provider: "server", Runtime: "server", PoolID: "mixed", Revision: 1}}} old := ServiceConfig{Provider: "server", Target: "amd", TargetSettings: map[string]string{"docker_id": "amd", "architecture": "amd64"}, Workload: provider.WebApp, Source: "cmd/api", Image: "Dockerfile", CloudPlacement: &CloudPlacement{CloudID: "cloud", TargetID: "b", TargetName: "mixed", PoolID: "mixed", ServerID: "amd", ConnectionID: "amd"}} raw, err := json.Marshal(old) if err != nil { @@ -418,7 +418,7 @@ func TestLocationPlacementCurrentPoolLabelDoesNotKeepIneligibleHost(t *testing.T store := locationTestStore{candidates: in.Candidates} s := NewService(Deps{Store: store, Providers: providers.Registry()}) s.now = func() time.Time { return in.Now } - a := &cloudprofiles.Assignment{CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "a", Name: "a", Provider: "server"}, {ID: "b", Name: "b", Provider: "server", PoolID: "mixed"}}} + a := &cloudprofiles.ProjectCloud{CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "a", Name: "a", Provider: "server"}, {ID: "b", Name: "b", Provider: "server", PoolID: "mixed"}}} old := ServiceConfig{Target: "old-b", TargetSettings: map[string]string{"architecture": "amd64"}, Workload: provider.Worker, CloudPlacement: &CloudPlacement{TargetID: "b", PoolID: "mixed", ServerID: "old-b"}} raw, err := json.Marshal(old) if err != nil { @@ -447,7 +447,7 @@ func TestLocationPlacementNewPoolDependencyBeforeRank(t *testing.T) { "dependency": {Kind: "web-app", Settings: manifest.Settings{CloudTarget: "pool", Public: &public}}, "consumer": {Kind: "web-app", Needs: []string{"dependency"}, Settings: manifest.Settings{Placement: &manifest.PlacementConstraints{}}}, }} - a := &cloudprofiles.Assignment{CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "a", Name: "a", Provider: "server", ConnectionID: "a"}, {ID: "b", Name: "pool", Provider: "server", PoolID: "mixed"}}} + a := &cloudprofiles.ProjectCloud{CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "a", Name: "a", Provider: "server", ConnectionID: "a"}, {ID: "b", Name: "pool", Provider: "server", PoolID: "mixed"}}} options := []ConnectionOption{{ID: "a", Cloud: "server", Ready: true, Details: map[string]string{"docker_id": "a"}}, {ID: "amd", Cloud: "server", Ready: true, Details: map[string]string{"docker_id": "amd"}}} var bindings []*Binding if scenario == "applied-private" { @@ -473,7 +473,7 @@ func TestLocationPlacementMixedMovePreservesAppliedInputs(t *testing.T) { c.Provider, c.ServerID, c.RuntimeConnectionID, c.ConnectionGeneration = "server", "amd", "amd", 1 s, plan, resolver := targetPlanningService(t, "version: 1\nservices:\n web: {source: cmd/api, kind: worker, placement: {}}\n other: {source: cmd/api, kind: worker, cloud_target: mixed, size: {cpu: 1.5, memory: 768}}\n") s.now = func() time.Time { return in.Now } - resolver.assignment = &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 1, Revision: 1, GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "b", OrgID: "org", CloudID: "cloud", Name: "mixed", Provider: "server", Runtime: "server", PoolID: "mixed", Revision: 1}}} + resolver.assignment = &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 1, GrantRevision: 2, Targets: []cloudprofiles.Target{{ID: "b", OrgID: "org", CloudID: "cloud", Name: "mixed", Provider: "server", Runtime: "server", PoolID: "mixed", Revision: 1}}} old := ServiceConfig{Provider: "server", Target: "arm", TargetSettings: map[string]string{"docker_id": "arm", "architecture": "amd64"}, Workload: provider.Worker, Repo: "app", CommitSHA: "old", Source: "cmd/api", Image: "Dockerfile", Size: &manifest.Size{CPU: 1, Memory: 512}, CloudPlacement: &CloudPlacement{CloudID: "cloud", TargetID: "b", TargetName: "mixed", PoolID: "mixed", ServerID: "arm", ConnectionID: "arm"}, AppliedInputs: &AppliedInputs{Variables: "vars", ArtifactKey: "artifact", Source: &PlanSource{Alias: "app", CommitSHA: "old"}}} raw, _ := json.Marshal(old) s.store = locationComputeStore{catalogStore: catalogStore{bindings: []*Binding{{ID: "binding", Subject: ServiceSubject, Name: "other", Provider: "server", ConnectionID: "arm", CommitSHA: "old", Config: raw}}}, mixed: mixedLocationStore{locationTestStore{candidates: []PlacementCandidate{c}}}} @@ -507,7 +507,7 @@ func TestLocationPlacementSkipsPlatformTargets(t *testing.T) { s := NewService(Deps{Store: store, Providers: providers.Registry()}) s.now = func() time.Time { return in.Now } plan := &Plan{OrgID: "org", ProjectID: "project", EnvironmentID: "env", Environment: "production"} - assignment := &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{ + assignment := &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", GrantRevision: 2, Targets: []cloudprofiles.Target{ {ID: "fra", Name: "fra", Provider: "platform", Runtime: "platform", Region: "fra"}, {ID: "a", Name: "a", Provider: "vercel", Runtime: "managed", LocationID: "la"}, }} diff --git a/internal/planning/location_requirements.go b/internal/planning/location_requirements.go index d17da9ca5..cdeb6c1bd 100644 --- a/internal/planning/location_requirements.go +++ b/internal/planning/location_requirements.go @@ -52,7 +52,7 @@ func locationWorkload(m *manifest.Manifest, name string, g *graph.Graph) (provid // locationRequirements reads only this plan's scoped bindings and declared // destinations. Unknown dependency destinations are not network evidence. -func (s *Service) locationRequirements(plan *Plan, m *manifest.Manifest, name string, g *graph.Graph, a *cloudprofiles.Assignment, bindings []*Binding, options []ConnectionOption, prior map[string]locationSelection, held map[string]bool, chosen map[string]string, pools map[string]*cloudinfra.Placement) (locationRequirements, error) { +func (s *Service) locationRequirements(plan *Plan, m *manifest.Manifest, name string, g *graph.Graph, a *cloudprofiles.ProjectCloud, bindings []*Binding, options []ConnectionOption, prior map[string]locationSelection, held map[string]bool, chosen map[string]string, pools map[string]*cloudinfra.Placement) (locationRequirements, error) { out := locationRequirements{} var err error out.Workload, err = locationWorkload(m, name, g) diff --git a/internal/planning/planner_test.go b/internal/planning/planner_test.go index c2e58e5cb..ed6874f7a 100644 --- a/internal/planning/planner_test.go +++ b/internal/planning/planner_test.go @@ -320,7 +320,7 @@ func TestCompute_azureAppsCantReachPrivateAppsElsewhere(t *testing.T) { {"another resource group", "other", "east"}, } { t.Run(tt.name, func(t *testing.T) { - assigned := &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 1, Revision: 1, Targets: []cloudprofiles.Target{ + assigned := &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{ {ID: "t-east", OrgID: "org", ProjectID: "project", CloudID: "cloud", Name: "east", Provider: "azure-container-apps", ConnectionID: "conn_a", Region: "eastus", Revision: 1}, {ID: "t-west", OrgID: "org", ProjectID: "project", CloudID: "cloud", Name: "west", Provider: "azure-container-apps", ConnectionID: "conn_a", Region: "westeurope", Revision: 1}, {ID: "t-other", OrgID: "org", ProjectID: "project", CloudID: "cloud", Name: "other", Provider: "azure-container-apps", ConnectionID: "conn_b", Region: "eastus", Revision: 1}, diff --git a/internal/planning/platform.go b/internal/planning/platform.go index b09b2d9c1..17acd72b4 100644 --- a/internal/planning/platform.go +++ b/internal/planning/platform.go @@ -68,7 +68,7 @@ func platformRequest(plan *Plan, name, region string, size *manifest.Size) (plat // refusePlatformLocation refuses location constraints on a service that a // Loomplane Cloud target places, or that only Loomplane Cloud targets could // place: the platform chooses its own hosts. -func refusePlatformLocation(name string, set manifest.Settings, a *cloudprofiles.Assignment) error { +func refusePlatformLocation(name string, set manifest.Settings, a *cloudprofiles.ProjectCloud) error { if set.Placement == nil || a == nil { return nil } @@ -91,7 +91,7 @@ func refusePlatformLocation(name string, set manifest.Settings, a *cloudprofiles // Loomplane Cloud target. A refusal is the plan's problem at the service. // A Cloud default is never a Loomplane Cloud target, so only services that // name or tag one are previewed. -func (s *Service) resolvePlatform(ctx context.Context, plan *Plan, m *manifest.Manifest, a *cloudprofiles.Assignment, held map[string]bool) (map[string]*platformcloud.Ref, error) { +func (s *Service) resolvePlatform(ctx context.Context, plan *Plan, m *manifest.Manifest, a *cloudprofiles.ProjectCloud, held map[string]bool) (map[string]*platformcloud.Ref, error) { out := map[string]*platformcloud.Ref{} if a == nil { return out, nil @@ -128,7 +128,7 @@ func (s *Service) resolvePlatform(ctx context.Context, plan *Plan, m *manifest.M // platformPlacement pins a service to a Loomplane Cloud target. It looks up // no connection: the target has none, and the room is ref's. -func platformPlacement(name, path string, set manifest.Settings, a *cloudprofiles.Assignment, t cloudprofiles.Target, ref *platformcloud.Ref) (CloudPlacement, manifest.Settings, error) { +func platformPlacement(name, path string, set manifest.Settings, a *cloudprofiles.ProjectCloud, t cloudprofiles.Target, ref *platformcloud.Ref) (CloudPlacement, manifest.Settings, error) { if ref == nil { message := platformUnavailable if name == dbGatewayName { @@ -148,27 +148,27 @@ func platformPlacement(name, path string, set manifest.Settings, a *cloudprofile return CloudPlacement{}, set, err } set.Provider, set.Region, set.Target = platformRuntime, t.Region, "" - set.CloudTarget, set.CloudTags = "", nil + set.Cloud, set.CloudTarget, set.CloudTags = "", "", nil return p, set, nil } // platformCloudPin pins the assignment's Loomplane Cloud target t with the // room ref previewed in it. The pin names no connection, pool or server. -func platformCloudPin(a *cloudprofiles.Assignment, t cloudprofiles.Target, ref *platformcloud.Ref, regionSource string) (CloudPlacement, error) { +func platformCloudPin(a *cloudprofiles.ProjectCloud, t cloudprofiles.Target, ref *platformcloud.Ref, regionSource string) (CloudPlacement, error) { if !isPlatformTarget(&t) || ref == nil || ref.Region != t.Region { return CloudPlacement{}, fmt.Errorf("a Loomplane Cloud placement needs its target's region previewed") } if regionSource == "" { regionSource = "default" } - return CloudPlacement{GrantRevision: a.GrantRevision, CloudID: a.CloudID, CloudRevision: a.CloudRevision, AssignmentRevision: a.Revision, TargetID: t.ID, TargetRevision: t.Revision, TargetName: t.Name, Provider: t.Provider, Region: t.Region, RegionSource: regionSource, Platform: ref}, nil + return CloudPlacement{GrantRevision: a.GrantRevision, CloudID: a.CloudID, CloudRevision: a.CloudRevision, TargetID: t.ID, TargetRevision: t.Revision, TargetName: t.Name, Provider: t.Provider, Region: t.Region, RegionSource: regionSource, Platform: ref}, nil } // syncPlatformPlacements previews room on Loomplane Cloud for every applied // service a Cloud sync moves onto one of after's Loomplane Cloud targets, // at the size it was applied with. selector picks the services the sync // moves, as appliedCloudPlan does. -func (s *Service) syncPlatformPlacements(ctx context.Context, plan *Plan, bindings []*Binding, after *cloudprofiles.Assignment, selector string) (map[string]CloudPlacement, error) { +func (s *Service) syncPlatformPlacements(ctx context.Context, plan *Plan, bindings []*Binding, after *cloudprofiles.ProjectCloud, selector string) (map[string]CloudPlacement, error) { out := map[string]CloudPlacement{} if after == nil { return out, nil diff --git a/internal/planning/platform_targets_test.go b/internal/planning/platform_targets_test.go index 72d17433c..16a9fa620 100644 --- a/internal/planning/platform_targets_test.go +++ b/internal/planning/platform_targets_test.go @@ -31,8 +31,8 @@ func (f *fakePlacer) Preview(_ context.Context, req platformcloud.Request) (*pla // platformAssignment is an environment assigned to the platform-owned // Loomplane Cloud with one region target, fra. -func platformAssignment() *cloudprofiles.Assignment { - return &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud_platform", CloudRevision: 1, Revision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{ +func platformAssignment() *cloudprofiles.ProjectCloud { + return &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud_platform", CloudRevision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{ {ID: "target_fra", OrgID: "org", CloudID: "cloud_platform", Name: "fra", DisplayName: "Frankfurt", Runtime: platformcloud.RuntimePlatform, Provider: platformcloud.RuntimePlatform, Region: "fra", Revision: 1}, }} } diff --git a/internal/planning/server_pools_test.go b/internal/planning/server_pools_test.go index 94bd07d7c..164947c62 100644 --- a/internal/planning/server_pools_test.go +++ b/internal/planning/server_pools_test.go @@ -26,7 +26,7 @@ func TestPoolServerResourceDefaultsAndBounds(t *testing.T) { } } func TestPoolTargetSelectsRuntimeAndRemainsStable(t *testing.T) { - assigned := &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud", CloudRevision: 1, Revision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", CloudID: "cloud", Name: "shared", Provider: "server", Runtime: "server", PoolID: "pool", Revision: 1}}} + assigned := &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud", CloudRevision: 1, GrantRevision: 1, Targets: []cloudprofiles.Target{{ID: "target", OrgID: "org", CloudID: "cloud", Name: "shared", Provider: "server", Runtime: "server", PoolID: "pool", Revision: 1}}} options := []ConnectionOption{{ID: "runtime", Cloud: "server", Ready: true, Pooled: true, Details: map[string]string{"docker_id": "daemon", "architecture": "amd64"}}} m := parse(t, "version: 1\nservices:\n web: {source: cmd/api, cloud_target: shared}\n") pool := &cloudinfra.Placement{PoolID: "pool", PoolRevision: 3, ServerID: "host", ServerRevision: 2, ConnectionID: "runtime", ConnectionGeneration: 1, CPUMillis: 1000, MemoryBytes: 512 << 20} diff --git a/internal/planning/service.go b/internal/planning/service.go index cc9560496..e6d042a4b 100644 --- a/internal/planning/service.go +++ b/internal/planning/service.go @@ -24,7 +24,6 @@ import ( "github.com/xraph/loomplane/internal/metering" "github.com/xraph/loomplane/internal/orchestration" "github.com/xraph/loomplane/internal/page" - "github.com/xraph/loomplane/internal/platformcloud" "github.com/xraph/loomplane/internal/projects" "github.com/xraph/loomplane/internal/recipes" "github.com/xraph/loomplane/internal/security" @@ -853,46 +852,33 @@ func (s *Service) compute(ctx context.Context, plan *Plan) (*Result, string, err resolutionManifest, needs, resolutionErr := cloudResolutionManifest(rev.Manifest, Input{Environment: plan.Environment, Graph: g, Bindings: bindings, Held: held, Only: loaded.only}) // A composed resource on one of the Cloud's targets is placed there too. composed := composedResources(rev.Manifest, plan.Environment, s.kinds) - var assignment *cloudprofiles.Assignment + var assignment *cloudprofiles.ProjectCloud // composedLookup says only composed resources asked for the Cloud. composedLookup := false if resolutionErr == nil && (needs.Explicit || needs.Fallback || len(composed) > 0) && s.cloudProfiles != nil { composedLookup = !needs.Explicit && !needs.Fallback - assignment, resolutionErr = s.cloudProfiles.Resolve(ctx, plan.OrgID, plan.ProjectID, plan.EnvironmentID) + // Every environment resolves through the project's default Cloud. + assignment, resolutionErr = s.cloudProfiles.ResolveCloud(ctx, plan.OrgID, plan.ProjectID, "") // A revoked grant only matters to services that ask for the Cloud. if !needs.Explicit && errors.Is(resolutionErr, cloudprofiles.ErrNotFound) { assignment, resolutionErr = nil, nil } - if resolutionErr == nil && assignment != nil && (assignment.OrgID != plan.OrgID || assignment.ProjectID != plan.ProjectID || assignment.EnvironmentID != plan.EnvironmentID) { - resolutionErr = fmt.Errorf("cloud assignment is outside this organization, project or environment scope") + if resolutionErr == nil && assignment != nil && (assignment.OrgID != plan.OrgID || assignment.ProjectID != plan.ProjectID) { + resolutionErr = fmt.Errorf("the project's default Cloud is outside this organization or project") } } intents := map[string]*CapacityIntent{} locationSelections := map[string]locationSelection{} var placements map[string]CloudPlacement var resolved *manifest.Manifest + var named map[string]*cloudprofiles.ProjectCloud if resolutionErr == nil { - var pools map[string]*cloudinfra.Placement - var poolErr error - constrained := false - for _, svc := range resolutionManifest.Services { - constrained = constrained || svc.For(plan.Environment, resolutionManifest.Defaults).Placement != nil - } - if constrained { - pools, poolErr = s.resolvePoolsWithLocationInput(ctx, plan, resolutionManifest, assignment, bindings, options, needs.Held, locationSelections, Input{Graph: g, Chosen: chosen}, intents) - } else { - pools, poolErr = s.resolvePools(ctx, plan, resolutionManifest, assignment, bindings, options, needs.Held, intents) - } - var platform map[string]*platformcloud.Ref - if poolErr == nil { - platform, poolErr = s.resolvePlatform(ctx, plan, resolutionManifest, assignment, needs.Held) - } - if poolErr != nil { - resolutionErr = poolErr - } else { - resolved, placements, resolutionErr = resolveCloudPlacements(resolutionManifest, plan.Environment, assignment, options, pools, platform, needs.Held, intents) - } + named, resolutionErr = s.namedClouds(ctx, plan, needs) + } + if resolutionErr == nil { + resolved, placements, resolutionErr = s.resolveAcrossClouds(ctx, plan, resolutionManifest, assignment, named, needs, bindings, options, locationSelections, Input{Graph: g, Chosen: chosen}, intents) } + clouds := cloudsByID(assignment, named) for name, selection := range locationSelections { if pin, ok := placements[name]; ok { pin.LocationReview = selection.Review @@ -930,7 +916,8 @@ func (s *Service) compute(ctx context.Context, plan *Plan) (*Result, string, err var placementErr *CloudPlacementError switch { case errors.As(resolutionErr, &placementErr): - finding = Finding{Code: placementErr.Code, Subject: ServiceSubject, Name: strings.TrimSuffix(strings.TrimPrefix(placementErr.Path, "services."), ".cloud_tags"), Path: placementErr.Path, Message: placementErr.Message} + service, _, _ := strings.Cut(strings.TrimPrefix(placementErr.Path, "services."), ".") + finding = Finding{Code: placementErr.Code, Subject: ServiceSubject, Name: service, Path: placementErr.Path, Message: placementErr.Message} if strings.HasPrefix(placementErr.Path, "database_gateway.") { finding.Name = dbGatewayName } @@ -951,7 +938,7 @@ func (s *Service) compute(ctx context.Context, plan *Plan) (*Result, string, err var moves map[string]Action var moveProblems []Finding if len(locationSelections) > 0 { - moves, moveProblems = appliedPoolMoves(bindings, assignment, options, s.providers, placements, routes, locationSelections) + moves, moveProblems = appliedPoolMoves(bindings, clouds, options, s.providers, placements, routes, locationSelections) } native, nativeErr := nativeMoves(ctx, s.nativeFallbacks, plan.OrgID, plan.EnvironmentID, bindings) if nativeErr != nil { @@ -976,7 +963,7 @@ func (s *Service) compute(ctx context.Context, plan *Plan) (*Result, string, err }) } if resolutionErr == nil && len(locationSelections) == 0 && poolRelocation(bindings, placements) { - result = appliedCloudPlan(bindings, assignment, "", options, s.providers, placements, routes) + result = appliedCloudPlanChoosing(bindings, clouds, "", options, s.providers, placements, nil, routes) planRelease(Input{Environment: plan.Environment, Manifest: resolved, Providers: s.providers}, result) } // A rollback changes only services' code and settings, before anything diff --git a/internal/planning/service_test.go b/internal/planning/service_test.go index 26f8f0507..f1fcd807a 100644 --- a/internal/planning/service_test.go +++ b/internal/planning/service_test.go @@ -269,18 +269,18 @@ func (edgeClouds) All(context.Context, string) ([]*connections.Connection, error return out, nil } -// failingResolver can't read the environment's assignment. +// failingResolver can't read the project's Clouds. type failingResolver struct{} -func (failingResolver) Resolve(context.Context, string, string, string) (*cloudprofiles.Assignment, error) { - return nil, errors.New("cloud assignments are unavailable") +func (failingResolver) ResolveCloud(context.Context, string, string, string) (*cloudprofiles.ProjectCloud, error) { + return nil, errors.New("project Clouds are unavailable") } // edgeService plans doc as a catalog plan in an environment assigned // cloud_1, whose one target is reached through targets. func edgeService(t *testing.T, doc string, targets ...cloudprofiles.Target) (*Service, *Plan, *targetResolver) { t.Helper() - resolver := &targetResolver{assignment: &cloudprofiles.Assignment{OrgID: "org", ProjectID: "project", EnvironmentID: "env", CloudID: "cloud_1", CloudRevision: 2, Revision: 3, GrantRevision: 4, Targets: targets}} + resolver := &targetResolver{assignment: &cloudprofiles.ProjectCloud{OrgID: "org", ProjectID: "project", CloudID: "cloud_1", CloudRevision: 2, GrantRevision: 4, Targets: targets}} service := NewService(Deps{ Store: catalogStore{}, Manifests: catalogManifest{revision: &manifests.Revision{Manifest: parse(t, doc)}}, Providers: providers.Registry(), Connections: edgeClouds{}, Kinds: recipestest.Registry(t), CloudProfiles: resolver, @@ -300,7 +300,7 @@ func TestCreatePlanPlacesComposedResourceOnTheMatchingCloudTarget(t *testing.T) if resolver.calls != 1 { t.Fatalf("resolved the assignment %d times", resolver.calls) } - want := CloudPlacement{GrantRevision: 4, CloudID: "cloud_1", CloudRevision: 2, AssignmentRevision: 3, TargetID: "t1", TargetRevision: 5, TargetName: "edge-host", Provider: "server", ConnectionID: targetA, + want := CloudPlacement{GrantRevision: 4, CloudID: "cloud_1", CloudRevision: 2, TargetID: "t1", TargetRevision: 5, TargetName: "edge-host", Provider: "server", ConnectionID: targetA, AccountIdentity: connections.AccountIdentity(connections.Server, "", edgeDetails(targetA)), RegionSource: "default"} if want.AccountIdentity == "" { t.Fatal("fixture account isn't verified") @@ -399,7 +399,7 @@ func TestCreatePlanReportsACloudLookupFailureOnTheComposedResource(t *testing.T) if result.Executable || len(result.Problems) != 1 { t.Fatalf("lookup failure: %+v", result) } - if f := result.Problems[0]; f.Code != "cloud-target" || f.Subject != ResourceSubject || f.Name != "edge" || f.Path != "resources.edge.target" || f.Message != "cloud assignments are unavailable" { + if f := result.Problems[0]; f.Code != "cloud-target" || f.Subject != ResourceSubject || f.Name != "edge" || f.Path != "resources.edge.target" || f.Message != "project Clouds are unavailable" { t.Fatalf("finding: %+v", f) } diff --git a/internal/publicplan/plan.go b/internal/publicplan/plan.go index 17b43628a..56ef077d0 100644 --- a/internal/publicplan/plan.go +++ b/internal/publicplan/plan.go @@ -170,7 +170,6 @@ type CloudPlacement struct { GrantRevision int64 `json:"grant_revision,omitempty"` CloudID string `json:"cloud_id"` CloudRevision int64 `json:"cloud_revision"` - AssignmentRevision int64 `json:"assignment_revision"` Default bool `json:"default,omitempty"` TargetID string `json:"target_id"` TargetRevision int64 `json:"target_revision"` @@ -244,15 +243,14 @@ type CapacityDemand struct { } type CapacityIntent struct { - Demand CapacityDemand `json:"demand"` - Template cloudinfra.PoolExpansionPolicy `json:"template"` - TemplateHash string `json:"template_hash"` - CommitSHA string `json:"commit_sha"` - AssignmentRevision int64 `json:"assignment_revision"` - CloudRevision int64 `json:"cloud_revision"` - TargetRevision int64 `json:"target_revision"` - GrantRevision int64 `json:"grant_revision"` - TargetName string `json:"target_name"` + Demand CapacityDemand `json:"demand"` + Template cloudinfra.PoolExpansionPolicy `json:"template"` + TemplateHash string `json:"template_hash"` + CommitSHA string `json:"commit_sha"` + CloudRevision int64 `json:"cloud_revision"` + TargetRevision int64 `json:"target_revision"` + GrantRevision int64 `json:"grant_revision"` + TargetName string `json:"target_name"` } type CloudCompensation struct { @@ -308,7 +306,7 @@ func projectCloudPlacement(v *planning.CloudPlacement) *CloudPlacement { if v == nil { return nil } - return &CloudPlacement{AccountIdentity: v.AccountIdentity, Allocation: v.Allocation, PoolID: v.PoolID, PoolRevision: v.PoolRevision, ServerID: v.ServerID, ServerRevision: v.ServerRevision, ConnectionGeneration: v.ConnectionGeneration, CPUMillis: v.CPUMillis, MemoryBytes: v.MemoryBytes, GPUKind: v.GPUKind, GPUs: v.GPUs, GrantRevision: v.GrantRevision, CloudID: v.CloudID, CloudRevision: v.CloudRevision, AssignmentRevision: v.AssignmentRevision, Default: v.Default, TargetID: v.TargetID, TargetRevision: v.TargetRevision, TargetName: v.TargetName, Provider: v.Provider, ConnectionID: v.ConnectionID, Region: v.Region, RegionSource: v.RegionSource} + return &CloudPlacement{AccountIdentity: v.AccountIdentity, Allocation: v.Allocation, PoolID: v.PoolID, PoolRevision: v.PoolRevision, ServerID: v.ServerID, ServerRevision: v.ServerRevision, ConnectionGeneration: v.ConnectionGeneration, CPUMillis: v.CPUMillis, MemoryBytes: v.MemoryBytes, GPUKind: v.GPUKind, GPUs: v.GPUs, GrantRevision: v.GrantRevision, CloudID: v.CloudID, CloudRevision: v.CloudRevision, Default: v.Default, TargetID: v.TargetID, TargetRevision: v.TargetRevision, TargetName: v.TargetName, Provider: v.Provider, ConnectionID: v.ConnectionID, Region: v.Region, RegionSource: v.RegionSource} } func projectExistingResourceConfig(v *planning.ExistingResourceConfig) *ExistingResourceConfig { @@ -352,7 +350,7 @@ func projectCapacityIntent(v *planning.CapacityIntent) *CapacityIntent { } d := v.Demand demand := CapacityDemand{OrgID: d.OrgID, CloudID: d.CloudID, PoolID: d.PoolID, TargetID: d.TargetID, ProjectID: d.ProjectID, EnvironmentID: d.EnvironmentID, PlanID: d.PlanID, Service: d.Service, Architecture: d.Architecture, StickyServerID: d.StickyServerID, Resources: d.Resources, LocalData: d.LocalData, PolicyRevision: d.PolicyRevision, IntentHash: d.IntentHash} - return &CapacityIntent{Demand: demand, Template: v.Template, TemplateHash: v.TemplateHash, CommitSHA: v.CommitSHA, AssignmentRevision: v.AssignmentRevision, CloudRevision: v.CloudRevision, TargetRevision: v.TargetRevision, GrantRevision: v.GrantRevision, TargetName: v.TargetName} + return &CapacityIntent{Demand: demand, Template: v.Template, TemplateHash: v.TemplateHash, CommitSHA: v.CommitSHA, CloudRevision: v.CloudRevision, TargetRevision: v.TargetRevision, GrantRevision: v.GrantRevision, TargetName: v.TargetName} } func projectCloudCompensation(v *planning.CloudCompensation) *CloudCompensation { diff --git a/pkg/client/client.go b/pkg/client/client.go index b0e9d8525..f13dae6da 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -403,19 +403,23 @@ type NewResource struct { // anything else left out is inherited or comes from analysis. EnabledIn, // Only and NeededBy work as they do for a resource. type NewService struct { - Name string `json:"name"` - Source string `json:"source"` - Repo string `json:"repo,omitempty"` - Kind string `json:"kind,omitempty"` - Provider string `json:"provider,omitempty"` - Region string `json:"region,omitempty"` - Target string `json:"target,omitempty"` - Port int `json:"port,omitempty"` - Public *bool `json:"public,omitempty"` - Needs []string `json:"needs,omitempty"` - NeededBy []string `json:"needed_by,omitempty"` - EnabledIn string `json:"enabled_in,omitempty"` - Only bool `json:"only,omitempty"` + Name string `json:"name"` + Source string `json:"source"` + Repo string `json:"repo,omitempty"` + Kind string `json:"kind,omitempty"` + // Cloud and CloudTarget put the service on a Cloud target: CloudTarget + // in the Cloud named, or the project's default Cloud. + Cloud string `json:"cloud,omitempty"` + CloudTarget string `json:"cloud_target,omitempty"` + Provider string `json:"provider,omitempty"` + Region string `json:"region,omitempty"` + Target string `json:"target,omitempty"` + Port int `json:"port,omitempty"` + Public *bool `json:"public,omitempty"` + Needs []string `json:"needs,omitempty"` + NeededBy []string `json:"needed_by,omitempty"` + EnabledIn string `json:"enabled_in,omitempty"` + Only bool `json:"only,omitempty"` } // ServiceSuggestions are the services analysis found that the manifest diff --git a/pkg/client/clouds.go b/pkg/client/clouds.go index e2170158e..243923c3a 100644 --- a/pkg/client/clouds.go +++ b/pkg/client/clouds.go @@ -48,29 +48,31 @@ type CloudTarget struct { UpdatedAt time.Time `json:"updated_at"` } -// CloudAssignment is the public Cloud API record. -type CloudAssignment struct { - GrantRevision int64 `json:"grant_revision"` - CloudRevision int64 `json:"cloud_revision"` - OrgID string `json:"org_id"` - ProjectID string `json:"project_id"` - EnvironmentID string `json:"environment_id"` - CloudID string `json:"cloud_id"` - Revision int64 `json:"revision"` - Targets []CloudTarget `json:"targets"` +// ProjectCloud is one Cloud as one project may use it. +type ProjectCloud struct { + GrantRevision int64 `json:"grant_revision"` + CloudRevision int64 `json:"cloud_revision"` + OrgID string `json:"org_id"` + ProjectID string `json:"project_id"` + CloudID string `json:"cloud_id"` + // Default marks the project's default Cloud. + Default bool `json:"default"` + Targets []CloudTarget `json:"targets"` // DefaultPlacement is present when the project's grant covers the whole Cloud. DefaultPlacement *CloudPlacement `json:"default_placement,omitempty"` } // CloudChangeInput is the public Cloud API record. type CloudChangeInput struct { - Runtime string `json:"runtime,omitempty"` - PoolID string `json:"pool_id,omitempty"` - Revision int64 `json:"revision"` - CloudID string `json:"cloud_id"` - TargetID string `json:"target_id,omitempty"` - EnvironmentID string `json:"environment_id,omitempty"` - // Default reviews a Cloud default switch; Revision is then the Cloud's. + Runtime string `json:"runtime,omitempty"` + PoolID string `json:"pool_id,omitempty"` + Revision int64 `json:"revision"` + CloudID string `json:"cloud_id"` + TargetID string `json:"target_id,omitempty"` + // ProjectDefault reviews making CloudID the project's default Cloud; + // Revision is then the current default's grant revision, zero for none. + ProjectDefault bool `json:"project_default,omitempty"` + // Default reviews a Cloud default placement switch; Revision is then the Cloud's. Default bool `json:"default,omitempty"` Provider string `json:"provider,omitempty"` ConnectionID string `json:"connection_id,omitempty"` @@ -123,21 +125,21 @@ type CloudSyncRoute struct { // CloudPreview is the public Cloud API record. type CloudPreview struct { - ID string `json:"id" forge:"id"` - OrgID string `json:"org_id"` - ProjectID string `json:"project_id"` - Revision string `json:"revision"` - Input CloudChangeInput `json:"input"` - Before *CloudTarget `json:"before,omitempty"` - After *CloudTarget `json:"after,omitempty"` - BeforeDefault *CloudPlacement `json:"before_default,omitempty"` - AfterDefault *CloudPlacement `json:"after_default,omitempty"` - BeforeAssignment *CloudAssignment `json:"before_assignment,omitempty"` - AfterAssignment *CloudAssignment `json:"after_assignment,omitempty"` - Environments []CloudEnvironmentChange `json:"environments"` - Blockers []string `json:"blockers"` - Reverts string `json:"reverts,omitempty"` - CreatedAt time.Time `json:"created_at"` + ID string `json:"id" forge:"id"` + OrgID string `json:"org_id"` + ProjectID string `json:"project_id"` + Revision string `json:"revision"` + Input CloudChangeInput `json:"input"` + Before *CloudTarget `json:"before,omitempty"` + After *CloudTarget `json:"after,omitempty"` + BeforeDefault *CloudPlacement `json:"before_default,omitempty"` + AfterDefault *CloudPlacement `json:"after_default,omitempty"` + BeforeCloud *ProjectCloud `json:"before_cloud,omitempty"` + AfterCloud *ProjectCloud `json:"after_cloud,omitempty"` + Environments []CloudEnvironmentChange `json:"environments"` + Blockers []string `json:"blockers"` + Reverts string `json:"reverts,omitempty"` + CreatedAt time.Time `json:"created_at"` } // CloudSync is the public Cloud API record. @@ -197,11 +199,17 @@ type CloudUpdateTargetInput struct { Revision int64 `json:"revision"` } -type EnvironmentCloud struct { - Assignment *CloudAssignment `json:"assignment"` - Revision int64 `json:"revision"` +// DefaultCloud is the Cloud every environment of a project uses unless a +// service names another. Cloud is nil when the project has none. +type DefaultCloud struct { + ProjectID string `json:"project_id"` + Cloud *ProjectCloud `json:"cloud"` + Revision int64 `json:"revision"` } -type EnvironmentCloudInput struct { + +// DefaultCloudInput reviews making CloudID the project's default Cloud, or +// with no CloudID, leaving the project without one. +type DefaultCloudInput struct { CloudID string `json:"cloud_id"` Revision int64 `json:"revision"` } @@ -283,14 +291,14 @@ func (c *Client) UpdateCloudTarget(ctx context.Context, project, cloud, id strin func (c *Client) DeleteCloudTarget(ctx context.Context, project, cloud, id string) error { return c.do(ctx, http.MethodDelete, targetPath(project, cloud)+"/"+esc(id), nil, nil) } -func (c *Client) EnvironmentCloud(ctx context.Context, project, environment string) (*EnvironmentCloud, error) { - var out EnvironmentCloud - err := c.do(ctx, http.MethodGet, cloudPath(project)+"/environments/"+esc(environment)+"/cloud", nil, &out) +func (c *Client) DefaultCloud(ctx context.Context, project string) (*DefaultCloud, error) { + var out DefaultCloud + err := c.do(ctx, http.MethodGet, cloudPath(project)+"/default-cloud", nil, &out) return &out, err } -func (c *Client) PreviewEnvironmentCloud(ctx context.Context, project, environment string, in EnvironmentCloudInput) (*CloudPreview, error) { +func (c *Client) PreviewDefaultCloud(ctx context.Context, project string, in DefaultCloudInput) (*CloudPreview, error) { var out CloudPreview - err := c.do(ctx, http.MethodPost, cloudPath(project)+"/environments/"+esc(environment)+"/cloud/preview", in, &out) + err := c.do(ctx, http.MethodPost, cloudPath(project)+"/default-cloud/preview", in, &out) return &out, err } func (c *Client) PreviewCloudChange(ctx context.Context, project string, in CloudChangeInput) (*CloudPreview, error) { @@ -384,6 +392,8 @@ type CloudProjectGrant struct { TargetIDs []string `json:"target_ids"` Revision int64 `json:"revision"` Revoked bool `json:"revoked"` + // Default marks the project's default Cloud. + Default bool `json:"default"` } func (c *Client) OrganizationClouds(ctx context.Context) ([]Cloud, error) { return c.Clouds(ctx, "") } diff --git a/pkg/client/clouds_test.go b/pkg/client/clouds_test.go index eb2759839..1c7f27d2b 100644 --- a/pkg/client/clouds_test.go +++ b/pkg/client/clouds_test.go @@ -9,16 +9,16 @@ import ( "time" ) -func TestCloudClientPreservesNullableAssignmentAndGeneration(t *testing.T) { +func TestCloudClientReadsAProjectWithNoDefaultCloud(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/api/v1/projects/p/environments/env/cloud" { + if r.URL.Path != "/api/v1/projects/p/default-cloud" { t.Error(r.URL.Path) } - _, _ = w.Write([]byte(`{"assignment":null,"revision":4}`)) + _, _ = w.Write([]byte(`{"project_id":"p","cloud":null,"revision":0}`)) })) defer srv.Close() - value, err := New(srv.URL, "key").EnvironmentCloud(t.Context(), "p", "env") - if err != nil || value.Assignment != nil || value.Revision != 4 { + value, err := New(srv.URL, "key").DefaultCloud(t.Context(), "p") + if err != nil || value.Cloud != nil || value.Revision != 0 || value.ProjectID != "p" { t.Fatalf("%+v %v", value, err) } } diff --git a/pkg/manifest/cloud_field_test.go b/pkg/manifest/cloud_field_test.go new file mode 100644 index 000000000..2354f4622 --- /dev/null +++ b/pkg/manifest/cloud_field_test.go @@ -0,0 +1,54 @@ +package manifest + +import ( + "strings" + "testing" +) + +func TestCloudFieldPrecedence(t *testing.T) { + m, err := Parse([]byte(`version: 1 +services: + trainer: + source: trainer + cloud: GPU Lab + cloud_target: a100 + environments: + preview: {cloud_target: eu-run} + staging: {cloud: GPU Lab EU} + nightly: {cloud: GPU Lab EU, cloud_tags: [small]} +`)) + if err != nil { + t.Fatal(err) + } + s := m.Services["trainer"] + for env, want := range map[string]struct{ cloud, target, tags string }{ + // The service's own Cloud and target. + "production": {"GPU Lab", "a100", ""}, + // A target named without a Cloud is in the project's default Cloud. + "preview": {"", "eu-run", ""}, + // A Cloud alone keeps the service's target, in that Cloud. + "staging": {"GPU Lab EU", "a100", ""}, + "nightly": {"GPU Lab EU", "", "small"}, + } { + got := s.For(env, m.Defaults) + if got.Cloud != want.cloud || got.CloudTarget != want.target || strings.Join(got.CloudTags, ",") != want.tags { + t.Errorf("%s: cloud %q target %q tags %v, want %+v", env, got.Cloud, got.CloudTarget, got.CloudTags, want) + } + } +} + +func TestCloudFieldValidation(t *testing.T) { + for doc, want := range map[string]string{ + "services:\n web: {source: web, cloud: GPU Lab, provider: vercel}\n": "services.web.cloud", + "services:\n web: {source: web, cloud: ' GPU Lab'}\n": "services.web.cloud", + "services:\n web:\n source: web\n environments:\n staging: {cloud: Lab, target: conn_1}\n": "services.web.environments.staging.cloud", + } { + _, err := Parse([]byte("version: 1\n" + doc)) + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%q: %v, want a finding at %s", doc, err, want) + } + } + if _, err := Parse([]byte("version: 1\nservices:\n web: {source: web, cloud: GPU Lab}\n")); err != nil { + t.Errorf("a Cloud alone is its default placement: %v", err) + } +} diff --git a/pkg/manifest/edit.go b/pkg/manifest/edit.go index 4a5ff9e37..122d5e780 100644 --- a/pkg/manifest/edit.go +++ b/pkg/manifest/edit.go @@ -29,7 +29,10 @@ type Placement struct { Environment string `json:"environment,omitempty"` Provider *string `json:"provider,omitempty"` Region *string `json:"region,omitempty"` - CloudTarget *string `json:"cloud_target,omitempty"` + // Cloud names the Cloud cloud_target or cloud_tags resolve in; an + // empty value restores the project's default Cloud. + Cloud *string `json:"cloud,omitempty"` + CloudTarget *string `json:"cloud_target,omitempty"` // CloudTags replaces the tag list; an empty list restores inheritance. // Clear cloud_target in the same edit when switching to tags. CloudTags *[]string `json:"cloud_tags,omitempty"` @@ -60,11 +63,11 @@ func WithPlacement(doc []byte, p Placement) ([]byte, error) { return nil, err } if !slices.Contains([]string{"services", "resources", "gateways"}, p.Section) || - (p.Commands == nil && p.Vercel == nil && p.CloudSQLNetwork == nil && p.CloudTarget == nil && p.CloudTags == nil && p.Provider == nil && p.Region == nil && p.Enabled == nil && p.Target == nil && p.HealthPath == nil && p.Endpoint == nil && p.Build == nil && p.Scale == nil && p.Size == nil) { + (p.Commands == nil && p.Vercel == nil && p.CloudSQLNetwork == nil && p.Cloud == nil && p.CloudTarget == nil && p.CloudTags == nil && p.Provider == nil && p.Region == nil && p.Enabled == nil && p.Target == nil && p.HealthPath == nil && p.Endpoint == nil && p.Build == nil && p.Scale == nil && p.Size == nil) { return nil, fmt.Errorf("%w: name a service, resource or gateway and its placement changes", ErrInvalid) } - if p.Section != "services" && (p.Commands != nil || p.Vercel != nil || p.CloudSQLNetwork != nil || p.CloudTarget != nil || p.CloudTags != nil || p.Target != nil || p.HealthPath != nil || p.Endpoint != nil || p.Build != nil || p.Scale != nil || p.Size != nil) { - return nil, fmt.Errorf("%w: cloud_sql_network, cloud_target, cloud_tags, target, endpoint, health_path, build, scale and size edits need a service", ErrInvalid) + if p.Section != "services" && (p.Commands != nil || p.Vercel != nil || p.CloudSQLNetwork != nil || p.Cloud != nil || p.CloudTarget != nil || p.CloudTags != nil || p.Target != nil || p.HealthPath != nil || p.Endpoint != nil || p.Build != nil || p.Scale != nil || p.Size != nil) { + return nil, fmt.Errorf("%w: cloud_sql_network, cloud, cloud_target, cloud_tags, target, endpoint, health_path, build, scale and size edits need a service", ErrInvalid) } if p.Environment == "" && p.Section != "services" && p.Enabled != nil { return nil, fmt.Errorf("%w: enabled on %s needs an environment", ErrInvalid, p.Section) @@ -117,7 +120,7 @@ func WithPlacement(doc []byte, p Placement) ([]byte, error) { for _, field := range []struct { key string value *string - }{{"cloud_target", p.CloudTarget}, {"provider", p.Provider}, {"region", p.Region}, {"target", p.Target}, {"health_path", p.HealthPath}} { + }{{"cloud", p.Cloud}, {"cloud_target", p.CloudTarget}, {"provider", p.Provider}, {"region", p.Region}, {"target", p.Target}, {"health_path", p.HealthPath}} { if field.value != nil { setPlacementField(target, field.key, scalar(*field.value), *field.value == "") } @@ -646,15 +649,20 @@ func WithEnabledIn(doc []byte, section, name string, enabled map[string]bool) ([ // left empty is inherited or comes from analysis, as it does for a // service written by hand. type NewService struct { - Repo string - Source string - Kind string - Provider string - Region string - Target string - Port int - Public *bool - Needs []string + Repo string + Source string + Kind string + // Cloud and CloudTarget put the service on a Cloud target: CloudTarget + // in the Cloud named, or in the project's default when Cloud is empty. + // They can't be set with Provider or Target. + Cloud string + CloudTarget string + Provider string + Region string + Target string + Port int + Public *bool + Needs []string } // WithService adds a service to a manifest's YAML, after the ones already @@ -677,6 +685,9 @@ func WithService(doc []byte, name string, s NewService) ([]byte, error) { return nil, fmt.Errorf("%w: something is already called %s", ErrInvalid, name) } } + if (s.CloudTarget != "" || s.Cloud != "") && (s.Provider != "" || s.Target != "") { + return nil, fmt.Errorf("%w: %s runs on a Cloud target or on an account directly, not both", ErrInvalid, name) + } for _, need := range s.Needs { if need == name { return nil, fmt.Errorf("%w: %s can't need itself", ErrInvalid, name) @@ -704,6 +715,8 @@ func WithService(doc []byte, name string, s NewService) ([]byte, error) { add("repo", s.Repo) add("source", source) add("kind", s.Kind) + add("cloud", s.Cloud) + add("cloud_target", s.CloudTarget) add("provider", s.Provider) add("region", s.Region) add("target", s.Target) diff --git a/pkg/manifest/manifest.go b/pkg/manifest/manifest.go index 3467e473a..e83123d25 100644 --- a/pkg/manifest/manifest.go +++ b/pkg/manifest/manifest.go @@ -182,9 +182,15 @@ type Settings struct { CapacityMode string `json:"capacity_mode,omitempty" yaml:"capacity_mode,omitempty"` // CloudSQLNetwork is the explicit application route for PSC attachments. CloudSQLNetwork *providercontract.CloudSQLApplicationNetwork `json:"cloud_sql_network,omitempty" yaml:"cloud_sql_network,omitempty"` - // CloudTarget names a target in the environment's assigned Cloud. + // Cloud names, by name, the Cloud this service's cloud_target, + // cloud_tags or default placement resolves in: any Cloud granted to the + // project. Empty means the project's default Cloud. An environment that + // names a target also says which Cloud it's in, so an override with a + // target and no cloud goes back to the default Cloud. + Cloud string `json:"cloud,omitempty" yaml:"cloud,omitempty"` + // CloudTarget names a target in the service's Cloud. CloudTarget string `json:"cloud_target,omitempty" yaml:"cloud_target,omitempty"` - // CloudTags select the one target in the assigned Cloud that carries + // CloudTags select the one target in the service's Cloud that carries // every tag. Planning fails rather than guessing when none or several do. CloudTags []string `json:"cloud_tags,omitempty" yaml:"cloud_tags,omitempty"` Provider string `json:"provider,omitempty" yaml:"provider,omitempty"` @@ -835,6 +841,12 @@ func checkSettings(add func(string, string, ...any), path string, s Settings) { add(path+".cloud_sql_network", "requires a canonical VPC and regional subnet in the consumer project") } } + if s.Cloud != "" && (len(s.Cloud) > 64 || strings.TrimSpace(s.Cloud) != s.Cloud) { + add(path+".cloud", "must be a Cloud's name, at most 64 characters with no surrounding spaces") + } + if s.Cloud != "" && (s.Provider != "" || s.Target != "") { + add(path+".cloud", "can't be set with provider or target; a service runs on a Cloud or on an account directly") + } if s.CloudTarget != "" && (len(s.CloudTarget) > 48 || !cloudTargetRE.MatchString(s.CloudTarget)) { add(path+".cloud_target", "must be a lowercase target slug of at most 48 characters") } @@ -1164,12 +1176,16 @@ func (s Service) For(env string, d Defaults) Settings { out.Endpoint = nil } out.Provider, out.Region = override(out.Provider, out.Region, o.Provider, o.Region, d) - // An environment names its target one way, replacing the service's. + // An environment names its target one way, replacing the service's, + // and in the Cloud it names: none is the project's default. if o.CloudTarget != "" { - out.CloudTarget, out.CloudTags = o.CloudTarget, nil + out.Cloud, out.CloudTarget, out.CloudTags = o.Cloud, o.CloudTarget, nil } if len(o.CloudTags) > 0 { - out.CloudTarget, out.CloudTags = "", o.CloudTags + out.Cloud, out.CloudTarget, out.CloudTags = o.Cloud, "", o.CloudTags + } + if o.Cloud != "" { + out.Cloud = o.Cloud } if o.Target != "" { out.Target = o.Target diff --git a/pkg/manifest/schema.json b/pkg/manifest/schema.json index f079f6d56..1b31408c7 100644 --- a/pkg/manifest/schema.json +++ b/pkg/manifest/schema.json @@ -680,8 +680,14 @@ "description": "Managed workload reservation mode. Guaranteed reserves your reviewed replica maximum; best effort grants no fleet expansion.", "enum": ["guaranteed", "best_effort"] }, + "cloud": { + "description": "Name of the Cloud cloud_target, cloud_tags or the default placement resolve in, any Cloud granted to the project. Omit for the project's default Cloud.", + "type": "string", + "minLength": 1, + "maxLength": 64 + }, "cloud_target": { - "description": "Named target in this environment's assigned Cloud.", + "description": "Named target in the service's Cloud: the one cloud names, or the project's default Cloud.", "type": "string", "maxLength": 48, "pattern": "^[a-z][a-z0-9]*(-[a-z0-9]+)*$" diff --git a/tests/integration/azure_test.go b/tests/integration/azure_test.go index ec97046fb..4b2b74b05 100644 --- a/tests/integration/azure_test.go +++ b/tests/integration/azure_test.go @@ -12,7 +12,6 @@ import ( "github.com/xraph/loomplane/internal/clouds/azure" "github.com/xraph/loomplane/internal/clouds/azure/azuretest" "github.com/xraph/loomplane/internal/planning" - apiclient "github.com/xraph/loomplane/pkg/client" ) // TestDeploy_anAPIOnAzureContainerAppsThroughACloudTarget connects an @@ -119,19 +118,7 @@ func TestDeploy_anAPIOnAzureContainerAppsThroughACloudTarget(t *testing.T) { cloudprofiles.CreateTargetInput{Name: "backend", Provider: "azure-container-apps", ConnectionID: conn.ID, Region: "westeurope"}, &target) c.must(http.StatusCreated, http.MethodPost, base+"/clouds/"+cloud.ID+"/targets", cloudprofiles.CreateTargetInput{Name: "data", Provider: "azure-database", ConnectionID: conn.ID, Region: "westeurope"}, &data) - var envs struct{ Environments []struct{ ID, Name string } } - c.must(http.StatusOK, http.MethodGet, base+"/environments", nil, &envs) - env := "" - for _, e := range envs.Environments { - if e.Name == "production" { - env = e.ID - } - } - var preview cloudprofiles.Preview - c.must(http.StatusOK, http.MethodPost, base+"/environments/"+env+"/cloud/preview", apiclient.EnvironmentCloudInput{CloudID: cloud.ID}, &preview) - if got := waitCloudAPI(t, c, base, applyCloudAPI(t, c, base, &preview, "assign-azure").ID); got.Status != cloudprofiles.SyncSucceeded { - t.Fatalf("assignment %+v", got) - } + makeDefaultCloudAPI(t, c, base, cloud.ID, "assign-azure") // A manifest places a resource by its provider, not a Cloud target, so // db names the data target's provider and region. diff --git a/tests/integration/capacity_planning_test.go b/tests/integration/capacity_planning_test.go index e19314608..7ea8701c6 100644 --- a/tests/integration/capacity_planning_test.go +++ b/tests/integration/capacity_planning_test.go @@ -47,7 +47,7 @@ func futurePlanWith(t *testing.T, f *poolFixture, id, env string, change func(*p t.Helper() req := f.request(env, "api") template := cloudinfra.PoolExpansionPolicy{PoolID: "pool", ConnectionID: "runtime-1", Region: "region", Architecture: "amd64", Image: "ubuntu", AllowedSizes: []string{"small"}} - intent := &planning.CapacityIntent{ProviderPin: cloudinfra.CapacityTemplatePin{ConnectionGeneration: 1, AccountID: "runtime-1"}, Template: template, CommitSHA: "commit", AssignmentRevision: 1, CloudRevision: 1, TargetRevision: 1, GrantRevision: 1, TargetName: "shared", Demand: cloudinfra.CapacityDemand{OrgID: "org", CloudID: "cloud", PoolID: "pool", TargetID: "pool-target", ProjectID: req.ProjectID, EnvironmentID: env, PlanID: id, Service: "api", Architecture: "amd64", PolicyRevision: 1, Resources: cloudinfra.ResourceVector{CPUMillis: 2000, MemoryBytes: 512 << 20}}} + intent := &planning.CapacityIntent{ProviderPin: cloudinfra.CapacityTemplatePin{ConnectionGeneration: 1, AccountID: "runtime-1"}, Template: template, CommitSHA: "commit", CloudRevision: 1, TargetRevision: 1, GrantRevision: 1, TargetName: "shared", Demand: cloudinfra.CapacityDemand{OrgID: "org", CloudID: "cloud", PoolID: "pool", TargetID: "pool-target", ProjectID: req.ProjectID, EnvironmentID: env, PlanID: id, Service: "api", Architecture: "amd64", PolicyRevision: 1, Resources: cloudinfra.ResourceVector{CPUMillis: 2000, MemoryBytes: 512 << 20}}} if change != nil { change(intent) } @@ -257,7 +257,7 @@ func (deployOnlyTemplateAuth) Require(_ context.Context, p security.Principal, p } func TestCapacityPlanningTemplateFit(t *testing.T) { f, _, d := expansionFixture(t, false, 0) - if _, err := f.sql.Exec(t.Context(), `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1) ON CONFLICT DO NOTHING`); err != nil { + if _, err := f.sql.Exec(t.Context(), defaultCloudSQL("org", "proj", "cloud")); err != nil { t.Fatal(err) } policy, err := f.store.GetCapacityPolicy(t.Context(), "org", "cloud") diff --git a/tests/integration/cloud_acceptance_test.go b/tests/integration/cloud_acceptance_test.go index c4610b577..3359eb8aa 100644 --- a/tests/integration/cloud_acceptance_test.go +++ b/tests/integration/cloud_acceptance_test.go @@ -145,8 +145,10 @@ func TestAcceptanceCloudAccountSwitch(t *testing.T) { t.Fatalf("live migration timed out: %s", sync.Status) return nil } + var standing apiclient.DefaultCloud + c.must(http.StatusOK, http.MethodGet, base+"/default-cloud", nil, &standing) var preview cloudprofiles.Preview - c.must(http.StatusOK, http.MethodPost, base+"/environments/"+env+"/cloud/preview", apiclient.EnvironmentCloudInput{CloudID: cloud.ID}, &preview) + c.must(http.StatusOK, http.MethodPost, base+"/default-cloud/preview", apiclient.DefaultCloudInput{CloudID: cloud.ID, Revision: standing.Revision}, &preview) if got := wait(applyCloudAPI(t, c, base, &preview, "assign-live").ID); got.Status != cloudprofiles.SyncSucceeded { t.Fatalf("assignment %s", got.Status) } diff --git a/tests/integration/cloud_api_test.go b/tests/integration/cloud_api_test.go index 35f414904..05141e717 100644 --- a/tests/integration/cloud_api_test.go +++ b/tests/integration/cloud_api_test.go @@ -161,6 +161,37 @@ func applyCloudAPI(t *testing.T, c *client, base string, preview *cloudprofiles. c.must(http.StatusAccepted, http.MethodPost, base+"/cloud-changes/apply", apiclient.ApplyCloudInput{PreviewID: preview.ID, Revision: preview.Revision, IdempotencyKey: key}, &result) return &result } + +// makeDefaultCloudAPI makes cloud the project's default Cloud through a +// reviewed change and waits for it to settle. A project's first grant is +// already its default, and then there is nothing to review: it returns nil. +// makeDefaultCloudAPI makes cloud the project's default through the reviewed +// API change, unless it already is. +func makeDefaultCloudAPI(t *testing.T, c *client, base, cloud, key string) { + t.Helper() + var current apiclient.DefaultCloud + c.must(http.StatusOK, http.MethodGet, base+"/default-cloud", nil, ¤t) + if current.Cloud != nil && current.Cloud.CloudID == cloud { + return + } + var preview cloudprofiles.Preview + c.must(http.StatusOK, http.MethodPost, base+"/default-cloud/preview", apiclient.DefaultCloudInput{CloudID: cloud, Revision: current.Revision}, &preview) + result := waitCloudAPI(t, c, base, applyCloudAPI(t, c, base, &preview, key).ID) + if result.Status != cloudprofiles.SyncSucceeded { + t.Fatalf("default Cloud change: %+v", result) + } +} + +// cloudPreviewEnvironment finds one environment's reviewed change. +func cloudPreviewEnvironment(preview *cloudprofiles.Preview, env string) *cloudprofiles.EnvironmentChange { + for i := range preview.Environments { + if preview.Environments[i].EnvironmentID == env { + return &preview.Environments[i] + } + } + return nil +} + func TestCloudAPIActualReleaseSwitchAndNextRelease(t *testing.T) { provider := newCloudAPIVercel(t) cfg, r, c, org, project := cloudAPISetup(t) @@ -198,14 +229,15 @@ func TestCloudAPIActualReleaseSwitchAndNextRelease(t *testing.T) { if env == "" { t.Fatal("production missing") } - assignment := base + "/environments/" + env + "/cloud" - var initial apiclient.EnvironmentCloud + // Creating a Cloud inside the project grants it without making it the default. + assignment := base + "/default-cloud" + var initial apiclient.DefaultCloud c.must(http.StatusOK, http.MethodGet, assignment, nil, &initial) - if initial.Assignment != nil || initial.Revision != 0 { - t.Fatalf("unassigned: %+v", initial) + if initial.Cloud != nil || initial.Revision != 0 { + t.Fatalf("no default Cloud: %+v", initial) } var preview cloudprofiles.Preview - c.must(http.StatusOK, http.MethodPost, assignment+"/preview", apiclient.EnvironmentCloudInput{CloudID: cloud.ID}, &preview) + c.must(http.StatusOK, http.MethodPost, assignment+"/preview", apiclient.DefaultCloudInput{CloudID: cloud.ID}, &preview) first := applyCloudAPI(t, c, base, &preview, "initial-assignment") if got := waitCloudAPI(t, c, base, first.ID); got.Status != cloudprofiles.SyncSucceeded { t.Fatalf("initial: %+v", got) @@ -231,7 +263,9 @@ ignore: } input := cloudprofiles.ChangeInput{CloudID: cloud.ID, TargetID: target.ID, Revision: 1, Provider: "vercel", ConnectionID: newAccount.ID} c.must(http.StatusOK, http.MethodPost, base+"/cloud-changes/preview", input, &preview) - if len(preview.Blockers) != 0 || len(preview.Environments) != 1 || preview.Environments[0].Summary.Replace != 1 { + // Every environment of the project uses its default Cloud; only + // production runs anything on the target. + if production := cloudPreviewEnvironment(&preview, env); len(preview.Blockers) != 0 || len(preview.Environments) != 2 || production == nil || production.Summary.Replace != 1 { t.Fatalf("switch review: %+v", preview) } // A private snapshot must never appear in the preview or read API. @@ -370,10 +404,15 @@ ignore: otherBase := "/api/v1/projects/" + other.ID c.must(http.StatusNotFound, http.MethodGet, otherBase+"/clouds/"+cloud.ID, nil, nil) c.must(http.StatusNotFound, http.MethodGet, otherBase+"/cloud-syncs/"+operation.ID, nil, nil) - c.must(http.StatusNotFound, http.MethodGet, otherBase+"/environments/"+env+"/cloud", nil, nil) + c.must(http.StatusNotFound, http.MethodPost, otherBase+"/default-cloud/preview", apiclient.DefaultCloudInput{CloudID: cloud.ID}, nil) var foreignCloud cloudprofiles.Profile c.must(http.StatusCreated, http.MethodPost, otherBase+"/clouds", cloudprofiles.CreateInput{Name: "Foreign"}, &foreignCloud) - c.must(http.StatusNotFound, http.MethodPost, assignment+"/preview", apiclient.EnvironmentCloudInput{CloudID: foreignCloud.ID, Revision: 1}, nil) + var standing apiclient.DefaultCloud + c.must(http.StatusOK, http.MethodGet, assignment, nil, &standing) + if standing.Cloud == nil || standing.Cloud.CloudID != cloud.ID { + t.Fatalf("default Cloud: %+v", standing) + } + c.must(http.StatusNotFound, http.MethodPost, assignment+"/preview", apiclient.DefaultCloudInput{CloudID: foreignCloud.ID, Revision: standing.Revision}, nil) c.must(http.StatusBadRequest, http.MethodGet, base+"/cloud-syncs?before=bad-cursor", nil, nil) input.Revision = 1 c.must(http.StatusConflict, http.MethodPost, base+"/cloud-changes/preview", input, nil) @@ -458,7 +497,7 @@ func TestCloudAPIStartupAndPeriodicOutboxRecovery(t *testing.T) { ID string `json:"id"` } c.must(http.StatusCreated, http.MethodPost, base+"/environments", map[string]string{"name": "recovery"}, &env) - assignment := base + "/environments/" + env.ID + "/cloud" + assignment := base + "/default-cloud" db := pgdriver.New() if err := db.Open(t.Context(), cfg.Database.URL); err != nil { t.Fatal(err) @@ -480,7 +519,11 @@ func TestCloudAPIStartupAndPeriodicOutboxRecovery(t *testing.T) { return sync } var preview cloudprofiles.Preview - c.must(http.StatusOK, http.MethodPost, assignment+"/preview", apiclient.EnvironmentCloudInput{CloudID: cloud.ID, Revision: 0}, &preview) + c.must(http.StatusOK, http.MethodPost, assignment+"/preview", apiclient.DefaultCloudInput{CloudID: cloud.ID, Revision: 0}, &preview) + // The change covers every environment of the project, the new one too. + if cloudPreviewEnvironment(&preview, env.ID) == nil { + t.Fatalf("default Cloud review missed an environment: %+v", preview.Environments) + } r.stop() pending := acceptWithoutEnqueue("startup-outbox", &preview) r = start(t, cfg) @@ -488,17 +531,30 @@ func TestCloudAPIStartupAndPeriodicOutboxRecovery(t *testing.T) { if got := waitCloudAPI(t, c, base, pending.ID); got.Status != cloudprofiles.SyncSucceeded { t.Fatalf("startup: %+v", got) } - c.must(http.StatusOK, http.MethodPost, assignment+"/preview", apiclient.EnvironmentCloudInput{CloudID: "", Revision: 1}, &preview) + var assigned apiclient.DefaultCloud + c.must(http.StatusOK, http.MethodGet, assignment, nil, &assigned) + if assigned.Cloud == nil || assigned.Cloud.CloudID != cloud.ID || assigned.Revision == 0 { + t.Fatalf("default Cloud: %+v", assigned) + } + c.must(http.StatusOK, http.MethodPost, assignment+"/preview", apiclient.DefaultCloudInput{CloudID: "", Revision: assigned.Revision}, &preview) pending = acceptWithoutEnqueue("periodic-outbox", &preview) if got := waitCloudAPI(t, c, base, pending.ID); got.Status != cloudprofiles.SyncSucceeded { t.Fatalf("periodic: %+v", got) } - var tombstone apiclient.EnvironmentCloud + var tombstone apiclient.DefaultCloud c.must(http.StatusOK, http.MethodGet, assignment, nil, &tombstone) - if tombstone.Assignment != nil || tombstone.Revision != 2 { - t.Fatalf("unassignment generation lost: %+v", tombstone) + if tombstone.Cloud != nil || tombstone.Revision != 0 { + t.Fatalf("default Cloud not cleared: %+v", tombstone) + } + // The grant keeps advancing, so a review against the old default is stale. + var grants struct { + Grants []apiclient.CloudProjectGrant `json:"grants"` + } + c.must(http.StatusOK, http.MethodGet, "/api/v1/clouds/"+cloud.ID+"/projects", nil, &grants) + if len(grants.Grants) != 1 || grants.Grants[0].Default || grants.Grants[0].Revision != assigned.Revision+1 { + t.Fatalf("cleared default lost its grant revision: %+v", grants) } - c.must(http.StatusConflict, http.MethodPost, assignment+"/preview", apiclient.EnvironmentCloudInput{CloudID: cloud.ID, Revision: 0}, nil) + c.must(http.StatusConflict, http.MethodPost, assignment+"/preview", apiclient.DefaultCloudInput{CloudID: cloud.ID, Revision: assigned.Revision}, nil) c.must(http.StatusConflict, http.MethodPost, base+"/cloud-syncs/"+pending.ID+"/retry", nil, nil) c.must(http.StatusOK, http.MethodPost, base+"/cloud-syncs/"+pending.ID+"/revert/preview", nil, &preview) if preview.Reverts != pending.ID { @@ -509,9 +565,9 @@ func TestCloudAPIStartupAndPeriodicOutboxRecovery(t *testing.T) { if got := waitCloudAPI(t, c, base, compensation.ID); got.Status != cloudprofiles.SyncSucceeded { t.Fatalf("compensation %+v", got) } - var restored apiclient.EnvironmentCloud + var restored apiclient.DefaultCloud c.must(http.StatusOK, http.MethodGet, assignment, nil, &restored) - if restored.Assignment == nil || restored.Assignment.CloudID != cloud.ID || restored.Revision != 3 { + if restored.Cloud == nil || restored.Cloud.CloudID != cloud.ID || restored.Revision != assigned.Revision+2 { t.Fatalf("restored %+v", restored) } } @@ -535,14 +591,14 @@ func assertCloudAPISchemas(t *testing.T, c *client) { found[op.OperationID] = true } } - for _, operation := range []string{"clouds.list", "clouds.create", "clouds.get", "clouds.update", "clouds.delete", "cloudTargets.list", "cloudTargets.get", "cloudTargets.create", "cloudTargets.update", "cloudTargets.delete", "cloudChanges.preview", "cloudChanges.getPreview", "cloudChanges.apply", "environmentClouds.get", "environmentClouds.preview", "cloudSyncs.list", "cloudSyncs.get", "cloudSyncs.retry", "cloudSyncs.previewRevert", "cloudSyncs.applyRevert", "cloudSyncs.completeRouting"} { + for _, operation := range []string{"clouds.list", "clouds.create", "clouds.get", "clouds.update", "clouds.delete", "cloudTargets.list", "cloudTargets.get", "cloudTargets.create", "cloudTargets.update", "cloudTargets.delete", "cloudChanges.preview", "cloudChanges.getPreview", "cloudChanges.apply", "defaultCloud.get", "defaultCloud.preview", "cloudSyncs.list", "cloudSyncs.get", "cloudSyncs.retry", "cloudSyncs.previewRevert", "cloudSyncs.applyRevert", "cloudSyncs.completeRouting"} { if !found[operation] { t.Errorf("missing operation %s", operation) } } - assignmentSchema := document.Components.Schemas["EnvironmentCloud"] - if !strings.Contains(string(assignmentSchema.Properties["assignment"]), "nullable") { - t.Error("assignment schema does not admit explicit null") + assignmentSchema := document.Components.Schemas["DefaultCloud"] + if !strings.Contains(string(assignmentSchema.Properties["cloud"]), "nullable") { + t.Error("default Cloud schema does not admit explicit null") } for _, name := range []string{"Sync", "Preview"} { schema, ok := document.Components.Schemas[name] diff --git a/tests/integration/cloud_default_switch_test.go b/tests/integration/cloud_default_switch_test.go index ee67ef347..9768c9bb0 100644 --- a/tests/integration/cloud_default_switch_test.go +++ b/tests/integration/cloud_default_switch_test.go @@ -35,7 +35,7 @@ func defaultSwitchFixture(t *testing.T) *syncFixture { if err := json.Unmarshal(raw, &cfg); err != nil { t.Fatal(err) } - cfg.CloudPlacement = &planning.CloudPlacement{Default: true, CloudID: "cloud", CloudRevision: 2, AssignmentRevision: 1, Provider: "vercel", ConnectionID: "old", AccountIdentity: connections.AccountIdentity("vercel", "old", map[string]string{"team_id": "old"})} + cfg.CloudPlacement = &planning.CloudPlacement{Default: true, CloudID: "cloud", CloudRevision: 2, Provider: "vercel", ConnectionID: "old", AccountIdentity: connections.AccountIdentity("vercel", "old", map[string]string{"team_id": "old"})} raw, err := json.Marshal(cfg) if err != nil { t.Fatal(err) @@ -122,12 +122,13 @@ func TestCloudDefaultSwitchMovesOnlyDefaultPlacedServices(t *testing.T) { if connection, revision := cloudDefault(t, f); connection != "new" || revision != 3 { t.Fatalf("acceptance left the default at %s revision %d", connection, revision) } - // One switch per Cloud at a time, and no environment joins it meanwhile. - if _, err = f.conn.Exec(ctx, `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('late','org','proj','late','preview',now(),now())`); err != nil { + // One switch per Cloud at a time, and no project takes the Cloud as its + // default, bringing its environments, meanwhile. + if _, err = f.conn.Exec(ctx, `INSERT INTO loomplane_projects(id,org_id,name,slug,status,created_by,created_at,updated_at) VALUES('late','org','Late','late','ready','usr',now(),now())`); err != nil { t.Fatal(err) } - if _, err = f.conn.Exec(ctx, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','late','cloud',1)`); err == nil { - t.Fatal("an environment joined the Cloud during its default switch") + if _, err = f.conn.Exec(ctx, defaultCloudSQL("org", "late", "cloud")); err == nil { + t.Fatal("a project joined the Cloud during its default switch") } again, err := service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{CloudID: "cloud", Default: true, Revision: 3, Provider: "vercel", ConnectionID: "old"}) if err == nil && len(again.Blockers) == 0 { @@ -197,6 +198,16 @@ func TestCloudDefaultSwitchVisibilityAndClearing(t *testing.T) { t.Fatal("blocked clear accepted") } + // An environment created in a project whose default the Cloud is joins + // the next shared change. + if _, err = f.conn.Exec(ctx, `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('late','org','proj','late','preview',now(),now())`); err != nil { + t.Fatal(err) + } + switching, err := f.service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{CloudID: "cloud", Default: true, Revision: 2, Provider: "vercel", ConnectionID: "new"}) + if err != nil || cloudPreviewEnvironment(switching, "late") == nil || len(switching.Environments) != 3 { + t.Fatalf("new environment missed by the next shared change: %+v %v", switching, err) + } + // Default switches are shared: only an organization Cloud manager reviews them. f.auth.denied = true if _, err = f.service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{CloudID: "cloud", Default: true, Revision: 2, Provider: "vercel", ConnectionID: "new"}); err == nil { diff --git a/tests/integration/cloud_flow_test.go b/tests/integration/cloud_flow_test.go index b7c7405a0..fa8a3bcfc 100644 --- a/tests/integration/cloud_flow_test.go +++ b/tests/integration/cloud_flow_test.go @@ -67,9 +67,9 @@ func TestCloudFlowIsolationAdoptionRecoveryAndProviderReplacement(t *testing.T) if env == "" { t.Fatal("production missing") } - assignment := base + "/environments/" + env + "/cloud" + assignment := base + "/default-cloud" var preview cloudprofiles.Preview - c.must(http.StatusOK, http.MethodPost, assignment+"/preview", apiclient.EnvironmentCloudInput{CloudID: cloud.ID}, &preview) + c.must(http.StatusOK, http.MethodPost, assignment+"/preview", apiclient.DefaultCloudInput{CloudID: cloud.ID}, &preview) if got := waitCloudAPI(t, c, base, applyCloudAPI(t, c, base, &preview, "assign").ID); got.Status != cloudprofiles.SyncSucceeded { t.Fatalf("assignment: %+v", got) } @@ -137,10 +137,10 @@ func TestCloudFlowIsolationAdoptionRecoveryAndProviderReplacement(t *testing.T) if len(afterAdoption) != 2 || afterAdoption["docs"].ConnectionID != docs || count("old-token-0123456789") != 1 || count("docs-token-0123456789") != 1 { t.Fatalf("two-target deployment: %+v", afterAdoption) } - var assignedBefore apiclient.EnvironmentCloud + var assignedBefore apiclient.DefaultCloud c.must(http.StatusOK, http.MethodGet, assignment, nil, &assignedBefore) replacement := connect("vercel", "new-token-0123456789") - var assignedAfter apiclient.EnvironmentCloud + var assignedAfter apiclient.DefaultCloud c.must(http.StatusOK, http.MethodGet, assignment, nil, &assignedAfter) var targetAfter cloudprofiles.Target c.must(http.StatusOK, http.MethodGet, targets+"/"+frontend.ID, nil, &targetAfter) @@ -153,7 +153,7 @@ func TestCloudFlowIsolationAdoptionRecoveryAndProviderReplacement(t *testing.T) switchTo := func(provider, conn string, revision int64, key string) *cloudprofiles.Sync { t.Helper() c.must(http.StatusOK, http.MethodPost, base+"/cloud-changes/preview", cloudprofiles.ChangeInput{CloudID: cloud.ID, TargetID: frontend.ID, Revision: revision, Provider: provider, ConnectionID: conn}, &preview) - if len(preview.Blockers) != 0 || len(preview.Environments) != 1 || preview.Environments[0].Summary.Replace != 1 { + if production := cloudPreviewEnvironment(&preview, env); len(preview.Blockers) != 0 || len(preview.Environments) != 2 || production == nil || production.Summary.Replace != 1 { t.Fatalf("switch preview: %+v", preview) } return applyCloudAPI(t, c, base, &preview, key) @@ -384,7 +384,9 @@ func TestCloudFlowIsolationAdoptionRecoveryAndProviderReplacement(t *testing.T) // Even a read-only recent preview keeps its referenced Cloud protected. var reviewed cloudprofiles.Profile c.must(http.StatusCreated, http.MethodPost, base+"/clouds", cloudprofiles.CreateInput{Name: "Recently reviewed"}, &reviewed) - c.must(http.StatusOK, http.MethodPost, assignment+"/preview", apiclient.EnvironmentCloudInput{CloudID: reviewed.ID, Revision: 1}, &preview) + var standing apiclient.DefaultCloud + c.must(http.StatusOK, http.MethodGet, assignment, nil, &standing) + c.must(http.StatusOK, http.MethodPost, assignment+"/preview", apiclient.DefaultCloudInput{CloudID: reviewed.ID, Revision: standing.Revision}, &preview) c.must(http.StatusConflict, http.MethodDelete, base+"/clouds/"+reviewed.ID, nil, nil) // A fresh unreferenced Cloud and target can be removed through public APIs. var disposable cloudprofiles.Profile diff --git a/tests/integration/cloud_location_placement_test.go b/tests/integration/cloud_location_placement_test.go index 8e4840942..0f5068053 100644 --- a/tests/integration/cloud_location_placement_test.go +++ b/tests/integration/cloud_location_placement_test.go @@ -175,7 +175,7 @@ func TestCloudLocationPlacementPolicyPersistence(t *testing.T) { func TestCloudLocationPlacementAcceptanceGrantChanged(t *testing.T) { f := newSyncFixture(t) ctx := t.Context() - a, err := f.store.Resolve(ctx, "org", "proj", "env") + a, err := f.store.ResolveCloud(ctx, "org", "proj", "") if err != nil { t.Fatal(err) } @@ -207,7 +207,7 @@ func TestCloudLocationPlacementEvidenceAndRevalidation(t *testing.T) { if err := st.SaveLocation(ctx, &l, 1, 0); err != nil { t.Fatal(err) } - if _, err := conn.Exec(ctx, `UPDATE loomplane_cloud_targets SET location_id='location',region='iad1',revision=revision+1 WHERE id='target'; INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1)`); err != nil { + if _, err := conn.Exec(ctx, `UPDATE loomplane_cloud_targets SET location_id='location',region='iad1',revision=revision+1 WHERE id='target'; `+defaultCloudSQL("org", "proj", "cloud")); err != nil { t.Fatal(err) } svc := cloudprofiles.NewService(cloudprofiles.Deps{Store: st, Authz: &infraAuth{}, Connections: &syncAccounts{store: connections.NewPgStore(db)}, Providers: providers.Registry()}) @@ -215,7 +215,7 @@ func TestCloudLocationPlacementEvidenceAndRevalidation(t *testing.T) { if err != nil { t.Fatal(err) } - assignment, err := st.Resolve(ctx, "org", "proj", "env") + assignment, err := st.ResolveCloud(ctx, "org", "proj", "") if err != nil { t.Fatal(err) } @@ -270,7 +270,7 @@ func TestCloudLocationPlacementCapacityStalePolicyAndGrant(t *testing.T) { t.Run(change, func(t *testing.T) { f, _, in, _ := clusterWorkloadFixture(t) ctx := t.Context() - a, err := f.clouds.Resolve(ctx, "org", "proj", "env") + a, err := f.clouds.ResolveCloud(ctx, "org", "proj", "cloud") if err != nil { t.Fatal(err) } @@ -302,7 +302,7 @@ func TestCloudLocationPlacementCapacityStalePolicyAndGrant(t *testing.T) { func TestCloudLocationPlacementQualifiedClusterCPU(t *testing.T) { f, _, plan, _, _ := managedDemandFixture(t) ctx := t.Context() - a, err := f.clouds.Resolve(ctx, "org", "proj", "env") + a, err := f.clouds.ResolveCloud(ctx, "org", "proj", "cloud") if err != nil { t.Fatal(err) } @@ -378,7 +378,7 @@ func TestCloudLocationPlacementPoolStickyAndCumulative(t *testing.T) { if err = f.plans.PutBinding(ctx, &planning.Binding{ID: "binding-location", OrgID: "org", ProjectID: "proj", EnvironmentID: "env", Subject: planning.ServiceSubject, Name: "api", Provider: "server", ConnectionID: placed.ConnectionID, Config: raw, PlanID: "applied", CreatedAt: time.Now(), UpdatedAt: time.Now()}); err != nil { t.Fatal(err) } - a, err := f.clouds.Resolve(ctx, "org", "proj", "env") + a, err := f.clouds.ResolveCloud(ctx, "org", "proj", "cloud") if err != nil { t.Fatal(err) } diff --git a/tests/integration/cloud_metadata_test.go b/tests/integration/cloud_metadata_test.go index 4c0436aeb..b54f98c1c 100644 --- a/tests/integration/cloud_metadata_test.go +++ b/tests/integration/cloud_metadata_test.go @@ -13,7 +13,7 @@ import ( func TestCloudMetadataRetainedSyncGuard(t *testing.T) { st, _, _ := cloudSyncDatabase(t) - p, snap, s := persistAssignmentPreview(t, st, "metadata", "cloud", 0) + p, snap, s := persistDefaultCloudPreview(t, st, "metadata", "cloud") accepted, err := st.Accept(t.Context(), p, snap, s, "metadata") if err != nil { t.Fatal(err) @@ -70,7 +70,7 @@ func TestCloudMetadataAcceptanceRace(t *testing.T) { for i := range 5 { t.Run(fmt.Sprintf("%s/%d", kind, i), func(t *testing.T) { st, conn, _ := cloudSyncDatabase(t) - p, snap, s := persistAssignmentPreview(t, st, "race", "cloud", 0) + p, snap, s := persistDefaultCloudPreview(t, st, "race", "cloud") snap.ProfileRevisions = map[string]int64{"cloud": 1} snap.TargetRevisions = map[string]int64{"target": 1} target, err := st.GetTarget(t.Context(), "org", "proj", "cloud", "target") diff --git a/tests/integration/cloud_profiles_test.go b/tests/integration/cloud_profiles_test.go index 133621c82..4ced03d5f 100644 --- a/tests/integration/cloud_profiles_test.go +++ b/tests/integration/cloud_profiles_test.go @@ -140,21 +140,28 @@ func TestCloudProfiles_scopesRevisionsAndDeletion(t *testing.T) { if err = cs.DeleteConnection(ctx, "org_1", "conn_1"); !errors.Is(err, connections.ErrInUse) { t.Fatalf("referenced connection deleted: %v", err) } - assignment, err := st.Resolve(ctx, "org_1", "proj_1", "env_1") + // Creating a Cloud from a project grants it to that project without + // making it the project's default. + assignment, err := st.ResolveCloud(ctx, "org_1", "proj_1", "") if err != nil || assignment != nil { - t.Fatalf("unassigned: %+v %v", assignment, err) + t.Fatalf("no default Cloud: %+v %v", assignment, err) } - if _, err = st.Resolve(ctx, "org_1", "proj_1", "env_2"); !errors.Is(err, cloudprofiles.ErrNotFound) { - t.Fatalf("wrong environment resolved: %v", err) + if _, err = st.ResolveCloud(ctx, "org_1", "proj_2", p.ID); !errors.Is(err, cloudprofiles.ErrNotFound) { + t.Fatalf("ungranted Cloud resolved: %v", err) } - // An assignment's parent lock must serialize target deletion, including - // an assignment that has not yet committed. + // Making the Cloud a project's default must serialize with target + // deletion, including a default change that has not yet committed. + // Acceptance locks the Cloud row before it moves the default, as here. tx, err := conn.Begin(ctx) if err != nil { t.Fatal(err) } - if _, err = tx.Exec(ctx, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org_1','proj_1','env_1','cloud_1',1)`); err != nil { + if _, err = tx.Exec(ctx, `SELECT 1 FROM loomplane_cloud_profiles WHERE org_id='org_1' AND id='cloud_1' FOR UPDATE`); err != nil { + _ = tx.Rollback(ctx) + t.Fatal(err) + } + if _, err = tx.Exec(ctx, `UPDATE loomplane_cloud_project_grants SET is_default=true,revision=revision+1 WHERE org_id='org_1' AND cloud_id='cloud_1' AND project_id='proj_1'`); err != nil { _ = tx.Rollback(ctx) t.Fatal(err) } @@ -163,39 +170,44 @@ func TestCloudProfiles_scopesRevisionsAndDeletion(t *testing.T) { cancel() if !errors.Is(err, context.DeadlineExceeded) { _ = tx.Rollback(ctx) - t.Fatalf("delete did not wait for assignment: %v", err) + t.Fatalf("delete did not wait for the default change: %v", err) } if err = tx.Commit(ctx); err != nil { t.Fatal(err) } - if _, err = conn.Exec(ctx, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org_1','proj_2','env_2','cloud_1',1)`); err == nil { - t.Fatal("cross-project assignment accepted") + // A revoked grant can never be a project's default. + if _, err = conn.Exec(ctx, `INSERT INTO loomplane_cloud_project_grants(org_id,cloud_id,project_id,target_ids,revoked,is_default) VALUES('org_1','cloud_1','proj_2','{}',true,true)`); err == nil { + t.Fatal("revoked default grant accepted") } - assignment, err = st.Resolve(ctx, "org_1", "proj_1", "env_1") - if err != nil || assignment == nil || assignment.CloudID != p.ID || assignment.CloudRevision != p.Revision || len(assignment.Targets) != 1 || assignment.Targets[0].ID != target.ID { - t.Fatalf("assignment: %+v %v", assignment, err) + assignment, err = st.ResolveCloud(ctx, "org_1", "proj_1", "") + if err != nil || assignment == nil || assignment.CloudID != p.ID || !assignment.Default || assignment.CloudRevision != p.Revision || len(assignment.Targets) != 1 || assignment.Targets[0].ID != target.ID { + t.Fatalf("default Cloud: %+v %v", assignment, err) } - if _, err = st.Resolve(ctx, "org_2", "proj_1", "env_1"); !errors.Is(err, cloudprofiles.ErrNotFound) { + if _, err = st.ResolveCloud(ctx, "org_2", "proj_1", ""); !errors.Is(err, cloudprofiles.ErrNotFound) { t.Fatalf("cross-org resolve: %v", err) } + // A manifest names a Cloud by name; the same view comes back. + named, err := st.ResolveNamedCloud(ctx, "org_1", "proj_1", assignment.Name) + if err != nil || named.CloudID != p.ID || named.GrantRevision != assignment.GrantRevision || len(named.Targets) != 1 { + t.Fatalf("named Cloud: %+v %v", named, err) + } + if _, err = st.ResolveNamedCloud(ctx, "org_1", "proj_1", "No such Cloud"); !errors.Is(err, cloudprofiles.ErrNotFound) { + t.Fatalf("unknown Cloud name: %v", err) + } + if _, err = st.ResolveNamedCloud(ctx, "org_2", "proj_1", assignment.Name); !errors.Is(err, cloudprofiles.ErrNotFound) { + t.Fatalf("cross-org named Cloud: %v", err) + } if err = st.DeleteTarget(ctx, "org_1", "proj_1", p.ID, target.ID); !errors.Is(err, cloudprofiles.ErrInUse) { - t.Fatalf("assigned target deleted: %v", err) + t.Fatalf("target of a default Cloud deleted: %v", err) } if err = st.DeleteProfile(ctx, "org_1", "proj_1", p.ID); !errors.Is(err, cloudprofiles.ErrInUse) { - t.Fatalf("assigned cloud deleted: %v", err) + t.Fatalf("default Cloud deleted: %v", err) } - if _, err = conn.Exec(ctx, `DELETE FROM loomplane_cloud_assignments WHERE environment_id='env_1'`); err != nil { + if _, err = conn.Exec(ctx, `UPDATE loomplane_cloud_project_grants SET is_default=false,revision=revision+1 WHERE org_id='org_1' AND project_id='proj_1' AND is_default`); err != nil { t.Fatal(err) } - // A scoped environment row alone cannot authorize the wrong parent project. - if _, err = conn.Exec(ctx, `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('env_bad','org_2','proj_1','bad','preview',now(),now())`); err != nil { - t.Fatal(err) - } - if _, err = st.Resolve(ctx, "org_2", "proj_1", "env_bad"); !errors.Is(err, cloudprofiles.ErrNotFound) { - t.Fatalf("inconsistent environment parent accepted: %v", err) - } if err = st.DeleteProfile(ctx, "org_1", "proj_1", p.ID); err != nil { t.Fatal(err) } diff --git a/tests/integration/cloud_sync_test.go b/tests/integration/cloud_sync_test.go index 89ad64df7..9442be9bb 100644 --- a/tests/integration/cloud_sync_test.go +++ b/tests/integration/cloud_sync_test.go @@ -72,15 +72,45 @@ func cloudSyncDatabase(t *testing.T) (*cloudprofiles.PgStore, *pgx.Conn, *pgdriv } return st, conn, db } -func persistAssignmentPreview(t *testing.T, st *cloudprofiles.PgStore, id, cloud string, revision int64) (*cloudprofiles.Preview, *cloudprofiles.Snapshot, *cloudprofiles.Sync) { + +// defaultCloudSQL makes cloud the project's default Cloud and clears the +// project's previous default, as a reviewed default change does: both +// grants advance their revision. A project with no default whose grant on +// cloud is untouched (revision 1, whole Cloud) instead gets the state a +// project's first grant has: the default, still at revision 1, so fixtures +// that pin grant revision 1 stay current. +func defaultCloudSQL(org, project, cloud string) string { + return fmt.Sprintf(`DELETE FROM loomplane_cloud_project_grants WHERE org_id='%[1]s' AND project_id='%[2]s' AND cloud_id='%[3]s' AND revision=1 AND NOT revoked AND NOT is_default AND cardinality(target_ids)=0 + AND NOT EXISTS(SELECT 1 FROM loomplane_cloud_project_grants WHERE org_id='%[1]s' AND project_id='%[2]s' AND is_default); +WITH cleared AS (UPDATE loomplane_cloud_project_grants SET is_default=false,revision=revision+1,updated_at=now() WHERE org_id='%[1]s' AND project_id='%[2]s' AND is_default AND cloud_id<>'%[3]s' RETURNING 1) +INSERT INTO loomplane_cloud_project_grants(org_id,cloud_id,project_id,target_ids,revoked,is_default) SELECT '%[1]s','%[3]s','%[2]s','{}',false,true FROM (SELECT count(*) FROM cleared) n +ON CONFLICT(org_id,cloud_id,project_id) DO UPDATE SET is_default=true,revision=loomplane_cloud_project_grants.revision+1,updated_at=now() WHERE NOT loomplane_cloud_project_grants.is_default`, org, project, cloud) +} + +// clearDefaultCloudSQL leaves the project without a default Cloud. +func clearDefaultCloudSQL(org, project string) string { + return fmt.Sprintf(`UPDATE loomplane_cloud_project_grants SET is_default=false,revision=revision+1,updated_at=now() WHERE org_id='%s' AND project_id='%s' AND is_default`, org, project) +} + +// persistDefaultCloudPreview stores a reviewed change of the project's +// default Cloud to cloud, "" for none, against the default as it is now. +func persistDefaultCloudPreview(t *testing.T, st *cloudprofiles.PgStore, id, cloud string) (*cloudprofiles.Preview, *cloudprofiles.Snapshot, *cloudprofiles.Sync) { t.Helper() now := time.Now().UTC() - p := &cloudprofiles.Preview{ID: "preview-" + id, OrgID: "org", ProjectID: "proj", Revision: "digest-" + id, Input: cloudprofiles.ChangeInput{EnvironmentID: "env", CloudID: cloud, Revision: revision}, CreatedAt: now} + current, revision, err := st.DefaultCloud(t.Context(), "org", "proj") + if err != nil { + t.Fatal(err) + } + before, err := st.ResolveCloud(t.Context(), "org", "proj", "") + if err != nil { + t.Fatal(err) + } + p := &cloudprofiles.Preview{ID: "preview-" + id, OrgID: "org", ProjectID: "proj", Revision: "digest-" + id, Input: cloudprofiles.ChangeInput{ProjectDefault: true, CloudID: cloud, Revision: revision}, BeforeCloud: before, CreatedAt: now} raw, err := st.SnapshotBindings(t.Context(), "org", "env") if err != nil { t.Fatal(err) } - snap := &cloudprofiles.Snapshot{Environments: []cloudprofiles.EnvironmentSnapshot{{EnvironmentID: "env", AssignmentRevision: revision, Bindings: raw, Plan: json.RawMessage(`{}`)}}, Connections: []string{"old", "new"}} + snap := &cloudprofiles.Snapshot{Environments: []cloudprofiles.EnvironmentSnapshot{{EnvironmentID: "env", DefaultCloud: current, Bindings: raw, Plan: json.RawMessage(`{}`)}}, Connections: []string{"old", "new"}} if err = st.SavePreview(t.Context(), p, snap); err != nil { t.Fatal(err) } @@ -90,7 +120,7 @@ func persistAssignmentPreview(t *testing.T, st *cloudprofiles.PgStore, id, cloud func TestCloudSyncAtomicAcceptanceRecoveryAndABA(t *testing.T) { st, conn, _ := cloudSyncDatabase(t) ctx := t.Context() - p, snap, sync := persistAssignmentPreview(t, st, "assign", "cloud", 0) + p, snap, sync := persistDefaultCloudPreview(t, st, "assign", "cloud") accepted, err := st.Accept(ctx, p, snap, sync, "request") if err != nil { t.Fatal(err) @@ -103,7 +133,12 @@ func TestCloudSyncAtomicAcceptanceRecoveryAndABA(t *testing.T) { if err != nil || len(pending) != 1 { t.Fatalf("commit without enqueue lost durable work: %v %v", pending, err) } - otherP, otherSnap, otherSync := persistAssignmentPreview(t, st, "blocked", "cloud", 1) + // Reviewed against the default as it is now: the Cloud, at its current + // grant revision. + otherP, otherSnap, otherSync := persistDefaultCloudPreview(t, st, "blocked", "") + if otherP.BeforeCloud == nil || otherP.BeforeCloud.CloudID != "cloud" { + t.Fatalf("default change was not applied: %+v", otherP.BeforeCloud) + } if _, err = st.Accept(ctx, otherP, otherSnap, otherSync, "other"); !errors.Is(err, cloudprofiles.ErrBusy) { t.Fatalf("second change passed guard: %v", err) } @@ -121,25 +156,42 @@ func TestCloudSyncAtomicAcceptanceRecoveryAndABA(t *testing.T) { if err = st.SaveSync(ctx, accepted, snap); err != nil { t.Fatal(err) } - unassign, unsnap, unsync := persistAssignmentPreview(t, st, "unassign", "", 1) + unassign, unsnap, unsync := persistDefaultCloudPreview(t, st, "unassign", "") removed, err := st.Accept(ctx, unassign, unsnap, unsync, "remove") if err != nil { t.Fatal(err) } - resolved, err := st.Resolve(ctx, "org", "proj", "env") + resolved, err := st.ResolveCloud(ctx, "org", "proj", "") if err != nil || resolved != nil { - t.Fatalf("unassignment: %+v %v", resolved, err) + t.Fatalf("default cleared: %+v %v", resolved, err) } - generation, err := st.AssignmentGeneration(ctx, "org", "proj", "env") - if err != nil || generation != 2 { - t.Fatalf("lost tombstone: %d %v", generation, err) + // The grant keeps its row and advances, so a review against the old + // default can never match again. + if grant, grantErr := st.GetProjectGrant(ctx, "org", "cloud", "proj"); grantErr != nil || grant.Default || grant.Revision != unassign.Input.Revision+1 { + t.Fatalf("lost tombstone: %+v %v", grant, grantErr) } removed.Status = cloudprofiles.SyncSucceeded if err = st.SaveSync(ctx, removed, unsnap); err != nil { t.Fatal(err) } if _, err = st.Accept(ctx, otherP, otherSnap, otherSync, "stale"); !errors.Is(err, cloudprofiles.ErrConflict) { - t.Fatalf("old assignment generation resurrected: %v", err) + t.Fatalf("review of a cleared default accepted: %v", err) + } + // ABA: the same Cloud becomes the default again, at a later revision. + back, backSnap, backSync := persistDefaultCloudPreview(t, st, "reassign", "cloud") + restored, err := st.Accept(ctx, back, backSnap, backSync, "reassign") + if err != nil { + t.Fatal(err) + } + restored.Status = cloudprofiles.SyncSucceeded + if err = st.SaveSync(ctx, restored, backSnap); err != nil { + t.Fatal(err) + } + if current, _, defaultErr := st.DefaultCloud(ctx, "org", "proj"); defaultErr != nil || current != "cloud" { + t.Fatalf("default restored: %q %v", current, defaultErr) + } + if _, err = st.Accept(ctx, otherP, otherSnap, otherSync, "stale"); !errors.Is(err, cloudprofiles.ErrConflict) { + t.Fatalf("old default revision resurrected: %v", err) } if _, _, err = st.GetPreview(ctx, "other", "proj", p.ID); !errors.Is(err, cloudprofiles.ErrNotFound) { t.Fatalf("preview scope leak: %v", err) @@ -332,7 +384,7 @@ func newSyncFixture(t *testing.T) *syncFixture { ctx := t.Context() for _, sql := range []string{ `UPDATE loomplane_cloud_connections SET details=jsonb_build_object('team_id',id)`, - `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1),('org','proj','stage','cloud',1)`, + defaultCloudSQL("org", "proj", "cloud"), `INSERT INTO loomplane_manifests(id,org_id,project_id,revision,body,digest,created_by,created_at) VALUES('manifest','org','proj',1,'version: 1','digest','usr',now())`, } { if _, err := conn.Exec(ctx, sql); err != nil { @@ -353,7 +405,7 @@ func newSyncFixture(t *testing.T) *syncFixture { key := deployments.SourceKey("org", "proj", "app", commit) secrets[ref] = []byte(`{"values":{"SECRET_TOKEN":"applied-secret","BASE_VERSION":"applied-base"},"secrets":{"SECRET_TOKEN":true}}`) sources[key] = name + "-exact-original-artifact" - cfg := planning.ServiceConfig{Provider: "vercel", Repo: "app", CommitSHA: commit, Service: name, Public: true, Workload: provider.WebApp, Execution: provider.Serverless, CloudPlacement: &planning.CloudPlacement{CloudID: "cloud", CloudRevision: 1, AssignmentRevision: 1, TargetID: "target", TargetRevision: 1, TargetName: "frontend", Provider: "vercel", ConnectionID: "old", AccountIdentity: connections.AccountIdentity("vercel", "old", map[string]string{"team_id": "old"})}, AppliedInputs: &planning.AppliedInputs{Variables: ref, Source: &planning.PlanSource{Alias: "app", Repository: "owner/app", CommitSHA: commit}, ArtifactKey: key}} + cfg := planning.ServiceConfig{Provider: "vercel", Repo: "app", CommitSHA: commit, Service: name, Public: true, Workload: provider.WebApp, Execution: provider.Serverless, CloudPlacement: &planning.CloudPlacement{CloudID: "cloud", CloudRevision: 1, TargetID: "target", TargetRevision: 1, TargetName: "frontend", Provider: "vercel", ConnectionID: "old", AccountIdentity: connections.AccountIdentity("vercel", "old", map[string]string{"team_id": "old"})}, AppliedInputs: &planning.AppliedInputs{Variables: ref, Source: &planning.PlanSource{Alias: "app", Repository: "owner/app", CommitSHA: commit}, ArtifactKey: key}} if name == "web" { cfg.Env = []planning.EnvLink{{Key: "API_URL", Subject: planning.ServiceSubject, From: "api"}} } @@ -616,7 +668,7 @@ func TestCloudSyncDatabaseReleaseSerialization(t *testing.T) { } } insertPlan("approved", "approved") - p, snap, sync := persistAssignmentPreview(t, st, "serialized", "cloud", 0) + p, snap, sync := persistDefaultCloudPreview(t, st, "serialized", "cloud") if _, err := st.Accept(ctx, p, snap, sync, "switch"); !errors.Is(err, cloudprofiles.ErrBusy) { t.Fatalf("approved release overtaken: %v", err) } @@ -724,9 +776,9 @@ func TestCloudSyncEmptyAssignmentAndEnqueueRecovery(t *testing.T) { service := planning.NewService(planning.Deps{Store: plans, Projects: projects.NewPgStore(db), CloudProfiles: st, Connections: accounts, Providers: providers.Registry(), Authz: &syncAuth{}, CloudSyncWorkflow: workflow}) runner := deployments.NewRunner(deployments.RunnerDeps{Store: deployments.NewPgStore(db), Plans: plans, Credentials: accounts, CloudProfiles: st, CloudSyncAuth: service, Capacity: service}) service.BindCloudSyncRunner(runner, runner) - preview, err := service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{EnvironmentID: "env", CloudID: "cloud", Revision: 0}) + preview, err := service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{ProjectDefault: true, CloudID: "cloud", Revision: 0}) if err != nil || len(preview.Blockers) > 0 { - t.Fatalf("initial assignment: %+v %v", preview, err) + t.Fatalf("initial default Cloud: %+v %v", preview, err) } sync, err := service.ApplyCloudChange(ctx, actor, "proj", preview.ID, preview.Revision, "empty-assign") if err != nil { @@ -765,6 +817,7 @@ func TestCloudSyncEmptyAssignmentAndEnqueueRecovery(t *testing.T) { func TestCloudSyncAssignmentMigrationAndMetadataAdoption(t *testing.T) { t.Run("assignment", func(t *testing.T) { f := newSyncFixture(t) + f.executor.failStage = false ctx := orchestration.CapacityContext(t.Context()) actor := security.Principal{OrgID: "org", UserID: "usr"} now := time.Now().UTC() @@ -774,12 +827,17 @@ func TestCloudSyncAssignmentMigrationAndMetadataAdoption(t *testing.T) { if err := f.store.CreateTarget(ctx, &cloudprofiles.Target{ID: "target-b", OrgID: "org", ProjectID: "proj", CloudID: "cloud-b", Name: "frontend", DisplayName: "Frontend", Provider: "vercel", ConnectionID: "new", Revision: 1, CreatedAt: now, UpdatedAt: now}); err != nil { t.Fatal(err) } - preview, err := f.service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{EnvironmentID: "env", CloudID: "cloud-b", Revision: 1}) + _, revision, err := f.store.DefaultCloud(ctx, "org", "proj") + if err != nil { + t.Fatal(err) + } + preview, err := f.service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{ProjectDefault: true, CloudID: "cloud-b", Revision: revision}) if err != nil || len(preview.Blockers) > 0 { - t.Fatalf("assignment preview: %+v %v", preview, err) + t.Fatalf("default Cloud preview: %+v %v", preview, err) } - if len(preview.Environments) != 1 || preview.Environments[0].Summary.Replace != 2 { - t.Fatalf("assignment summary: %+v", preview.Environments) + // Changing the project's default moves every environment. + if len(preview.Environments) != 2 || preview.Environments[0].Summary.Replace != 2 || preview.Environments[1].Summary.Replace != 2 { + t.Fatalf("default Cloud summary: %+v", preview.Environments) } sync, err := f.service.ApplyCloudChange(ctx, actor, "proj", preview.ID, preview.Revision, "assignment") if err != nil { @@ -788,15 +846,16 @@ func TestCloudSyncAssignmentMigrationAndMetadataAdoption(t *testing.T) { if err = f.service.ReconcileCloudSync(ctx, "org", "proj", sync.ID, func([]byte) error { return nil }); err != nil { t.Fatal(err) } - assignment, err := f.store.Resolve(ctx, "org", "proj", "env") - if err != nil || assignment.CloudID != "cloud-b" || assignment.Revision != 2 { - t.Fatalf("assignment not persisted: %+v %v", assignment, err) + assignment, err := f.store.ResolveCloud(ctx, "org", "proj", "") + if err != nil || assignment == nil || assignment.CloudID != "cloud-b" || !assignment.Default { + t.Fatalf("default Cloud not persisted: %+v %v", assignment, err) } - if f.executor.calls["stage/api"] != 0 || f.executor.calls["env/api"] != 1 { - t.Fatalf("assignment crossed environments: %v", f.executor.calls) + // Both grants advanced, so plans resolved against the old default are stale. + if old, oldErr := f.store.GetProjectGrant(ctx, "org", "cloud", "proj"); oldErr != nil || old.Default || old.Revision != revision+1 { + t.Fatalf("old default grant: %+v %v", old, oldErr) } - if _, err = f.conn.Exec(ctx, `DELETE FROM loomplane_cloud_assignments WHERE environment_id='stage'`); err != nil { - t.Fatal(err) + if f.executor.calls["stage/api"] != 1 || f.executor.calls["env/api"] != 1 { + t.Fatalf("default Cloud change missed an environment: %v", f.executor.calls) } if _, err = f.conn.Exec(ctx, `UPDATE loomplane_cloud_previews SET created_at=now()-interval '25 hours'`); err != nil { t.Fatal(err) @@ -918,11 +977,15 @@ func TestCloudSyncApprovalAcceptanceRace(t *testing.T) { if _, err = conn.Exec(ctx, `INSERT INTO loomplane_plans(id,org_id,project_id,environment_id,environment,status,manifest_id,manifest_revision,created_by,created_at) VALUES($1,'org','proj','env','production','ready','manifest',1,'usr',now())`, id); err != nil { t.Fatal(err) } - revision, e := st.AssignmentGeneration(ctx, "org", "proj", "env") + current, revision, e := st.DefaultCloud(ctx, "org", "proj") if e != nil { t.Fatal(e) } - p, snap, sync := persistAssignmentPreview(t, st, id, "cloud", revision) + next := "cloud" + if current == next { + next = "" + } + p, snap, sync := persistDefaultCloudPreview(t, st, id, next) start, done := make(chan struct{}), make(chan error, 1) go func() { <-start @@ -945,9 +1008,9 @@ func TestCloudSyncApprovalAcceptanceRace(t *testing.T) { t.Fatal(err) } case errors.Is(e, cloudprofiles.ErrBusy): - generation, generationErr := st.AssignmentGeneration(ctx, "org", "proj", "env") - if generationErr != nil || generation != revision { - t.Fatalf("blocked switch mutated desired assignment: %d %v", generation, generationErr) + cloud, generation, generationErr := st.DefaultCloud(ctx, "org", "proj") + if generationErr != nil || cloud != current || generation != revision { + t.Fatalf("blocked switch mutated the default Cloud: %q %d %v", cloud, generation, generationErr) } default: t.Fatalf("race acceptance: %v", e) diff --git a/tests/integration/cloud_tags_test.go b/tests/integration/cloud_tags_test.go index 53335cd99..f2168a571 100644 --- a/tests/integration/cloud_tags_test.go +++ b/tests/integration/cloud_tags_test.go @@ -39,7 +39,7 @@ func TestCloudTagsAndDefaultPlacementPersistence(t *testing.T) { // The first default may be set while the Cloud is in use: the services // it places had no placement before. - if _, err = conn.Exec(ctx, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1)`); err != nil { + if _, err = conn.Exec(ctx, defaultCloudSQL("org", "proj", "cloud")); err != nil { t.Fatal(err) } profile, err := st.GetProfile(ctx, "org", "", "cloud") @@ -51,47 +51,47 @@ func TestCloudTagsAndDefaultPlacementPersistence(t *testing.T) { if err = st.UpdateProfile(ctx, profile, 1); err != nil { t.Fatal(err) } - a, err := st.Resolve(ctx, "org", "proj", "env") + a, err := st.ResolveCloud(ctx, "org", "proj", "") if err != nil || a.DefaultPlacement == nil || *a.DefaultPlacement != *profile.DefaultPlacement || a.CloudRevision != 2 { - t.Fatalf("assignment default: %+v %v", a, err) + t.Fatalf("default Cloud's default placement: %+v %v", a, err) } for _, at := range a.Targets { if at.Tags == nil { - t.Fatalf("assigned target lost tags: %+v", at) + t.Fatalf("granted target lost tags: %+v", at) } } // Renaming keeps the default; replacing or clearing it would move serving services. profile.Name, profile.Revision = "Renamed", 3 if err = st.UpdateProfile(ctx, profile, 2); err != nil { - t.Fatalf("rename of an assigned Cloud with a default: %v", err) + t.Fatalf("rename of a default Cloud with a default placement: %v", err) } for _, next := range []*cloudprofiles.DefaultPlacement{nil, {Provider: "vercel", ConnectionID: "new"}, {Provider: "vercel", ConnectionID: "old", Region: "sfo1"}} { changed := *profile changed.DefaultPlacement, changed.Revision = next, 4 if err = st.UpdateProfile(ctx, &changed, 3); !errors.Is(err, cloudprofiles.ErrInUse) { - t.Fatalf("default change on an assigned Cloud: %v", err) + t.Fatalf("default placement change on a default Cloud: %v", err) } } // A grant limited to chosen targets reaches those targets, not the default. grants := any(st).(interface { - SetProjectGrant(context.Context, string, string, string, []string, bool) (int64, error) + SetProjectGrant(context.Context, string, string, string, []string, bool) (*cloudprofiles.ProjectGrant, error) }) if _, err = grants.SetProjectGrant(ctx, "org", "cloud", "proj", []string{"gpu"}, false); err != nil { t.Fatal(err) } - a, err = st.Resolve(ctx, "org", "proj", "env") - if err != nil || a.DefaultPlacement != nil || len(a.Targets) != 1 || a.Targets[0].ID != "gpu" { + a, err = st.ResolveCloud(ctx, "org", "proj", "") + if err != nil || a == nil || !a.Default || a.DefaultPlacement != nil || len(a.Targets) != 1 || a.Targets[0].ID != "gpu" { t.Fatalf("limited grant reached the default: %+v %v", a, err) } - retained, err := st.RetainedAssignment(ctx, "org", "proj", "env") + retained, err := st.RetainedCloud(ctx, "org", "proj", "cloud") if err != nil || retained.DefaultPlacement == nil { t.Fatalf("cleanup lost the default it placed with: %+v %v", retained, err) } // Once nothing uses the Cloud, its default can change, and the account stays retained. - if _, err = conn.Exec(ctx, `DELETE FROM loomplane_cloud_assignments WHERE environment_id='env'`); err != nil { + if _, err = conn.Exec(ctx, clearDefaultCloudSQL("org", "proj")); err != nil { t.Fatal(err) } profile.DefaultPlacement, profile.Revision = &cloudprofiles.DefaultPlacement{Provider: "vercel", ConnectionID: "new"}, 4 diff --git a/tests/integration/cloud_usage_test.go b/tests/integration/cloud_usage_test.go index 4a3273d07..04b51bcde 100644 --- a/tests/integration/cloud_usage_test.go +++ b/tests/integration/cloud_usage_test.go @@ -19,7 +19,9 @@ func TestCloudUsageCountsPlacedServicesByTarget(t *testing.T) { t.Fatal(err) } for _, sql := range []string{ - `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1)`, + defaultCloudSQL("org", "proj", "cloud"), + `INSERT INTO loomplane_projects(id,org_id,name,slug,status,created_by,created_at,updated_at) VALUES('second','org','Two','two','ready','usr',now(),now())`, + `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('second-env','org','second','production','production',now(),now())`, `INSERT INTO loomplane_bindings(id,org_id,project_id,environment_id,subject,name,provider,engine,config,created_at,updated_at) VALUES ('b1','org','proj','env','service','web','vercel','vercel','{"cloud_placement":{"cloud_id":"cloud","target_id":"target"}}',now(),now()), ('b2','org','proj','env','service','api','vercel','vercel','{"cloud_placement":{"cloud_id":"cloud","target_id":"","default":true}}',now(),now()), @@ -27,7 +29,8 @@ func TestCloudUsageCountsPlacedServicesByTarget(t *testing.T) { ('b4','org','proj','env','resource','db','vercel','vercel','{"cloud_placement":{"cloud_id":"cloud","target_id":"target"}}',now(),now()), ('b5','org','proj','env','service','direct','vercel','vercel','{}',now(),now()), ('b6','org','proj','stage','service','job','vercel','vercel','{"cloud_placement":{"cloud_id":"cloud","target_id":"target"}}',now(),now()), - ('b7','org','proj','stage','service','elsewhere','vercel','vercel','{"cloud_placement":{"cloud_id":"other","target_id":"x"}}',now(),now())`, + ('b7','org','proj','stage','service','elsewhere','vercel','vercel','{"cloud_placement":{"cloud_id":"other","target_id":"x"}}',now(),now()), + ('b8','org','second','second-env','service','job','vercel','vercel','{"cloud_placement":{"cloud_id":"cloud","target_id":"target"}}',now(),now())`, } { if _, err := conn.Exec(ctx, sql); err != nil { t.Fatal(err) @@ -37,17 +40,21 @@ func TestCloudUsageCountsPlacedServicesByTarget(t *testing.T) { if err != nil { t.Fatal(err) } - if len(usage.Environments) != 2 { + if len(usage.Environments) != 3 { t.Fatalf("environments: %+v", usage.Environments) } - prod, stage := usage.Environments[0], usage.Environments[1] - if prod.EnvironmentName != "production" || !prod.Assigned || prod.ProjectName != "One" { - t.Fatalf("assigned environment: %+v", prod) + // Every environment of a project whose default the Cloud is uses it. + prod, stage, leftover := usage.Environments[0], usage.Environments[1], usage.Environments[2] + if prod.EnvironmentName != "production" || !prod.Default || prod.ProjectName != "One" { + t.Fatalf("default environment: %+v", prod) } - // A service this Cloud placed keeps the environment listed after it - // chose another Cloud, so nothing running here goes unseen. - if stage.EnvironmentName != "staging" || stage.Assigned { - t.Fatalf("leftover environment: %+v", stage) + if stage.EnvironmentName != "staging" || !stage.Default || stage.ProjectName != "One" { + t.Fatalf("default environment: %+v", stage) + } + // A service this Cloud placed keeps the environment listed when the + // Cloud is not its project's default, so nothing running here goes unseen. + if leftover.EnvironmentID != "second-env" || leftover.Default || leftover.ProjectName != "Two" || len(leftover.Placements) != 1 || !slices.Equal(leftover.Placements[0].Services, []string{"job"}) { + t.Fatalf("leftover environment: %+v", leftover) } want := []cloudprofiles.PlacementUsage{{Default: true, Services: []string{"api"}}, {TargetID: "target", Services: []string{"admin", "web"}}} if len(prod.Placements) != 2 || !slices.Equal(prod.Placements[0].Services, want[0].Services) || !prod.Placements[0].Default || @@ -55,9 +62,13 @@ func TestCloudUsageCountsPlacedServicesByTarget(t *testing.T) { t.Fatalf("placements: %+v", prod.Placements) } if len(stage.Placements) != 1 || !slices.Equal(stage.Placements[0].Services, []string{"job"}) { - t.Fatalf("leftover placements: %+v", stage.Placements) + t.Fatalf("staging placements: %+v", stage.Placements) + } + scoped, err := st.CloudUsage(ctx, "org", "second", "cloud") + if err != nil || len(scoped.Environments) != 1 || scoped.Environments[0].EnvironmentID != "second-env" { + t.Fatalf("project scope: %+v %v", scoped, err) } - scoped, err := st.CloudUsage(ctx, "org", "nobody", "cloud") + scoped, err = st.CloudUsage(ctx, "org", "nobody", "cloud") if err != nil || len(scoped.Environments) != 0 { t.Fatalf("another project's usage leaked: %+v %v", scoped, err) } @@ -83,8 +94,8 @@ func TestCloudSyncPageFiltersByCloud(t *testing.T) { } insert("target-move", "cloud", `{}`, now.Add(-3*time.Second)) insert("other-cloud", "other", `{}`, now.Add(-2*time.Second)) - // Leaving a Cloud records no Cloud on the sync, only on the review. - insert("unassign", "", `{"before_assignment":{"cloud_id":"cloud"}}`, now.Add(-time.Second)) + // Clearing a project's default Cloud records no Cloud on the sync, only on the review. + insert("unassign", "", `{"before_cloud":{"cloud_id":"cloud"}}`, now.Add(-time.Second)) ids := func(cloud string) []string { t.Helper() diff --git a/tests/integration/cloudsql_partial_revert_test.go b/tests/integration/cloudsql_partial_revert_test.go index d10748c61..15da07ca8 100644 --- a/tests/integration/cloudsql_partial_revert_test.go +++ b/tests/integration/cloudsql_partial_revert_test.go @@ -269,9 +269,9 @@ func testInstalledPartialSQLCleanup(t *testing.T, loss string) { var profile cloudprofiles.Profile c.must(http.StatusCreated, http.MethodPost, base+"/clouds", cloudprofiles.CreateInput{Name: "Unrelated placement"}, &profile) var preview cloudprofiles.Preview - c.must(http.StatusOK, http.MethodPost, base+"/environments/"+plan.EnvironmentID+"/cloud/preview", apiclient.EnvironmentCloudInput{CloudID: profile.ID}, &preview) - if len(preview.Blockers) != 0 || len(preview.Environments) != 1 || preview.Environments[0].Summary != (cloudprofiles.PlanSummary{}) { - t.Fatalf("Cloud assignment imported partial SQL: %+v", preview) + c.must(http.StatusOK, http.MethodPost, base+"/default-cloud/preview", apiclient.DefaultCloudInput{CloudID: profile.ID}, &preview) + if production := cloudPreviewEnvironment(&preview, plan.EnvironmentID); len(preview.Blockers) != 0 || len(preview.Environments) != 2 || production == nil || production.Summary != (cloudprofiles.PlanSummary{}) { + t.Fatalf("default Cloud change imported partial SQL: %+v", preview) } assignment := applyCloudAPI(t, c, base, &preview, "assign-around-partial") if got := waitCloudAPI(t, c, base, assignment.ID); got.Status != cloudprofiles.SyncSucceeded { @@ -279,7 +279,7 @@ func testInstalledPartialSQLCleanup(t *testing.T, loss string) { } denied.must(http.StatusForbidden, http.MethodPost, base+"/cloud-syncs/"+assignment.ID+"/revert/preview", nil, nil) c.must(http.StatusOK, http.MethodPost, base+"/cloud-syncs/"+assignment.ID+"/revert/preview", nil, &preview) - if preview.Reverts != assignment.ID || len(preview.Blockers) != 0 || preview.Environments[0].Summary != (cloudprofiles.PlanSummary{}) { + if production := cloudPreviewEnvironment(&preview, plan.EnvironmentID); preview.Reverts != assignment.ID || len(preview.Blockers) != 0 || production == nil || production.Summary != (cloudprofiles.PlanSummary{}) { t.Fatalf("revert imported partial SQL: %+v", preview) } input := apiclient.ApplyCloudInput{PreviewID: preview.ID, Revision: preview.Revision, IdempotencyKey: "revert-around-partial"} diff --git a/tests/integration/cluster_workload_planning_test.go b/tests/integration/cluster_workload_planning_test.go index 987b1207c..948bc6ab5 100644 --- a/tests/integration/cluster_workload_planning_test.go +++ b/tests/integration/cluster_workload_planning_test.go @@ -84,7 +84,7 @@ func setupDemandForAttachment(t *testing.T, f *poolFixture, r *cloudinfra.Manage auth := &capacityPlanAuth{} svc := planning.NewService(planning.Deps{Store: f.plans, Authz: auth, Capacity: managedDemandAuthority{policy: policy}}) plan := &planning.Plan{ID: "managed-plan", OrgID: "org", ProjectID: "proj", EnvironmentID: "env", CreatedBy: "usr"} - cfg := &planning.ServiceConfig{Provider: "kubernetes", Target: connection, TargetSettings: map[string]string{"managed_attachment_id": attachment, "managed_project_id": "proj", "managed_resource_id": "cluster", "architecture": arch}, Size: &manifest.Size{CPU: .5, Memory: 128}, Scale: &manifest.Scale{Min: 1, Max: 4}, CloudPlacement: &planning.CloudPlacement{CloudID: "cloud", CloudRevision: 1, AssignmentRevision: 1, TargetID: target, TargetRevision: 1, GrantRevision: 1, ConnectionID: connection, Provider: "kubernetes"}} + cfg := &planning.ServiceConfig{Provider: "kubernetes", Target: connection, TargetSettings: map[string]string{"managed_attachment_id": attachment, "managed_project_id": "proj", "managed_resource_id": "cluster", "architecture": arch}, Size: &manifest.Size{CPU: .5, Memory: 128}, Scale: &manifest.Scale{Min: 1, Max: 4}, CloudPlacement: &planning.CloudPlacement{CloudID: "cloud", CloudRevision: 1, TargetID: target, TargetRevision: 1, GrantRevision: 1, ConnectionID: connection, Provider: "kubernetes"}} result := &planning.Result{Executable: true, Connections: map[string]string{"kubernetes": connection}, Actions: []planning.Action{{ID: "service:api", Subject: planning.ServiceSubject, Name: "api", Op: planning.Create, Provider: "kubernetes", Service: cfg}}} return f, svc, plan, result, auth } diff --git a/tests/integration/deployment_capacity_wait_test.go b/tests/integration/deployment_capacity_wait_test.go index ad6f719ff..9f865cb0b 100644 --- a/tests/integration/deployment_capacity_wait_test.go +++ b/tests/integration/deployment_capacity_wait_test.go @@ -316,7 +316,7 @@ func TestDeploymentCapacityWaitRemainsActive(t *testing.T) { if _, e := st.CreateDeployment(t.Context(), next); e == nil { t.Fatal("database accepted a release over paused work") } - preview, snapshot, sync := persistAssignmentPreview(t, clouds, "wait-replacement", "cloud", 0) + preview, snapshot, sync := persistDefaultCloudPreview(t, clouds, "wait-replacement", "cloud") if _, e := clouds.Accept(t.Context(), preview, snapshot, sync, "wait-replacement"); !errors.Is(e, cloudprofiles.ErrBusy) { t.Fatalf("paused allowed replacement: %v", e) } diff --git a/tests/integration/fleet_scope_guards_test.go b/tests/integration/fleet_scope_guards_test.go index 49cafdbf1..23373a0a9 100644 --- a/tests/integration/fleet_scope_guards_test.go +++ b/tests/integration/fleet_scope_guards_test.go @@ -5,14 +5,17 @@ package integration import ( "context" "errors" + "slices" "testing" "github.com/xraph/loomplane/internal/cloudprofiles" + "github.com/xraph/loomplane/internal/connections" "github.com/xraph/loomplane/internal/deployments" "github.com/xraph/loomplane/internal/environments" "github.com/xraph/loomplane/internal/manifests" "github.com/xraph/loomplane/internal/planning" "github.com/xraph/loomplane/internal/projects" + "github.com/xraph/loomplane/internal/providers" "github.com/xraph/loomplane/internal/security" ) @@ -42,8 +45,13 @@ func TestFleetLegacyWriteDenied(t *testing.T) { if _, err = plans.ChooseConnection(t.Context(), p, "proj", env.Name, "kubernetes", planning.ChooseConnectionInput{}); !errors.Is(err, projects.ErrFleetManaged) { t.Fatalf("legacy connection: %v", err) } - if _, err = plans.PreviewCloudChange(t.Context(), p, "proj", cloudprofiles.ChangeInput{EnvironmentID: env.ID}); !errors.Is(err, projects.ErrFleetManaged) { - t.Fatalf("legacy cloud assignment: %v", err) + // A project default Cloud change reaches every environment of the + // project; a fleet-managed one blocks the review rather than move. + clouds := planning.NewService(planning.Deps{Projects: f.projects, Store: planning.NewPgStore(f.db), CloudProfiles: cloudprofiles.NewPgStore(f.db), Connections: &syncAccounts{store: connections.NewPgStore(f.db)}, Providers: providers.Registry(), Authz: fleetAuth{}, Manifests: noFleetSourceManifest{}}) + if preview, previewErr := clouds.PreviewCloudChange(t.Context(), p, "proj", cloudprofiles.ChangeInput{ProjectDefault: true, CloudID: "cloud"}); previewErr != nil || !slices.Contains(preview.Blockers, "Manage instance placement through its fleet.") { + t.Fatalf("legacy cloud assignment: %+v %v", preview, previewErr) + } else if _, applyErr := clouds.ApplyCloudChange(t.Context(), p, "proj", preview.ID, preview.Revision, "fleet"); applyErr == nil { + t.Fatal("blocked default Cloud change applied") } deploymentStore := fleetGuardDeploymentStore{deployment: &deployments.Deployment{ID: "deployment", OrgID: "org", ProjectID: "proj", EnvironmentID: env.ID, Status: deployments.StatusFailed}} deploymentAPI := deployments.NewService(deploymentStore, fleetAuth{}, nil, nil) diff --git a/tests/integration/managed_cleanup_effects_test.go b/tests/integration/managed_cleanup_effects_test.go index 655c5d09a..cec6e3fa7 100644 --- a/tests/integration/managed_cleanup_effects_test.go +++ b/tests/integration/managed_cleanup_effects_test.go @@ -46,7 +46,7 @@ func managedCleanupEffectsRealAPI(t *testing.T, shared bool, modes ...string) { f := &poolFixture{sql: e.sql, db: e.pg, store: e.store, plans: planning.NewPgStore(e.pg), clouds: e.clouds} for _, stmt := range []string{ `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('env','org','proj','production','production',now(),now())`, - `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1)`, + defaultCloudSQL("org", "proj", "cloud"), `INSERT INTO loomplane_manifests(id,org_id,project_id,revision,body,digest,created_by,created_at) VALUES('pool-manifest-proj','org','proj',1,'version: 1','pool','usr',now())`, } { if _, err := f.sql.Exec(t.Context(), stmt); err != nil { diff --git a/tests/integration/managed_cleanup_issuer_test.go b/tests/integration/managed_cleanup_issuer_test.go index f11eb9c89..ef224cb2d 100644 --- a/tests/integration/managed_cleanup_issuer_test.go +++ b/tests/integration/managed_cleanup_issuer_test.go @@ -111,7 +111,7 @@ func TestManagedCleanupIssuerRecovery(t *testing.T) { if _, checkErr := application.Issue(t.Context(), f.scope, f.request); checkErr == nil { t.Fatal("application scope reopened") } - if _, checkErr := f.sql.Exec(t.Context(), `DELETE FROM loomplane_cloud_assignments WHERE org_id='org' AND project_id='proj' AND environment_id='env'`); checkErr != nil { + if _, checkErr := f.sql.Exec(t.Context(), clearDefaultCloudSQL("org", "proj")); checkErr != nil { t.Fatal(checkErr) } j := f.store.Journal("org", g.ID) @@ -241,7 +241,7 @@ func TestManagedCleanupIssuerCurrentAuthorization(t *testing.T) { "unresolved-application": `INSERT INTO loomplane_managed_workload_issuances(id,org_id,release_id,epoch,scope,request) SELECT 'unknown-late-app',org_id,release_id,epoch,scope,request FROM loomplane_managed_workload_issuances WHERE cleanup_grant_id IS NULL LIMIT 1`, } if change == "target" { - if _, checkErr := f.sql.Exec(t.Context(), `DELETE FROM loomplane_cloud_assignments WHERE org_id='org'`); checkErr != nil { + if _, checkErr := f.sql.Exec(t.Context(), `UPDATE loomplane_cloud_project_grants SET is_default=false,revision=revision+1 WHERE org_id='org' AND is_default`); checkErr != nil { t.Fatal(checkErr) } historicalCleanupBindingLoss(t.Context(), t, f.sql, "org", "cleanup-binding") diff --git a/tests/integration/managed_cleanup_targets_test.go b/tests/integration/managed_cleanup_targets_test.go index 481be5867..8cba7521c 100644 --- a/tests/integration/managed_cleanup_targets_test.go +++ b/tests/integration/managed_cleanup_targets_test.go @@ -326,14 +326,20 @@ func cleanupSyncFixture(t *testing.T) (*poolFixture, *planning.Service, *cloudpr if err != nil { t.Fatal(err) } - generation, err := f.clouds.AssignmentGeneration(t.Context(), "org", "proj", "env") + // The review clears the project's default Cloud, reviewed against the + // default as it stands. + defaultCloud, generation, err := f.clouds.DefaultCloud(t.Context(), "org", "proj") + if err != nil { + t.Fatal(err) + } + before, err := f.clouds.ResolveCloud(t.Context(), "org", "proj", "") if err != nil { t.Fatal(err) } now := time.Now().UTC() envs := []cloudprofiles.EnvironmentChange{{EnvironmentID: "env", Environment: "production", Status: cloudprofiles.SyncPending}} - preview := &cloudprofiles.Preview{ID: "cleanup-preview", OrgID: "org", ProjectID: "proj", Revision: "cleanup-digest", Input: cloudprofiles.ChangeInput{EnvironmentID: "env", Revision: generation}, Environments: envs, CreatedAt: now} - snapshot := &cloudprofiles.Snapshot{Actor: security.Principal{OrgID: "org", UserID: "preview-author"}, Environments: []cloudprofiles.EnvironmentSnapshot{{EnvironmentID: "env", AssignmentRevision: generation, Bindings: bindings, Plan: raw}}, Connections: []string{scope.Connection}} + preview := &cloudprofiles.Preview{ID: "cleanup-preview", OrgID: "org", ProjectID: "proj", Revision: "cleanup-digest", Input: cloudprofiles.ChangeInput{ProjectDefault: true, Revision: generation}, BeforeCloud: before, Environments: envs, CreatedAt: now} + snapshot := &cloudprofiles.Snapshot{Actor: security.Principal{OrgID: "org", UserID: "preview-author"}, Environments: []cloudprofiles.EnvironmentSnapshot{{EnvironmentID: "env", DefaultCloud: defaultCloud, Bindings: bindings, Plan: raw}}, Connections: []string{scope.Connection}} if err = f.clouds.SavePreview(t.Context(), preview, snapshot); err != nil { t.Fatal(err) } @@ -402,7 +408,7 @@ func TestManagedCleanupCloudSyncApply(t *testing.T) { func TestManagedCleanupCloudSyncRollback(t *testing.T) { f, _, preview, snapshot, sync := cleanupSyncFixture(t) var generation int64 - if err := f.sql.QueryRow(t.Context(), `SELECT revision FROM loomplane_cloud_assignments WHERE environment_id='env'`).Scan(&generation); err != nil { + if err := f.sql.QueryRow(t.Context(), `SELECT revision FROM loomplane_cloud_project_grants WHERE org_id='org' AND project_id='proj' AND is_default`).Scan(&generation); err != nil { t.Fatal(err) } if _, err := f.sql.Exec(t.Context(), `UPDATE loomplane_managed_workload_authority SET revision=revision+1 WHERE org_id='org'`); err != nil { @@ -413,8 +419,8 @@ func TestManagedCleanupCloudSyncRollback(t *testing.T) { } var current int64 var effects int - if err := f.sql.QueryRow(t.Context(), `SELECT revision FROM loomplane_cloud_assignments WHERE environment_id='env'`).Scan(¤t); err != nil || current != generation { - t.Fatalf("assignment did not roll back: %d %v", current, err) + if err := f.sql.QueryRow(t.Context(), `SELECT revision FROM loomplane_cloud_project_grants WHERE org_id='org' AND project_id='proj' AND is_default`).Scan(¤t); err != nil || current != generation { + t.Fatalf("default Cloud did not roll back: %d %v", current, err) } if err := f.sql.QueryRow(t.Context(), `SELECT (SELECT count(*) FROM loomplane_cloud_syncs)+(SELECT count(*) FROM loomplane_managed_cleanup_intents)+(SELECT count(*) FROM loomplane_environment_sync_guards)`).Scan(&effects); err != nil || effects != 0 { t.Fatalf("partial acceptance: %d %v", effects, err) diff --git a/tests/integration/managed_cluster_maintenance_recovery_test.go b/tests/integration/managed_cluster_maintenance_recovery_test.go index 82df45d43..455d99ac8 100644 --- a/tests/integration/managed_cluster_maintenance_recovery_test.go +++ b/tests/integration/managed_cluster_maintenance_recovery_test.go @@ -289,7 +289,7 @@ func reviewedCountCohort(t *testing.T, f *poolFixture, r *cloudinfra.ManagedReso for _, q := range []string{ `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('env','org','proj','production','production',now(),now()) ON CONFLICT DO NOTHING`, `INSERT INTO loomplane_cloud_project_grants(org_id,cloud_id,project_id) VALUES('org','cloud','proj') ON CONFLICT DO NOTHING`, - `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1) ON CONFLICT DO NOTHING`, + defaultCloudSQL("org", "proj", "cloud"), `INSERT INTO loomplane_manifests(id,org_id,project_id,revision,body,digest,created_by,created_at) VALUES('pool-manifest-proj','org','proj',1,'version: 1','pool','usr',now())`, } { if _, err := f.sql.Exec(t.Context(), q); err != nil { @@ -334,7 +334,7 @@ func reviewedCountCohort(t *testing.T, f *poolFixture, r *cloudinfra.ManagedReso svc := planning.NewService(planning.Deps{Store: f.plans, Authz: &capacityPlanAuth{}, Capacity: managedDemandAuthority{}}) svc.BindManagedRuntime(ledgerRuntimeFixture{}) plan := &planning.Plan{ID: "manual-wait", OrgID: "org", ProjectID: "proj", EnvironmentID: "env", CreatedBy: "usr"} - cfg := &planning.ServiceConfig{Provider: "kubernetes", Target: "cluster-runtime", TargetSettings: map[string]string{"managed_attachment_id": "attachment", "managed_project_id": "proj", "managed_resource_id": "cluster", "architecture": "amd64"}, Size: &manifest.Size{CPU: .5, Memory: 128}, Scale: &manifest.Scale{Min: 1, Max: 90}, CloudPlacement: &planning.CloudPlacement{CloudID: "cloud", CloudRevision: 1, AssignmentRevision: 1, TargetID: "cluster-target", TargetRevision: 1, GrantRevision: 1, ConnectionID: "cluster-runtime", Provider: "kubernetes"}} + cfg := &planning.ServiceConfig{Provider: "kubernetes", Target: "cluster-runtime", TargetSettings: map[string]string{"managed_attachment_id": "attachment", "managed_project_id": "proj", "managed_resource_id": "cluster", "architecture": "amd64"}, Size: &manifest.Size{CPU: .5, Memory: 128}, Scale: &manifest.Scale{Min: 1, Max: 90}, CloudPlacement: &planning.CloudPlacement{CloudID: "cloud", CloudRevision: 1, TargetID: "cluster-target", TargetRevision: 1, GrantRevision: 1, ConnectionID: "cluster-runtime", Provider: "kubernetes"}} result := &planning.Result{Executable: true, Connections: map[string]string{"kubernetes": "cluster-runtime"}, Actions: []planning.Action{{ID: "service:api", Subject: planning.ServiceSubject, Name: "api", Op: planning.Create, Provider: "kubernetes", Service: cfg}}} if err = svc.PrepareClusterWorkloadDemands(t.Context(), plan, result); err != nil { diff --git a/tests/integration/managed_cluster_service_recovery_test.go b/tests/integration/managed_cluster_service_recovery_test.go index 219c22f87..1d6873b9b 100644 --- a/tests/integration/managed_cluster_service_recovery_test.go +++ b/tests/integration/managed_cluster_service_recovery_test.go @@ -581,12 +581,12 @@ func TestManagedClusterSecondNamespaceTrustAndCredentials(t *testing.T) { if _, err = f.sql.Exec(t.Context(), `INSERT INTO loomplane_projects(id,org_id,name,slug,status,created_by,created_at,updated_at) VALUES('proj-two','org','Two','two','ready','usr',now(),now())`); err != nil { t.Fatal(err) } - grantRevision, err := f.clouds.SetProjectGrant(t.Context(), "org", "cloud", "proj-two", nil, false) + grant, err := f.clouds.SetProjectGrant(t.Context(), "org", "cloud", "proj-two", nil, false) if err != nil { t.Fatal(err) } attachment.ProjectID = "proj-two" - attachment.GrantRevision = grantRevision + attachment.GrantRevision = grant.Revision t.Cleanup(func() { _ = f.bootstrap.Kube.CoreV1().Namespaces().Delete(context.Background(), attachment.Namespace, metav1.DeleteOptions{}) }) diff --git a/tests/integration/managed_clusters_store_test.go b/tests/integration/managed_clusters_store_test.go index a4793eee7..a2fdb7726 100644 --- a/tests/integration/managed_clusters_store_test.go +++ b/tests/integration/managed_clusters_store_test.go @@ -331,13 +331,13 @@ func TestManagedClusterTargetAttachmentScope(t *testing.T) { } for _, sql := range []string{ `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('env','org','proj','production','production',now(),now())`, - `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1)`, + defaultCloudSQL("org", "proj", "cloud"), } { if _, err := db.Exec(t.Context(), sql); err != nil { t.Fatal(err) } } - assignment, err := clouds.Resolve(t.Context(), "org", "proj", "env") + assignment, err := clouds.ResolveCloud(t.Context(), "org", "proj", "") if err != nil || len(assignment.Targets) != 1 { t.Fatalf("active target missing: %v %v", assignment, err) } @@ -346,7 +346,7 @@ func TestManagedClusterTargetAttachmentScope(t *testing.T) { if err = store.SaveRuntimeAttachment(t.Context(), attachment, 1); err != nil { t.Fatal(err) } - assignment, err = clouds.Resolve(t.Context(), "org", "proj", "env") + assignment, err = clouds.ResolveCloud(t.Context(), "org", "proj", "") if err != nil || len(assignment.Targets) != 0 { t.Fatalf("deleted attachment remains eligible: %v %v", assignment, err) } diff --git a/tests/integration/managed_lifecycle_cleanup_fixture_test.go b/tests/integration/managed_lifecycle_cleanup_fixture_test.go index 56246c487..20be81346 100644 --- a/tests/integration/managed_lifecycle_cleanup_fixture_test.go +++ b/tests/integration/managed_lifecycle_cleanup_fixture_test.go @@ -52,7 +52,7 @@ func lifecycleCleanupFixture(t *testing.T, a *capacityAPI, attachmentID string) if err = a.sql.QueryRow(ctx, `SELECT id FROM loomplane_cloud_targets WHERE org_id=$1 AND connection_id=$2`, a.org, attachment.RuntimeConnectionID).Scan(&target); err != nil { t.Fatal(err) } - if _, err = a.sql.Exec(ctx, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES($1,$2,$3,$4,1) ON CONFLICT DO NOTHING`, a.org, a.project, environment, a.cloud); err != nil { + if _, err = a.sql.Exec(ctx, defaultCloudSQL(a.org, a.project, a.cloud)); err != nil { t.Fatal(err) } infrastructure, err := forge.InjectType[*cloudinfra.Service](a.r.app.(forge.App).Container()) @@ -64,7 +64,7 @@ func lifecycleCleanupFixture(t *testing.T, a *capacityAPI, attachmentID string) t.Fatal(err) } plan := &planning.Plan{ID: "fixture-cleanup-plan", OrgID: a.org, ProjectID: a.project, EnvironmentID: environment, Environment: "production", CreatedBy: owner} - cfg := &planning.ServiceConfig{Provider: "kubernetes", Target: attachment.RuntimeConnectionID, TargetSettings: map[string]string{"managed_attachment_id": attachmentID, "managed_project_id": a.project, "managed_resource_id": r.ID, "architecture": "amd64"}, CapacityMode: "best_effort", Size: &manifest.Size{CPU: .5, Memory: 128}, Scale: &manifest.Scale{Min: 1, Max: 1}, CloudPlacement: &planning.CloudPlacement{CloudID: a.cloud, CloudRevision: 1, AssignmentRevision: 1, TargetID: target, TargetRevision: 1, GrantRevision: 1, ConnectionID: attachment.RuntimeConnectionID, Provider: "kubernetes"}} + cfg := &planning.ServiceConfig{Provider: "kubernetes", Target: attachment.RuntimeConnectionID, TargetSettings: map[string]string{"managed_attachment_id": attachmentID, "managed_project_id": a.project, "managed_resource_id": r.ID, "architecture": "amd64"}, CapacityMode: "best_effort", Size: &manifest.Size{CPU: .5, Memory: 128}, Scale: &manifest.Scale{Min: 1, Max: 1}, CloudPlacement: &planning.CloudPlacement{CloudID: a.cloud, CloudRevision: 1, TargetID: target, TargetRevision: 1, GrantRevision: 1, ConnectionID: attachment.RuntimeConnectionID, Provider: "kubernetes"}} result := &planning.Result{Executable: true, Connections: map[string]string{"kubernetes": attachment.RuntimeConnectionID}, Actions: []planning.Action{{ID: "service:fixture", Subject: planning.ServiceSubject, Name: "fixture", Op: planning.Create, Provider: "kubernetes", Service: cfg}}} if err = svc.PrepareClusterWorkloadDemands(ctx, plan, result); err != nil { t.Fatal(err) diff --git a/tests/integration/managed_workload_installed_test.go b/tests/integration/managed_workload_installed_test.go index 1e38c785e..e352f7689 100644 --- a/tests/integration/managed_workload_installed_test.go +++ b/tests/integration/managed_workload_installed_test.go @@ -94,7 +94,7 @@ func installedApplication(ctx context.Context, t *testing.T, e *enrollmentServic t.Fatal(err) } cfg.TargetSettings = planning.ReviewedConnectionSettings(c.Cloud, c.Details) - assignment, err := f.clouds.Resolve(ctx, p.OrgID, p.ProjectID, p.EnvironmentID) + assignment, err := f.clouds.ResolveCloud(ctx, p.OrgID, p.ProjectID, cfg.CloudPlacement.CloudID) if err != nil { t.Fatal(err) } @@ -103,7 +103,6 @@ func installedApplication(ctx context.Context, t *testing.T, e *enrollmentServic t.Fatal(err) } cfg.CloudPlacement.CloudRevision = assignment.CloudRevision - cfg.CloudPlacement.AssignmentRevision = assignment.Revision cfg.CloudPlacement.TargetName, cfg.CloudPlacement.TargetRevision = targetPin.Name, targetPin.Revision cfg.CloudPlacement.AccountIdentity = connections.AccountIdentity(c.Cloud, c.Account, c.Details) cfg.CloudPlacement.Region, cfg.Region, a.Region = targetPin.Region, targetPin.Region, targetPin.Region diff --git a/tests/integration/nodes_test.go b/tests/integration/nodes_test.go index d1fc1aff5..d3f2104c2 100644 --- a/tests/integration/nodes_test.go +++ b/tests/integration/nodes_test.go @@ -34,7 +34,6 @@ import ( "github.com/xraph/loomplane/internal/cloudprofiles" "github.com/xraph/loomplane/internal/config" "github.com/xraph/loomplane/internal/nodes" - apiclient "github.com/xraph/loomplane/pkg/client" "github.com/xraph/loomplane/pkg/nodeproto" ) @@ -863,11 +862,7 @@ func TestNodeDeploysAndServes(t *testing.T) { mustE2E(t, c, http.StatusOK, http.MethodPut, cloudBase+"/projects/"+project, map[string]any{"target_ids": []string{}}, nil) var target cloudprofiles.Target mustE2E(t, c, http.StatusCreated, http.MethodPost, base+"/clouds/"+cloud.ID+"/targets", cloudprofiles.CreateTargetInput{Name: "node", Provider: "server", Runtime: "server", PoolID: pool.ID}, &target) - var preview cloudprofiles.Preview - mustE2E(t, c, http.StatusOK, http.MethodPost, base+"/environments/"+environment+"/cloud/preview", apiclient.EnvironmentCloudInput{CloudID: cloud.ID}, &preview) - if result := waitCloudAPI(t, c, base, applyCloudAPI(t, c, base, &preview, "assign-e2e").ID); result.Status != cloudprofiles.SyncSucceeded { - t.Fatalf("the environment's Cloud assignment: %+v", result) - } + makeDefaultCloudAPI(t, c, base, cloud.ID, "assign-e2e") mustE2E(t, c, http.StatusCreated, http.MethodPost, base+"/variables", map[string]any{"key": "WHOAMI_NAME", "value": webName, "environment": "production"}, nil) e2ePlan(t, c, project, webManifest) var op cloudinfra.RouteOperation diff --git a/tests/integration/server_admission_lock_test.go b/tests/integration/server_admission_lock_test.go index 9d40bb27b..c8bb2b6cc 100644 --- a/tests/integration/server_admission_lock_test.go +++ b/tests/integration/server_admission_lock_test.go @@ -192,16 +192,23 @@ func TestServerAdmissionDirectApplyLetsApprovalThrough(t *testing.T) { // after the organization lock. A direct apply on one of those daemons // mustn't hold it up. The direct plan was approved and started before the // server joined the pool, as in TestGPUAdmissionSerializesPooledAfterDirect, -// and runs in an environment outside the Cloud, so the sync has no reason -// of its own to wait for it. +// and runs in a project that doesn't use the Cloud, so the sync has no +// reason of its own to wait for it. (Every environment of a project whose +// default Cloud this is takes part in the sync.) func TestServerAdmissionDirectApplyLetsCloudSyncThrough(t *testing.T) { // Only the executor pause: the server rejoins the pool during the pause, // so a run paused before its pool check would just be refused. for _, pause := range []directPause{inExecutor} { t.Run(string(pause), func(t *testing.T) { f, svc := sharedAcceptanceFixture(t) - if _, err := f.sql.Exec(t.Context(), `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('side','org','proj','side','staging',now(),now())`); err != nil { - t.Fatal(err) + for _, query := range []string{ + `INSERT INTO loomplane_projects(id,org_id,name,slug,status,created_by,created_at,updated_at) VALUES('side','org','Side','side','ready','usr',now(),now())`, + `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('side','org','side','side','staging',now(),now())`, + `INSERT INTO loomplane_manifests(id,org_id,project_id,revision,body,digest,created_by,created_at) VALUES('pool-manifest-side','org','side',1,'version: 1','pool','usr',now())`, + } { + if _, err := f.sql.Exec(t.Context(), query); err != nil { + t.Fatal(err) + } } p := reviewPoolChange(t, svc) var listed bool diff --git a/tests/integration/server_pool_sizing_test.go b/tests/integration/server_pool_sizing_test.go index 7df0c7d72..d767ded3f 100644 --- a/tests/integration/server_pool_sizing_test.go +++ b/tests/integration/server_pool_sizing_test.go @@ -20,7 +20,6 @@ import ( "github.com/xraph/loomplane/internal/connections" "github.com/xraph/loomplane/internal/planning" "github.com/xraph/loomplane/internal/security" - apiclient "github.com/xraph/loomplane/pkg/client" ) func TestServerPoolSizingPublicPlanApproval(t *testing.T) { @@ -92,11 +91,7 @@ func TestServerPoolSizingPublicPlanApproval(t *testing.T) { if env == "" { t.Fatal("production environment missing") } - var preview cloudprofiles.Preview - c.must(http.StatusOK, http.MethodPost, base+"/environments/"+env+"/cloud/preview", apiclient.EnvironmentCloudInput{CloudID: cloud.ID}, &preview) - if result := waitCloudAPI(t, c, base, applyCloudAPI(t, c, base, &preview, "sizing-assignment").ID); result.Status != cloudprofiles.SyncSucceeded { - t.Fatalf("assignment: %+v", result) - } + makeDefaultCloudAPI(t, c, base, cloud.ID, "sizing-assignment") // A pooled host can't build untrusted source (build isolation), so // the service ships a pinned image and the test stays on sizing. manifest := fmt.Sprintf("version: 1\nservices:\n api:\n source: go:services/api\n cloud_target: %s\n public: false\n build: {image: traefik/whoami:v1.11.0@sha256:200689790a0a0ea48ca45992e0450bc26ccab5307375b41c84dfc4f2475937ab}\n%signore:\n resources: [postgres, redis]\n", target.Name, tc.size) diff --git a/tests/integration/server_pools_test.go b/tests/integration/server_pools_test.go index 053d8dfd7..f319a095f 100644 --- a/tests/integration/server_pools_test.go +++ b/tests/integration/server_pools_test.go @@ -59,7 +59,7 @@ func newPoolFixture(t *testing.T) *poolFixture { if err := clouds.CreateTarget(t.Context(), &cloudprofiles.Target{ID: "pool-target", OrgID: "org", ProjectID: "proj", CloudID: "cloud", Name: "shared", DisplayName: "Shared", Provider: "server", Runtime: "server", PoolID: "pool", Revision: 1, CreatedAt: now, UpdatedAt: now}); err != nil { t.Fatal(err) } - for _, query := range []string{`INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1),('org','proj','stage','cloud',1)`, `INSERT INTO loomplane_projects(id,org_id,name,slug,status,created_by,created_at,updated_at) VALUES('second','org','Second','second','ready','usr',now(),now())`, `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('second-env','org','second','production','production',now(),now())`, `INSERT INTO loomplane_cloud_project_grants(org_id,cloud_id,project_id) VALUES('org','cloud','second')`, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','second','second-env','cloud',1)`} { + for _, query := range []string{defaultCloudSQL("org", "proj", "cloud"), `INSERT INTO loomplane_projects(id,org_id,name,slug,status,created_by,created_at,updated_at) VALUES('second','org','Second','second','ready','usr',now(),now())`, `INSERT INTO loomplane_environments(id,org_id,project_id,name,kind,created_at,updated_at) VALUES('second-env','org','second','production','production',now(),now())`, `INSERT INTO loomplane_cloud_project_grants(org_id,cloud_id,project_id) VALUES('org','cloud','second')`, defaultCloudSQL("org", "second", "cloud")} { if _, err := sql.Exec(t.Context(), query); err != nil { t.Fatal(err) } @@ -73,14 +73,19 @@ func newPoolFixture(t *testing.T) *poolFixture { } func (f *poolFixture) request(env, name string) cloudinfra.PlacementRequest { project := "proj" - if env == "second-env" { + switch env { + case "second-env": project = "second" + case "side": + // A project of its own with no Cloud, so nothing reviewed on the + // Cloud reaches it. + project = "side" } return cloudinfra.PlacementRequest{OrgID: "org", ProjectID: project, EnvironmentID: env, CloudID: "cloud", TargetID: "pool-target", TargetRevision: 1, PoolID: "pool", Service: name, CPUMillis: 1000, MemoryBytes: 512 << 20, Replicas: 1, Architecture: "amd64"} } func (f *poolFixture) plan(t *testing.T, id string, r cloudinfra.PlacementRequest, p *cloudinfra.Placement) *planning.CloudPlacement { t.Helper() - pin := &planning.CloudPlacement{Allocation: p.Allocation, CloudID: "cloud", CloudRevision: 1, GrantRevision: 1, AssignmentRevision: 1, TargetID: "pool-target", TargetRevision: 1, TargetName: "shared", Provider: "server", ConnectionID: p.ConnectionID, AccountIdentity: connections.AccountIdentity("server", p.ConnectionID, map[string]string{"docker_id": p.ConnectionID, "architecture": "amd64"}), PoolID: p.PoolID, PoolRevision: p.PoolRevision, ServerID: p.ServerID, ServerRevision: p.ServerRevision, ConnectionGeneration: p.ConnectionGeneration, CPUMillis: p.CPUMillis, MemoryBytes: p.MemoryBytes, GPUKind: p.GPUKind, GPUs: p.GPUs} + pin := &planning.CloudPlacement{Allocation: p.Allocation, CloudID: "cloud", CloudRevision: 1, GrantRevision: 1, TargetID: "pool-target", TargetRevision: 1, TargetName: "shared", Provider: "server", ConnectionID: p.ConnectionID, AccountIdentity: connections.AccountIdentity("server", p.ConnectionID, map[string]string{"docker_id": p.ConnectionID, "architecture": "amd64"}), PoolID: p.PoolID, PoolRevision: p.PoolRevision, ServerID: p.ServerID, ServerRevision: p.ServerRevision, ConnectionGeneration: p.ConnectionGeneration, CPUMillis: p.CPUMillis, MemoryBytes: p.MemoryBytes, GPUKind: p.GPUKind, GPUs: p.GPUs} size := &manifest.Size{CPU: float64(r.CPUMillis) / 1000, Memory: int(r.MemoryBytes >> 20)} if r.GPUs > 0 { size.GPU = &manifest.GPU{Kind: r.GPUKind, Count: int(r.GPUs)} diff --git a/tests/integration/shared_cloud_combined_test.go b/tests/integration/shared_cloud_combined_test.go index 7e9f086e3..980df0cf9 100644 --- a/tests/integration/shared_cloud_combined_test.go +++ b/tests/integration/shared_cloud_combined_test.go @@ -29,7 +29,6 @@ import ( "github.com/xraph/loomplane/internal/cloudprofiles" "github.com/xraph/loomplane/internal/clouds/server" "github.com/xraph/loomplane/internal/planning" - apiclient "github.com/xraph/loomplane/pkg/client" ) type combinedHost struct { @@ -435,11 +434,7 @@ func TestAcceptanceSharedCloudCombined(t *testing.T) { var target cloudprofiles.Target c.must(http.StatusCreated, http.MethodPost, base+"/clouds/"+cloud.ID+"/targets", cloudprofiles.CreateTargetInput{Name: fmt.Sprintf("app%d", index), Provider: "server", Runtime: "server", PoolID: pools[roles[index]].ID}, &target) targets[project] = target - var preview cloudprofiles.Preview - c.must(http.StatusOK, http.MethodPost, base+"/environments/"+environments[project]+"/cloud/preview", apiclient.EnvironmentCloudInput{CloudID: cloud.ID}, &preview) - if result := waitCloudAPI(t, c, base, applyCloudAPI(t, c, base, &preview, "assign-"+project).ID); result.Status != cloudprofiles.SyncSucceeded { - t.Fatalf("assignment: %+v", result) - } + makeDefaultCloudAPI(t, c, base, cloud.ID, "assign-"+project) marker := state.RunID + "-" + project + "-release-one" markers[project] = marker var variable struct{ ID string } diff --git a/tests/integration/shared_cloud_live_acceptance_test.go b/tests/integration/shared_cloud_live_acceptance_test.go index 4793d1707..e5074734c 100644 --- a/tests/integration/shared_cloud_live_acceptance_test.go +++ b/tests/integration/shared_cloud_live_acceptance_test.go @@ -28,7 +28,6 @@ import ( "github.com/xraph/loomplane/internal/cloudinfra" "github.com/xraph/loomplane/internal/cloudprofiles" "github.com/xraph/loomplane/internal/planning" - apiclient "github.com/xraph/loomplane/pkg/client" "github.com/joho/godotenv" "github.com/xraph/grove" @@ -867,12 +866,7 @@ func liveLifecycle(t *testing.T, c *client, cfg config.Config, l *liveLedger, p var target cloudprofiles.Target c.must(http.StatusCreated, http.MethodPost, base+"/clouds/"+cloud.ID+"/targets", cloudprofiles.CreateTargetInput{Name: fmt.Sprintf("app%d", index), Provider: "server", Runtime: "server", PoolID: pools[hostIndices[index]].ID}, &target) targets = append(targets, target) - var preview cloudprofiles.Preview - c.must(http.StatusOK, http.MethodPost, base+"/environments/"+environment+"/cloud/preview", apiclient.EnvironmentCloudInput{CloudID: cloud.ID}, &preview) - if result := waitCloudAPI(t, c, base, applyCloudAPI(t, c, base, &preview, "assign-"+project).ID); result.Status != cloudprofiles.SyncSucceeded { - progress.failure(t, "assignment_failed") - t.Fatal("live assignment failed") - } + makeDefaultCloudAPI(t, c, base, cloud.ID, "assign-"+project) marker := l.RunID + "-" + project + "-release-one" markers = append(markers, marker) var variable struct{ ID string } diff --git a/tests/integration/shared_cloud_recovery_fixture_test.go b/tests/integration/shared_cloud_recovery_fixture_test.go index f7379a114..a60c9a0b4 100644 --- a/tests/integration/shared_cloud_recovery_fixture_test.go +++ b/tests/integration/shared_cloud_recovery_fixture_test.go @@ -29,7 +29,6 @@ import ( "github.com/xraph/loomplane/internal/config" "github.com/xraph/loomplane/internal/connections" "github.com/xraph/loomplane/internal/planning" - apiclient "github.com/xraph/loomplane/pkg/client" ) type recoveryFixture struct { @@ -153,9 +152,7 @@ func newRecoveryFixture(t *testing.T) *recoveryFixture { } } c.must(http.StatusCreated, http.MethodPost, base+"/clouds/"+f.cloud.ID+"/targets", cloudprofiles.CreateTargetInput{Name: "direct", Provider: "server", Runtime: "managed", ConnectionID: f.connections["host1"].ID}, &f.target) - var preview cloudprofiles.Preview - c.must(http.StatusOK, http.MethodPost, base+"/environments/"+f.environment+"/cloud/preview", apiclient.EnvironmentCloudInput{CloudID: f.cloud.ID}, &preview) - waitCloudAPI(t, c, base, applyCloudAPI(t, c, base, &preview, "recovery-assignment").ID) + makeDefaultCloudAPI(t, c, base, f.cloud.ID, "recovery-assignment") manifest := "version: 1\nservices:\n web:\n source: node:apps/web\n cloud_target: direct\n public: false\n port: 80\n health_path: /\n size: {cpu: 0.2, memory: 128}\n build: {image: traefik/whoami:v1.11.0@sha256:200689790a0a0ea48ca45992e0450bc26ccab5307375b41c84dfc4f2475937ab}\nignore:\n resources: [postgres, redis]\n" f.manifest = manifest c.must(http.StatusCreated, http.MethodPut, base+"/manifest", map[string]string{"yaml": manifest}, nil) @@ -543,9 +540,7 @@ func (f *recoveryFixture) routedProject() { } } f.c.must(http.StatusCreated, http.MethodPost, base+"/clouds/"+f.cloud.ID+"/targets", cloudprofiles.CreateTargetInput{Name: "routed", Provider: "server", Runtime: "server", PoolID: pool.ID}, &f.target) - var preview cloudprofiles.Preview - f.c.must(http.StatusOK, http.MethodPost, base+"/environments/"+f.environment+"/cloud/preview", apiclient.EnvironmentCloudInput{CloudID: f.cloud.ID}, &preview) - waitCloudAPI(t, f.c, base, applyCloudAPI(t, f.c, base, &preview, "routed-assignment").ID) + makeDefaultCloudAPI(t, f.c, base, f.cloud.ID, "routed-assignment") f.manifest = strings.Replace(f.manifest, "cloud_target: direct", "cloud_target: routed", 1) f.marker = f.state.RunID + "-routed" var variable struct{ ID string } diff --git a/tests/integration/shared_clouds_test.go b/tests/integration/shared_clouds_test.go index 48d374cfc..a58f02e20 100644 --- a/tests/integration/shared_clouds_test.go +++ b/tests/integration/shared_clouds_test.go @@ -39,7 +39,7 @@ func TestSharedCloudGrantIsolationAndProjectRemoval(t *testing.T) { } } grants, ok := any(st).(interface { - SetProjectGrant(context.Context, string, string, string, []string, bool) (int64, error) + SetProjectGrant(context.Context, string, string, string, []string, bool) (*cloudprofiles.ProjectGrant, error) }) if !ok { t.Fatal("organization Cloud grant persistence is missing") @@ -47,9 +47,10 @@ func TestSharedCloudGrantIsolationAndProjectRemoval(t *testing.T) { if _, err := st.GetProfile(ctx, "org", "second", "cloud"); !errors.Is(err, cloudprofiles.ErrNotFound) { t.Fatalf("ungranted Cloud: %v", err) } - revision, err := grants.SetProjectGrant(ctx, "org", "cloud", "second", []string{"target"}, false) - if err != nil || revision != 1 { - t.Fatalf("grant: %d %v", revision, err) + // The project's first grant becomes its default Cloud. + grant, err := grants.SetProjectGrant(ctx, "org", "cloud", "second", []string{"target"}, false) + if err != nil || grant.Revision != 1 || !grant.Default { + t.Fatalf("grant: %+v %v", grant, err) } if _, err = st.GetTarget(ctx, "org", "second", "cloud", "target"); err != nil { t.Fatal(err) @@ -73,23 +74,26 @@ func TestSharedCloudGrantIsolationAndProjectRemoval(t *testing.T) { if _, err = grants.SetProjectGrant(ctx, "org", "cloud", "foreign", nil, false); !errors.Is(err, cloudprofiles.ErrNotFound) { t.Fatalf("cross organization grant: %v", err) } - if _, err = conn.Exec(ctx, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','second','second-env','cloud',1)`); err != nil { - t.Fatal(err) - } - assignment, err := st.Resolve(ctx, "org", "second", "second-env") - if err != nil || assignment == nil || len(assignment.Targets) != 1 { - t.Fatalf("shared assignment: %+v %v", assignment, err) + assignment, err := st.ResolveCloud(ctx, "org", "second", "") + if err != nil || assignment == nil || assignment.CloudID != "cloud" || !assignment.Default || len(assignment.Targets) != 1 { + t.Fatalf("shared default Cloud: %+v %v", assignment, err) } - revision, err = grants.SetProjectGrant(ctx, "org", "cloud", "second", nil, true) - if err != nil || revision != 2 { - t.Fatalf("revoke: %d %v", revision, err) + grant, err = grants.SetProjectGrant(ctx, "org", "cloud", "second", nil, true) + if err != nil || grant.Revision != 2 || grant.Default { + t.Fatalf("revoke: %+v %v", grant, err) } - if _, err = st.Resolve(ctx, "org", "second", "second-env"); !errors.Is(err, cloudprofiles.ErrNotFound) { + if _, err = st.ResolveCloud(ctx, "org", "second", "cloud"); !errors.Is(err, cloudprofiles.ErrNotFound) { t.Fatalf("revoked placement resolved: %v", err) } - var count int - if err = conn.QueryRow(ctx, `SELECT count(*) FROM loomplane_cloud_assignments WHERE project_id='second'`).Scan(&count); err != nil || count != 1 { - t.Fatalf("revocation removed assignment: %d %v", count, err) + if assignment, err = st.ResolveCloud(ctx, "org", "second", ""); err != nil || assignment != nil { + t.Fatalf("revoked grant stayed the default: %+v %v", assignment, err) + } + // Revocation keeps the grant row, so retained cleanup still reaches it. + if kept, keptErr := st.GetProjectGrant(ctx, "org", "cloud", "second"); keptErr != nil || !kept.Revoked || kept.Default || kept.Revision != 2 { + t.Fatalf("revocation removed the grant: %+v %v", kept, keptErr) + } + if retained, retainedErr := st.RetainedCloud(ctx, "org", "second", "cloud"); retainedErr != nil || retained == nil || retained.CloudID != "cloud" { + t.Fatalf("revocation lost the retained Cloud: %+v %v", retained, retainedErr) } if _, err = conn.Exec(ctx, `DELETE FROM loomplane_projects WHERE id='proj'`); err != nil { t.Fatal(err) @@ -110,10 +114,11 @@ func TestSharedCloudPreviewParticipantsAndRevocation(t *testing.T) { t.Fatal(err) } } - if _, err := st.SetProjectGrant(ctx, "org", "cloud", "second", []string{"target"}, false); err != nil { - t.Fatal(err) + // The second project's first grant makes the Cloud its default. + if grant, err := st.SetProjectGrant(ctx, "org", "cloud", "second", []string{"target"}, false); err != nil || !grant.Default { + t.Fatalf("grant: %+v %v", grant, err) } - if _, err := conn.Exec(ctx, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1),('org','second','second-env','cloud',1)`); err != nil { + if _, err := conn.Exec(ctx, defaultCloudSQL("org", "proj", "cloud")); err != nil { t.Fatal(err) } service := planning.NewService(planning.Deps{Store: planning.NewPgStore(db), Projects: projects.NewPgStore(db), CloudProfiles: st, Connections: &syncAccounts{store: connections.NewPgStore(db)}, Providers: providers.Registry(), Authz: &syncAuth{}}) @@ -122,7 +127,8 @@ func TestSharedCloudPreviewParticipantsAndRevocation(t *testing.T) { if err != nil { t.Fatal(err) } - if len(preview.Environments) != 2 || preview.Environments[0].ProjectID != "proj" || preview.Environments[1].ProjectID != "second" { + // Every environment of each project whose default the Cloud is takes part. + if len(preview.Environments) != 3 || preview.Environments[0].EnvironmentID != "env" || preview.Environments[1].EnvironmentID != "stage" || preview.Environments[2].ProjectID != "second" { t.Fatalf("participants: %+v", preview.Environments) } if _, err = st.SetProjectGrant(ctx, "org", "cloud", "second", []string{"target"}, false); err != nil { @@ -139,11 +145,17 @@ func TestSharedCloudPreviewParticipantsAndRevocation(t *testing.T) { if err != nil { t.Fatal(err) } - if _, assignErr := conn.Exec(ctx, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','stage','cloud',1)`); assignErr == nil || !strings.Contains(assignErr.Error(), "unfinished migration") { + // No project can make the Cloud its default, and so join the change, + // while the accepted change is unfinished. + if _, assignErr := conn.Exec(ctx, `INSERT INTO loomplane_projects(id,org_id,name,slug,status,created_by,created_at,updated_at) VALUES('third','org','Third','third','ready','usr',now(),now())`); assignErr != nil { + t.Fatal(assignErr) + } + if _, assignErr := conn.Exec(ctx, defaultCloudSQL("org", "third", "cloud")); assignErr == nil || !strings.Contains(assignErr.Error(), "unfinished migration") { t.Fatalf("new participant joined accepted sync: %v", assignErr) } _, snapshot, err := st.GetSync(ctx, "org", "", sync.ID) - if err != nil || !snapshot.Shared || len(snapshot.Grants) != 2 { + // One grant pin per participant environment. + if err != nil || !snapshot.Shared || len(snapshot.Grants) != 3 { t.Fatalf("stored scope: %+v %v", snapshot, err) } for _, env := range []struct{ project, id string }{{"proj", "env"}, {"second", "second-env"}} { @@ -165,7 +177,7 @@ func TestSharedCloudPreviewParticipantsAndRevocation(t *testing.T) { func TestSharedCloudLegacySyncScope(t *testing.T) { st, _, _ := cloudSyncDatabase(t) ctx := t.Context() - p, snapshot, sync := persistAssignmentPreview(t, st, "legacy", "cloud", 0) + p, snapshot, sync := persistDefaultCloudPreview(t, st, "legacy", "cloud") accepted, err := st.Accept(ctx, p, snapshot, sync, "legacy") if err != nil { t.Fatal(err) @@ -328,7 +340,7 @@ func TestSharedCloudProjectCannotManageSharedInfrastructure(t *testing.T) { if _, err := service.PreviewCloudChange(t.Context(), actor, "proj", cloudprofiles.ChangeInput{CloudID: "cloud", TargetID: "target", Revision: 1, Provider: "vercel", ConnectionID: "new"}); !errors.Is(err, security.ErrForbidden) { t.Fatalf("project member changed shared target: %v", err) } - if _, err := service.PreviewCloudChange(t.Context(), actor, "proj", cloudprofiles.ChangeInput{CloudID: "cloud", EnvironmentID: "env", Revision: 0}); err != nil { + if _, err := service.PreviewCloudChange(t.Context(), actor, "proj", cloudprofiles.ChangeInput{CloudID: "cloud", ProjectDefault: true, Revision: 0}); err != nil { t.Fatalf("project release authority rejected: %v", err) } } @@ -347,46 +359,44 @@ func TestSharedCloudRevokedPreviewKeepsTargetsPrivate(t *testing.T) { if _, err = st.SetProjectGrant(ctx, "org", "cloud", "proj", []string{"target"}, false); err != nil { t.Fatal(err) } - if _, err = conn.Exec(ctx, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1)`); err != nil { + if _, err = conn.Exec(ctx, defaultCloudSQL("org", "proj", "cloud")); err != nil { + t.Fatal(err) + } + _, grantRevision, err := st.DefaultCloud(ctx, "org", "proj") + if err != nil { t.Fatal(err) } service := planning.NewService(planning.Deps{Store: planning.NewPgStore(db), Projects: projects.NewPgStore(db), CloudProfiles: st, Connections: &syncAccounts{store: connections.NewPgStore(db)}, Providers: providers.Registry(), Authz: sharedProjectAuthorizer{}}) actor := security.Principal{OrgID: "org", UserID: "developer"} - authorizedPreview, err := service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{EnvironmentID: "env", Revision: 1}) + authorizedPreview, err := service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{ProjectDefault: true, Revision: grantRevision}) if err != nil { t.Fatal(err) } - if authorizedPreview.BeforeAssignment == nil || len(authorizedPreview.BeforeAssignment.Targets) != 1 || authorizedPreview.BeforeAssignment.Targets[0].ID != "target" { - t.Fatalf("allowed preview target missing: %+v", authorizedPreview.BeforeAssignment) + if authorizedPreview.BeforeCloud == nil || len(authorizedPreview.BeforeCloud.Targets) != 1 || authorizedPreview.BeforeCloud.Targets[0].ID != "target" { + t.Fatalf("allowed preview target missing: %+v", authorizedPreview.BeforeCloud) } if _, err = st.SetProjectGrant(ctx, "org", "cloud", "proj", nil, true); err != nil { t.Fatal(err) } - preview, err := service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{EnvironmentID: "env", Revision: 1}) - if err != nil { - t.Fatal(err) + // Revocation ended the default, and a revoked Cloud can't become one. + if _, err = service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{ProjectDefault: true, CloudID: "cloud", Revision: 0}); !errors.Is(err, cloudprofiles.ErrNotFound) { + t.Fatalf("revoked Cloud reviewed as the default: %v", err) } check := func(preview *cloudprofiles.Preview) { t.Helper() - if preview.BeforeAssignment == nil || preview.BeforeAssignment.CloudID != "cloud" { - t.Fatalf("retained assignment reference missing: %+v", preview.BeforeAssignment) + if preview.BeforeCloud == nil || preview.BeforeCloud.CloudID != "cloud" { + t.Fatalf("retained Cloud reference missing: %+v", preview.BeforeCloud) } - if len(preview.BeforeAssignment.Targets) != 0 { - t.Errorf("revoked preview exposed target configurations: %+v", preview.BeforeAssignment.Targets) + if len(preview.BeforeCloud.Targets) != 0 { + t.Errorf("revoked preview exposed target configurations: %+v", preview.BeforeCloud.Targets) } } - check(preview) - stored, err := service.CloudPreview(ctx, actor, "proj", preview.ID) - if err != nil { - t.Fatal(err) - } - check(stored) - stored, err = service.CloudPreview(ctx, actor, "proj", authorizedPreview.ID) + stored, err := service.CloudPreview(ctx, actor, "proj", authorizedPreview.ID) if err != nil { t.Fatal(err) } check(stored) - retained, err := st.RetainedAssignment(ctx, "org", "proj", "env") + retained, err := st.RetainedCloud(ctx, "org", "proj", "cloud") if err != nil || len(retained.Targets) != 2 { t.Fatalf("private retained comparison state lost: %+v %v", retained, err) } @@ -589,14 +599,14 @@ func TestSharedCloudPreviewDefaultFollowsCurrentGrant(t *testing.T) { if _, err := conn.Exec(ctx, `UPDATE loomplane_cloud_profiles SET default_provider='vercel',default_connection_id='old',default_region='private-region',revision=revision+1 WHERE id='cloud'`); err != nil { t.Fatal(err) } - if _, err := conn.Exec(ctx, `INSERT INTO loomplane_cloud_assignments(org_id,project_id,environment_id,cloud_id,revision) VALUES('org','proj','env','cloud',1)`); err != nil { + if _, err := conn.Exec(ctx, defaultCloudSQL("org", "proj", "cloud")); err != nil { t.Fatal(err) } - assignment, err := st.RetainedAssignment(ctx, "org", "proj", "env") + assignment, err := st.RetainedCloud(ctx, "org", "proj", "cloud") if err != nil { t.Fatal(err) } - preview := &cloudprofiles.Preview{ID: "default-review", OrgID: "org", ProjectID: "proj", Revision: "immutable-review", BeforeAssignment: assignment, AfterAssignment: assignment, Input: cloudprofiles.ChangeInput{EnvironmentID: "env"}, CreatedAt: time.Now().UTC()} + preview := &cloudprofiles.Preview{ID: "default-review", OrgID: "org", ProjectID: "proj", Revision: "immutable-review", BeforeCloud: assignment, AfterCloud: assignment, Input: cloudprofiles.ChangeInput{ProjectDefault: true}, CreatedAt: time.Now().UTC()} snapshot := &cloudprofiles.Snapshot{Connections: []string{"old"}} if err = st.SavePreview(ctx, preview, snapshot); err != nil { t.Fatal(err) @@ -625,25 +635,26 @@ func TestSharedCloudPreviewDefaultFollowsCurrentGrant(t *testing.T) { if readErr != nil { t.Fatal(readErr) } - for _, a := range []*cloudprofiles.Assignment{public.BeforeAssignment, public.AfterAssignment} { + for _, a := range []*cloudprofiles.ProjectCloud{public.BeforeCloud, public.AfterCloud} { if a == nil || (a.DefaultPlacement != nil) != tc.wantDefault || len(a.Targets) != tc.wantTargets { t.Fatalf("grant leaked placement: %+v", a) } } if tc.revoked { - removal, removalErr := service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{EnvironmentID: "env", Revision: 1}) - if removalErr != nil { - t.Fatal(removalErr) + // Revocation ended the default, so nothing is left to remove, + // and the revoked Cloud can't be reviewed back in. + if current, _, defaultErr := st.DefaultCloud(ctx, "org", "proj"); defaultErr != nil || current != "" { + t.Fatalf("revoked grant stayed the default: %q %v", current, defaultErr) } - if removal.BeforeAssignment == nil || removal.BeforeAssignment.DefaultPlacement != nil || len(removal.BeforeAssignment.Targets) != 0 { - t.Fatalf("removal leaked retained placement: %+v", removal.BeforeAssignment) + if _, removalErr := service.PreviewCloudChange(ctx, actor, "proj", cloudprofiles.ChangeInput{ProjectDefault: true, CloudID: "cloud"}); !errors.Is(removalErr, cloudprofiles.ErrNotFound) { + t.Fatalf("revoked Cloud reviewed as the default: %v", removalErr) } } }) } manager := planning.NewService(planning.Deps{Projects: projects.NewPgStore(db), CloudProfiles: st, Authz: &syncAuth{}}) public, err := manager.CloudPreview(ctx, security.Principal{OrgID: "org", UserID: "manager"}, "proj", preview.ID) - if err != nil || public.BeforeAssignment.DefaultPlacement == nil || public.AfterAssignment.DefaultPlacement == nil { + if err != nil || public.BeforeCloud.DefaultPlacement == nil || public.AfterCloud.DefaultPlacement == nil { t.Fatalf("manager lost full view: %+v %v", public, err) } after, afterSnapshot, err := st.GetPreview(ctx, "org", "proj", preview.ID) diff --git a/tests/integration/shared_sync_acceptance_test.go b/tests/integration/shared_sync_acceptance_test.go index cb57a34a5..a60fde518 100644 --- a/tests/integration/shared_sync_acceptance_test.go +++ b/tests/integration/shared_sync_acceptance_test.go @@ -302,8 +302,13 @@ func TestSharedSyncAdmissionRejectsSourceAllocationMismatch(t *testing.T) { //go:embed testdata/pre_allocation_pool_functions.sql var preAllocationPoolFunctions string +// applySyncUpgrade replays the shared sync upgrade over legacy rows. The +// upgrade's function bodies have since been superseded, and some name tables +// later migrations dropped, so every function the replay changed goes back to +// its current definition: the rows see the upgrade, the code is today's. func applySyncUpgrade(t *testing.T, f *poolFixture) { t.Helper() + head := functionDefinitions(t, f) for _, migration := range migrations.Group().Migrations() { if migration.Name == "routed_releases" || migration.Name == "shared_sync_admission" || migration.Name == "shared_sync_capacity_ledger" { if err := migration.Up(t.Context(), pgmigrate.New(f.db)); err != nil { @@ -311,6 +316,36 @@ func applySyncUpgrade(t *testing.T, f *poolFixture) { } } } + for name, def := range functionDefinitions(t, f) { + if current, ok := head[name]; ok && current != def { + if _, err := f.sql.Exec(t.Context(), current); err != nil { + t.Fatalf("restore %s: %v", name, err) + } + } + } +} + +// functionDefinitions maps each Loomplane function to the statement that +// creates it as it stands. +func functionDefinitions(t *testing.T, f *poolFixture) map[string]string { + t.Helper() + rows, err := f.sql.Query(t.Context(), `SELECT p.oid::regprocedure::text, pg_get_functiondef(p.oid) FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace WHERE n.nspname='public' AND p.prokind='f' AND p.proname LIKE 'loomplane\_%'`) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + out := map[string]string{} + for rows.Next() { + var name, def string + if err = rows.Scan(&name, &def); err != nil { + t.Fatal(err) + } + out[name] = def + } + if err = rows.Err(); err != nil { + t.Fatal(err) + } + return out } func TestSharedSyncForwardUpgradeRetainsLegacyPlansAndBindings(t *testing.T) { f := newPoolFixture(t) diff --git a/tests/integration/shared_sync_compensation_test.go b/tests/integration/shared_sync_compensation_test.go index 31629bfb2..36f7fb0c8 100644 --- a/tests/integration/shared_sync_compensation_test.go +++ b/tests/integration/shared_sync_compensation_test.go @@ -583,7 +583,7 @@ func TestSharedSyncCompensationRestoresDirectServerSource(t *testing.T) { t.Fatal(err) } old := cfg.CloudPlacement - cfg.CloudPlacement = &planning.CloudPlacement{CloudID: old.CloudID, CloudRevision: old.CloudRevision, GrantRevision: old.GrantRevision, AssignmentRevision: old.AssignmentRevision, TargetID: target.ID, TargetRevision: target.Revision, TargetName: target.Name, Provider: old.Provider, ConnectionID: old.ConnectionID, AccountIdentity: old.AccountIdentity} + cfg.CloudPlacement = &planning.CloudPlacement{CloudID: old.CloudID, CloudRevision: old.CloudRevision, GrantRevision: old.GrantRevision, TargetID: target.ID, TargetRevision: target.Revision, TargetName: target.Name, Provider: old.Provider, ConnectionID: old.ConnectionID, AccountIdentity: old.AccountIdentity} b.Config, err = json.Marshal(cfg) if err != nil { t.Fatal(err) diff --git a/tests/integration/testdata/pre_allocation_pool_functions.sql b/tests/integration/testdata/pre_allocation_pool_functions.sql index 9329bc5f0..36b52fcc5 100644 --- a/tests/integration/testdata/pre_allocation_pool_functions.sql +++ b/tests/integration/testdata/pre_allocation_pool_functions.sql @@ -24,9 +24,8 @@ CREATE OR REPLACE FUNCTION loomplane_reserve_pool_plan() RETURNS TRIGGER LANGUAG IF NOT EXISTS(SELECT 1 FROM loomplane_cloud_connections c WHERE c.org_id=NEW.org_id AND c.id=host.runtime_connection_id AND c.status='ready' AND c.generation=(pin->>'connection_generation')::bigint) THEN RAISE EXCEPTION 'runtime connection changed' USING ERRCODE='23514'; END IF; PERFORM 1 FROM loomplane_cloud_project_grants WHERE org_id=NEW.org_id AND cloud_id=pin->>'cloud_id' AND project_id=NEW.project_id FOR SHARE; PERFORM 1 FROM loomplane_cloud_targets WHERE org_id=NEW.org_id AND id=pin->>'target_id' FOR SHARE; - PERFORM 1 FROM loomplane_cloud_assignments WHERE org_id=NEW.org_id AND environment_id=NEW.environment_id FOR SHARE; PERFORM 1 FROM loomplane_cloud_profiles WHERE org_id=NEW.org_id AND id=pin->>'cloud_id' FOR SHARE; - IF NOT EXISTS(SELECT 1 FROM loomplane_cloud_targets t JOIN loomplane_cloud_project_grants g ON g.org_id=t.org_id AND g.cloud_id=t.cloud_id AND g.project_id=NEW.project_id AND NOT g.revoked JOIN loomplane_cloud_assignments ca ON ca.org_id=t.org_id AND ca.project_id=NEW.project_id AND ca.environment_id=NEW.environment_id AND ca.cloud_id=t.cloud_id JOIN loomplane_cloud_profiles c ON c.org_id=t.org_id AND c.id=t.cloud_id WHERE t.org_id=NEW.org_id AND t.id=pin->>'target_id' AND t.pool_id=pool.id AND t.revision=(pin->>'target_revision')::bigint AND ca.revision=(pin->>'assignment_revision')::bigint AND c.revision=(pin->>'cloud_revision')::bigint AND g.revision=(pin->>'grant_revision')::bigint AND (cardinality(g.target_ids)=0 OR t.id=ANY(g.target_ids))) THEN RAISE EXCEPTION 'pool target authority changed' USING ERRCODE='23514'; END IF; + IF NOT EXISTS(SELECT 1 FROM loomplane_cloud_targets t JOIN loomplane_cloud_project_grants g ON g.org_id=t.org_id AND g.cloud_id=t.cloud_id AND g.project_id=NEW.project_id AND NOT g.revoked JOIN loomplane_cloud_profiles c ON c.org_id=t.org_id AND c.id=t.cloud_id WHERE t.org_id=NEW.org_id AND t.id=pin->>'target_id' AND t.pool_id=pool.id AND t.revision=(pin->>'target_revision')::bigint AND c.revision=(pin->>'cloud_revision')::bigint AND g.revision=(pin->>'grant_revision')::bigint AND (cardinality(g.target_ids)=0 OR t.id=ANY(g.target_ids))) THEN RAISE EXCEPTION 'pool target authority changed' USING ERRCODE='23514'; END IF; cpu:=coalesce((a->'service'->'size'->>'cpu')::numeric*1000,1000);mem:=coalesce((a->'service'->'size'->>'memory')::bigint*1048576,536870912); IF cpu<=0 OR mem<=0 OR cpu<>(pin->>'cpu_millis')::bigint OR mem<>(pin->>'memory_bytes')::bigint THEN RAISE EXCEPTION 'capacity differs from runtime limits' USING ERRCODE='23514'; END IF; SELECT coalesce(sum(c),0),coalesce(sum(m),0) INTO used_cpu,used_mem FROM (SELECT max(cpu_millis) c,max(memory_bytes) m FROM loomplane_capacity_reservations WHERE server_id=host.id AND NOT(environment_id=NEW.environment_id AND service=a->>'name') GROUP BY environment_id,service) r;