From 250bc72209c53eb2279daa8da1c6c581eface546 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Fri, 20 Nov 2026 13:23:02 -0600 Subject: [PATCH 1/5] fix(dashboard): make cache tags reach the screens they're meant to refresh A write or a live event only refreshes a screen when it names a tag some query carries. Many named nothing, so pages stayed stale until a reload, including the placement panel saying no Cloud was assigned after one was. Server declarations: - Live events used single-word tags ("EnvironmentCloud", "Sync", "CanaryReport", "NotificationList", "AgentTask", ...), which match only a query carrying exactly that word, and none did. They now name the item and list tags the reads carry. - Agent task, request and release report events carry separate event types, so upserting them never touched what REST reads hold. They invalidate the REST tags instead. - cloud_capacity.updated used {cloud_id}; frames are decoded to camelCase before tags resolve, so it never resolved. - Cluster writes and two DELETE routes named types the reads don't use (CloudClusterPage, Source, BitbucketWorkspace). Generated client: regenerated with a forge build carrying two generator fixes (pointer-slice envelopes lost their list tags; stream entities kept their bare name when only the REST document renamed them). That brings Profile[], CloudprofilesTarget[], Sync[], Pool[], Server[], Zone[], Report[], Request[] and ReleaseReport[] to life, and live Target, Source and Deployment events now land on the records the pages read. Forge now keeps stream routes out of the operation manifest, so their paths live in client/streams.ts. Dashboard: - cache-contract.test.ts fails on any write or live event invalidating a tag no read carries, with the remaining gaps listed and explained. - The release report listener plumbing is gone; the list refetches from its tag. - Hand-written deployment tags derive the typename from the generated contract. - The placement panel reads the environment's Cloud fresh when it opens, and says when the Cloud has no usable targets rather than claiming none is assigned. Needs the forge release carrying the generator fixes: CI's FORGE_CLI pin (v1.14.1) generates a different client, so `forge client check` fails until the pin moves. Verified: dashboard typecheck, lint and all 2213 tests pass; go build, vet and tests for realtime, discovery and cloudinfra pass; the specs were dumped from an API built from this branch with the same 452 operations as before. --- apps/dashboard/specs/loomplane.asyncapi.json | 116 +++-- apps/dashboard/specs/loomplane.openapi.json | 107 ++--- .../src/client/cache-contract.test.ts | 106 +++++ apps/dashboard/src/client/canary.ts | 12 +- apps/dashboard/src/client/failed-cleanup.ts | 3 +- .../src/client/forge/authsome/rest.ts | 16 +- .../src/client/forge/loomplane/README.md | 4 +- .../src/client/forge/loomplane/entities.ts | 21 +- .../src/client/forge/loomplane/hooks.ts | 3 - .../loomplane/hooks/useAgentTasksStream.ts | 4 - .../loomplane/hooks/useRealtimeEvents.ts | 4 - .../forge/loomplane/hooks/useRealtimeWs.ts | 4 - .../src/client/forge/loomplane/ops.ts | 286 +++++++------ .../forge/loomplane/ops/agentReports.list.ts | 4 +- .../forge/loomplane/ops/agentRequests.list.ts | 4 +- .../forge/loomplane/ops/agentTasks.stream.ts | 8 - .../loomplane/ops/aiModelDeployments.list.ts | 1 + .../forge/loomplane/ops/aiSettings.get.ts | 4 +- .../loomplane/ops/aiSettings.setBudget.ts | 1 + .../loomplane/ops/bitbucket.disconnect.ts | 4 +- .../loomplane/ops/catalogEndpoints.list.ts | 4 +- .../loomplane/ops/cloudClusters.preview.ts | 2 +- .../ops/cloudClusters.refreshCapacity.ts | 2 +- .../ops/cloudClusters.retirementPreview.ts | 2 +- .../forge/loomplane/ops/cloudPools.list.ts | 4 +- .../forge/loomplane/ops/cloudServers.list.ts | 4 +- .../forge/loomplane/ops/cloudSyncs.list.ts | 4 +- .../forge/loomplane/ops/cloudTargets.list.ts | 4 +- .../client/forge/loomplane/ops/clouds.list.ts | 4 +- .../loomplane/ops/clusterOperations.apply.ts | 2 +- .../loomplane/ops/clusterOperations.cancel.ts | 2 +- .../loomplane/ops/clusterOperations.retry.ts | 2 +- .../forge/loomplane/ops/dnsZones.list.ts | 4 +- .../loomplane/ops/domainRegistrations.list.ts | 4 +- .../loomplane/ops/domainRoutes.history.ts | 4 +- .../forge/loomplane/ops/domainRoutes.list.ts | 4 +- .../forge/loomplane/ops/domains.overview.ts | 3 +- .../loomplane/ops/environmentClouds.get.ts | 1 + .../ops/infrastructureOperations.list.ts | 4 +- .../ops/organizationCloudSyncs.list.ts | 4 +- .../ops/organizationCloudTargets.list.ts | 4 +- .../loomplane/ops/organizationClouds.list.ts | 4 +- .../loomplane/ops/providerResources.list.ts | 1 + .../forge/loomplane/ops/realtime.events.ts | 8 - .../client/forge/loomplane/ops/realtime.ws.ts | 8 - .../loomplane/ops/releaseReports.list.ts | 4 +- .../forge/loomplane/ops/sources.delete.ts | 4 +- .../src/client/forge/loomplane/rest.ts | 327 ++++++--------- .../src/client/forge/loomplane/sse.ts | 396 +++++++++--------- .../client/forge/loomplane/stream-bindings.ts | 148 +++---- .../src/client/forge/loomplane/websocket.ts | 2 +- apps/dashboard/src/client/streams.test.ts | 20 + apps/dashboard/src/client/streams.ts | 19 + apps/dashboard/src/client/tags.ts | 14 + .../src/components/deployment-targets.tsx | 23 +- .../src/components/release-reports-card.tsx | 8 +- apps/dashboard/src/lib/agent-stream.ts | 7 +- apps/dashboard/src/lib/realtime.test.ts | 55 +-- apps/dashboard/src/lib/realtime.ts | 29 +- apps/dashboard/src/lib/release-reports.ts | 28 -- apps/dashboard/src/pages/release-report.tsx | 2 - extensions/cloudinfra/clusters.go | 9 +- extensions/discovery/bitbucket.go | 2 +- extensions/discovery/routes.go | 2 +- extensions/realtime/routes.go | 18 +- 65 files changed, 998 insertions(+), 920 deletions(-) create mode 100644 apps/dashboard/src/client/cache-contract.test.ts delete mode 100644 apps/dashboard/src/client/forge/loomplane/hooks/useAgentTasksStream.ts delete mode 100644 apps/dashboard/src/client/forge/loomplane/hooks/useRealtimeEvents.ts delete mode 100644 apps/dashboard/src/client/forge/loomplane/hooks/useRealtimeWs.ts delete mode 100644 apps/dashboard/src/client/forge/loomplane/ops/agentTasks.stream.ts delete mode 100644 apps/dashboard/src/client/forge/loomplane/ops/realtime.events.ts delete mode 100644 apps/dashboard/src/client/forge/loomplane/ops/realtime.ws.ts create mode 100644 apps/dashboard/src/client/streams.test.ts create mode 100644 apps/dashboard/src/client/streams.ts create mode 100644 apps/dashboard/src/client/tags.ts diff --git a/apps/dashboard/specs/loomplane.asyncapi.json b/apps/dashboard/specs/loomplane.asyncapi.json index c15a8ec7a..d471fc122 100644 --- a/apps/dashboard/specs/loomplane.asyncapi.json +++ b/apps/dashboard/specs/loomplane.asyncapi.json @@ -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" @@ -720,7 +720,7 @@ "entityType": "CloudSyncEvent", "intent": "patch", "invalidates": [ - "Sync", + "Sync:{id}", "Sync[]", "EnvironmentCloud" ], @@ -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" @@ -1154,7 +1150,7 @@ "entityType": "CloudSyncEvent", "intent": "patch", "invalidates": [ - "Sync", + "Sync:{id}", "Sync[]", "EnvironmentCloud" ], @@ -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", diff --git a/apps/dashboard/specs/loomplane.openapi.json b/apps/dashboard/specs/loomplane.openapi.json index 502f18e14..689d81353 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}" ] } }, @@ -13019,7 +13019,7 @@ ], "x-forge-entity": { "idField": "id", - "type": "Source" + "type": "DiscoverySource" } }, "patch": { @@ -18146,9 +18146,6 @@ }, "/api/v1/realtime/events": { "get": { - "tags": [ - "Realtime" - ], "operationId": "realtime.events", "parameters": [ { @@ -18182,9 +18179,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": { @@ -18240,9 +18248,6 @@ }, "/api/v1/realtime/ws": { "get": { - "tags": [ - "Realtime" - ], "operationId": "realtime.ws", "parameters": [ { @@ -18275,10 +18280,14 @@ } ], "responses": { - "200": { - "description": "Success" + "101": { + "description": "Switching Protocols" } - } + }, + "tags": [ + "Realtime" + ], + "x-forge-protocol": "websocket" } }, "/api/v1/release-reports/{id}": { 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..d775a3aac --- /dev/null +++ b/apps/dashboard/src/client/cache-contract.test.ts @@ -0,0 +1,106 @@ +// 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 = { + EnvironmentCloud: + "the environment Cloud read has no identity; it goes when Clouds stop being per environment", + "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 4e5893b56..47e18d77f 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**: 455 -- **REST Endpoints**: 452 +- **Total Endpoints**: 452 +- **REST Endpoints**: 449 - **WebSocket Endpoints**: 1 - **SSE Endpoints**: 2 diff --git a/apps/dashboard/src/client/forge/loomplane/entities.ts b/apps/dashboard/src/client/forge/loomplane/entities.ts index 4a508d17e..1e776bb8d 100644 --- a/apps/dashboard/src/client/forge/loomplane/entities.ts +++ b/apps/dashboard/src/client/forge/loomplane/entities.ts @@ -13,7 +13,6 @@ export const entities = { '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 +29,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' }, @@ -52,10 +53,14 @@ 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' }, + 'EnvironmentCloud': { fields: { 'assignment': 'Assignment' } }, 'EnvironmentList': { fields: { 'environments': 'Environment' } }, 'EventPage': { fields: { 'items': 'FleetEvent' } }, 'Expansion': { idField: 'id' }, @@ -88,6 +93,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 +114,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,10 +123,12 @@ 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' }, + 'PoolList': { fields: { 'pools': 'Pool' } }, 'Preview': { idField: 'id', fields: { 'after': 'CloudprofilesTarget', 'afterAssignment': 'Assignment', 'before': 'CloudprofilesTarget', 'beforeAssignment': 'Assignment' } }, 'Profile': { idField: 'id' }, 'Project': { idField: 'id' }, @@ -129,6 +138,7 @@ export const entities = { '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' } }, 'Source': { idField: 'id' }, 'SourceList': { fields: { 'sources': 'DiscoverySource' } }, 'SourceState': { fields: { 'latest': 'Analysis', 'shown': 'Analysis', 'source': 'DiscoverySource' } }, @@ -174,10 +189,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 2f2bf76fc..2eae3dd2d 100644 --- a/apps/dashboard/src/client/forge/loomplane/hooks.ts +++ b/apps/dashboard/src/client/forge/loomplane/hooks.ts @@ -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']); @@ -427,9 +426,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/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 69d6d599e..feab7ad95 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'], }, @@ -2682,6 +2709,7 @@ export const ops = { 'environmentClouds.get': { method: 'GET', path: '/api/v1/projects/{id}/environments/{environmentId}/cloud', + rootType: 'EnvironmentCloud', provides: [], invalidates: [], responseCodec: CODECS['EnvironmentCloud'], @@ -2908,7 +2936,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'], }, @@ -3001,9 +3031,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', @@ -3054,7 +3084,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'], }, @@ -3102,7 +3134,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'], }, @@ -3536,6 +3570,7 @@ export const ops = { 'providerResources.list': { method: 'GET', path: '/api/v1/provider-resources', + rootType: 'ProviderResourceList', provides: [], invalidates: [], responseCodec: CODECS['ProviderResourceList'], @@ -3613,12 +3648,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', @@ -3626,12 +3655,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}', @@ -3935,7 +3958,6 @@ export const entities = { 'Binding': { idField: 'id' }, 'BindingList': { fields: { 'bindings': 'Binding' } }, 'BitbucketStatus': { fields: { 'workspaces': 'BitbucketWorkspaceView' } }, - 'BitbucketWorkspace': { idField: 'id' }, 'BitbucketWorkspaceView': { idField: 'id' }, 'CLIOrganization': { idField: 'id' }, 'CLIOrganizationList': { fields: { 'organizations': 'CLIOrganization' } }, @@ -3952,6 +3974,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' }, @@ -3974,10 +3998,14 @@ 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' }, + 'EnvironmentCloud': { fields: { 'assignment': 'Assignment' } }, 'EnvironmentList': { fields: { 'environments': 'Environment' } }, 'EventPage': { fields: { 'items': 'FleetEvent' } }, 'Expansion': { idField: 'id' }, @@ -4010,6 +4038,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' } }, @@ -4030,6 +4059,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' } }, @@ -4038,10 +4068,12 @@ 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' }, + 'PoolList': { fields: { 'pools': 'Pool' } }, 'Preview': { idField: 'id', fields: { 'after': 'CloudprofilesTarget', 'afterAssignment': 'Assignment', 'before': 'CloudprofilesTarget', 'beforeAssignment': 'Assignment' } }, 'Profile': { idField: 'id' }, 'Project': { idField: 'id' }, @@ -4051,6 +4083,7 @@ export const entities = { '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' }, @@ -4059,12 +4092,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' }, @@ -4081,6 +4118,7 @@ export const entities = { 'ScalingPool': { fields: { 'pool': 'Pool' } }, 'Sent': { fields: { 'conversation': 'Conversation', 'task': 'Task' } }, 'Server': { idField: 'id' }, + 'ServerList': { fields: { 'servers': 'Server' } }, 'Source': { idField: 'id' }, 'SourceList': { fields: { 'sources': 'DiscoverySource' } }, 'SourceState': { fields: { 'latest': 'Analysis', 'shown': 'Analysis', 'source': 'DiscoverySource' } }, @@ -4096,11 +4134,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; @@ -4145,19 +4185,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', @@ -4253,19 +4293,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', @@ -4273,7 +4313,7 @@ export const streams = [ message: 'canary_verdict.updated', entity: 'CanaryVerdict', intent: 'upsert', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -4282,7 +4322,7 @@ export const streams = [ message: 'canary_verdict.deleted', entity: 'CanaryVerdict', intent: 'evict', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -4325,19 +4365,19 @@ 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', @@ -4354,7 +4394,7 @@ export const streams = [ message: 'cloud_sync.updated', entity: 'CloudSyncEvent', intent: 'patch', - invalidates: ['Sync', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'EnvironmentCloud'], decode: (payload: unknown) => decode(payload, CODECS['CloudSyncEvent']), }, { @@ -4363,7 +4403,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']), }, { @@ -4372,7 +4412,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']), }, { @@ -4381,7 +4421,7 @@ export const streams = [ message: 'notification.created', entity: 'NotificationCreated', intent: 'upsert', - invalidates: ['NotificationList'], + invalidates: ['Notification[]'], decode: (payload: unknown) => decode(payload, CODECS['NotificationCreated']), }, { @@ -4398,8 +4438,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']), }, { @@ -4407,8 +4447,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']), }, { @@ -4417,7 +4457,7 @@ export const streams = [ message: 'agent_report.updated', entity: 'Report', intent: 'upsert', - invalidates: ['AgentReport', 'AgentReport[]'], + invalidates: ['Report[]'], decode: (payload: unknown) => decode(payload, CODECS['Report']), }, { @@ -4434,8 +4474,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']), }, { @@ -4443,8 +4483,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']), }, { @@ -4452,8 +4492,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']), }, { @@ -4461,8 +4501,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']), }, { @@ -4523,19 +4563,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', @@ -4631,19 +4671,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', @@ -4651,7 +4691,7 @@ export const streams = [ message: 'canary_verdict.updated', entity: 'CanaryVerdict', intent: 'upsert', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -4660,7 +4700,7 @@ export const streams = [ message: 'canary_verdict.deleted', entity: 'CanaryVerdict', intent: 'evict', - invalidates: ['CanaryReport'], + invalidates: ['CanaryVerdict[]'], decode: (payload: unknown) => decode(payload, CODECS['CanaryVerdict']), }, { @@ -4703,19 +4743,19 @@ 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', @@ -4732,7 +4772,7 @@ export const streams = [ message: 'cloud_sync.updated', entity: 'CloudSyncEvent', intent: 'patch', - invalidates: ['Sync', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'EnvironmentCloud'], decode: (payload: unknown) => decode(payload, CODECS['CloudSyncEvent']), }, { @@ -4741,7 +4781,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']), }, { @@ -4750,7 +4790,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']), }, { @@ -4759,7 +4799,7 @@ export const streams = [ message: 'notification.created', entity: 'NotificationCreated', intent: 'upsert', - invalidates: ['NotificationList'], + invalidates: ['Notification[]'], decode: (payload: unknown) => decode(payload, CODECS['NotificationCreated']), }, { @@ -4776,8 +4816,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']), }, { @@ -4785,8 +4825,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']), }, { @@ -4795,7 +4835,7 @@ export const streams = [ message: 'agent_report.updated', entity: 'Report', intent: 'upsert', - invalidates: ['AgentReport', 'AgentReport[]'], + invalidates: ['Report[]'], decode: (payload: unknown) => decode(payload, CODECS['Report']), }, { @@ -4812,8 +4852,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']), }, { @@ -4821,8 +4861,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']), }, { @@ -4830,8 +4870,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']), }, { @@ -4839,8 +4879,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/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 index 7ca3812a8..ca01dadfe 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops/environmentClouds.get.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops/environmentClouds.get.ts @@ -4,6 +4,7 @@ import { codec_EnvironmentCloud } from '../codecs/EnvironmentCloud'; export const op_environmentClouds_get = { method: 'GET', path: '/api/v1/projects/{id}/environments/{environmentId}/cloud', + rootType: 'EnvironmentCloud', provides: [], invalidates: [], responseCodec: codec_EnvironmentCloud, 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 38c1af900..bb7a6d492 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) { @@ -3228,10 +3203,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 +3229,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 +3310,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 +3544,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 +3566,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; @@ -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) { @@ -5071,16 +5046,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) { @@ -5155,10 +5130,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) { @@ -5181,16 +5156,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) { @@ -5231,16 +5206,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) { @@ -5263,16 +5238,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) { @@ -5309,8 +5284,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; @@ -5365,10 +5340,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) { @@ -6021,13 +5996,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) { @@ -6471,13 +6446,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) { @@ -6556,7 +6531,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) { @@ -7443,54 +7418,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) { @@ -7507,38 +7450,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 = { @@ -7621,7 +7532,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) { @@ -7732,10 +7643,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) { @@ -7797,7 +7708,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) { @@ -7869,8 +7780,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; @@ -8007,10 +7918,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) { @@ -8033,13 +7944,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) { @@ -8395,7 +8306,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) { @@ -8471,9 +8382,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..498efed2f 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) => { + 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); + 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("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,7 +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); + this.off("environment.updated", handler); } /** @@ -1275,7 +1275,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @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); + this.on("environment_cloud.updated", handler); } /** @@ -1283,7 +1283,7 @@ export class RealtimeEventsSSEClient extends EventEmitter { * @param handler - The handler to remove */ offEnvironmentCloudUpdated(handler: (data: types.EnvironmentCloudEvent) => void): void { - this.off('environment_cloud.updated', handler); + this.off("environment_cloud.updated", handler); } /** @@ -1291,7 +1291,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 +1299,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 +1307,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 +1315,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 +1323,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 +1331,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 +1339,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 +1347,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 +1355,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 +1363,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 +1371,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 +1379,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 +1387,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 +1395,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 +1403,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 +1411,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 +1419,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 +1427,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 +1435,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 +1443,7 @@ 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); } /** @@ -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..63eb0b638 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,19 +221,19 @@ 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', @@ -250,7 +250,7 @@ export const streams = [ message: 'cloud_sync.updated', entity: 'CloudSyncEvent', intent: 'patch', - invalidates: ['Sync', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'EnvironmentCloud'], 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,19 +599,19 @@ 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', @@ -628,7 +628,7 @@ export const streams = [ message: 'cloud_sync.updated', entity: 'CloudSyncEvent', intent: 'patch', - invalidates: ['Sync', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'EnvironmentCloud'], 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/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/deployment-targets.tsx b/apps/dashboard/src/components/deployment-targets.tsx index 0a68d1c02..1673db968 100644 --- a/apps/dashboard/src/components/deployment-targets.tsx +++ b/apps/dashboard/src/components/deployment-targets.tsx @@ -176,13 +176,18 @@ function placedManifest( export function usePlacementContext(projectId: string, environmentId?: string) { const providers = useQuery(useProvidersList) const connections = useQuery(useConnectionsList) - const cloud = useQuery(useEnvironmentCloudsGet, { - path: { id: projectId, environmentId: environmentId ?? "" }, - }) + // The assignment changes on the Clouds page, not here, and its read has no + // cache identity, so read it fresh each time a placement panel opens. + const cloud = useQuery( + useEnvironmentCloudsGet, + { path: { id: projectId, environmentId: environmentId ?? "" } }, + { staleTime: 0 } + ) return { providers, catalog: providers.data?.providers ?? [], connections: connections.data?.connections ?? [], + cloudAssigned: !!cloud.data?.assignment, cloudTargets: (cloud.data?.assignment?.targets ?? []).filter( (t): t is Target => !!t ), @@ -317,7 +322,7 @@ function PlacementForm({ onPendingChange?: (pending: boolean) => void }) { const environmentId = environments.find((e) => e.name === environment)?.id - const { providers, cloudTargets } = usePlacementContext( + const { providers, cloudTargets, cloudAssigned } = usePlacementContext( projectId, environmentId ) @@ -356,6 +361,7 @@ function PlacementForm({ environments={environments} catalog={providers.data.providers} cloudTargets={cloudTargets} + cloudAssigned={cloudAssigned} mode={mode} pending={pending} onUse={onUse} @@ -380,6 +386,7 @@ function PlacementChoices({ environments, catalog, cloudTargets, + cloudAssigned, mode, pending, onUse, @@ -396,6 +403,7 @@ function PlacementChoices({ environments: Environment[] catalog: Provider[] cloudTargets: Target[] + cloudAssigned: boolean mode: "pending" | "save" pending?: PendingPlacement onUse?: (change: PendingPlacement) => void @@ -715,14 +723,15 @@ function PlacementChoices({ )} {row.section === "services" && cloudTargets.length === 0 && (

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

)} 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/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/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/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/realtime/routes.go b/extensions/realtime/routes.go index beed55490..d89401321 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.CloudSyncEvent]("cloud_sync.updated").Invalidates("Sync:{id}", "Sync[]", "EnvironmentCloud"), + 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), ) } From 78a067b676e3dce2623798f9ec8b0f76720c49d9 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Fri, 20 Nov 2026 16:28:54 -0600 Subject: [PATCH 2/5] feat(clouds): Clouds belong to projects, not environments A Cloud was org-owned and a project's grant to it ignored environments, but each environment still had to be assigned one Cloud before any service could name a target, and cloud_target resolved only inside that assignment. The deploy screen's "No Cloud is assigned to production" was that model showing through. Now each project has one default Cloud, every environment of the project resolves through it, and environments differ only where loomplane.yaml says. Model and storage (migration project_default_cloud): - The default is a flag on the project's grant, unique per project among live grants. A project's first grant becomes its default; revoking a grant ends its default however the revocation is written. Backfill picks the Cloud most of a project's environments used, without moving any revision. - loomplane_cloud_assignments is dropped. The capacity, workload-scope and admission functions stop joining it and stop comparing assignment_revision; the grant revision they already pin covers a default switch, since the switch advances both grants. Placements and capacity intents keep the assignment_revision field so stored records hash as they were approved. - A target can't be deleted while its Cloud is a project's default or a serving binding pins it; a Cloud can't be deleted in either case either (its grants used to vanish with it). - project_cloud.updated replaces environment_cloud.updated, readable with the same permission. Behaviour: - Changing the default is a reviewed Cloud change (project_default) covering every environment of the project. The review pins both grants, and the new default at the revision the apply gives it, so the sync's own runs aren't refused as stale. - Shared changes (a target edit, a default placement switch) reach every environment of projects whose default the Cloud is, plus any environment running a service placed on it. - API: GET/POST /projects/:id/default-cloud[/preview] replace the environment cloud routes. loomctl: clouds default, clouds make-default. Dashboard: - The project's Clouds tab has no environment picker: one card per granted Cloud, the default first and open, "Make default" on the others, targets and where each service runs inside. Placing a service there applies to every environment and clears the placement an environment set for it. - The deploy drawer lists the default Cloud's targets under its name, and links to the Clouds tab when there's no Cloud or no target, instead of the dead end. - Polling that stood in for missing cache tags is gone. Docs and the agent's docs bundle describe the project default Cloud. Review notes: - internal/currentauthority records the new migration in its reviewed source lists (project and Fleet). The migration calls loomplane_append_event and adds a column to a Fleet-read table; it redefines neither the guarded functions nor any column Fleet reads. - applySyncUpgrade replays three historical migrations onto a current database; their pool function body now names a dropped table, so the helper restores every function the replay changed to its current definition. Verified: go build/vet and the full Go unit suite pass; golangci-lint clean on the change; database/migrations integration suite passes; integration tests matching Cloud, Shared, Pool, Capacity, Managed, Cleanup, Location, Tags, Usage, Default, Native, Placement, Server, Cluster, Fleet, Node, Model, Azure, Domain and Route pass (after the fixes in this commit, the affected ones re-run); dashboard typecheck, lint and all 2213 tests pass; the client regenerates without a diff from an API built from this commit. --- apps/dashboard/specs/loomplane.asyncapi.json | 160 ++--- apps/dashboard/specs/loomplane.openapi.json | 379 ++++++----- .../src/client/cache-contract.test.ts | 2 - .../src/client/forge/loomplane/codecs.ts | 24 +- .../forge/loomplane/codecs/Assignment.ts | 5 - .../forge/loomplane/codecs/CapacityIntent.ts | 2 +- .../forge/loomplane/codecs/ChangeInput.ts | 2 +- .../forge/loomplane/codecs/ChangeInputBody.ts | 2 +- .../forge/loomplane/codecs/CloudPlacement.ts | 2 +- .../forge/loomplane/codecs/DefaultCloud.ts | 4 + .../loomplane/codecs/DefaultCloudInputBody.ts | 3 + .../loomplane/codecs/EnvironmentCloud.ts | 4 - .../loomplane/codecs/EnvironmentCloudEvent.ts | 3 - .../codecs/EnvironmentCloudInputBody.ts | 3 - .../loomplane/codecs/EnvironmentUsage.ts | 2 +- .../client/forge/loomplane/codecs/Preview.ts | 4 +- ...ent.targets.ts => ProjectCloud.targets.ts} | 2 +- .../forge/loomplane/codecs/ProjectCloud.ts | 5 + .../loomplane/codecs/ProjectCloudEvent.ts | 3 + .../forge/loomplane/codecs/ProjectGrant.ts | 2 +- .../src/client/forge/loomplane/entities.ts | 6 +- .../src/client/forge/loomplane/hooks.ts | 6 +- .../loomplane/hooks/useDefaultCloudGet.ts | 5 + .../loomplane/hooks/useDefaultCloudPreview.ts | 5 + .../hooks/useEnvironmentCloudsGet.ts | 5 - .../hooks/useEnvironmentCloudsPreview.ts | 5 - .../src/client/forge/loomplane/ops.ts | 63 +- .../forge/loomplane/ops/defaultCloud.get.ts | 12 + ...uds.preview.ts => defaultCloud.preview.ts} | 8 +- .../loomplane/ops/environmentClouds.get.ts | 11 - .../src/client/forge/loomplane/rest.ts | 74 +-- .../src/client/forge/loomplane/sse.ts | 50 +- .../client/forge/loomplane/stream-bindings.ts | 20 +- .../src/client/forge/loomplane/types.ts | 71 +-- .../components/cloud-detail/environments.tsx | 25 +- .../src/components/cloud-detail/projects.tsx | 7 +- .../cloud-targets/change-review.tsx | 143 +++-- .../cloud-targets/service-adoption.tsx | 68 +- .../components/cloud-targets/sync-history.tsx | 28 +- .../components/cloud-targets/workspace.tsx | 587 ++++++------------ .../src/components/deploy-dialog.tsx | 5 +- apps/dashboard/src/components/deploy.tsx | 5 +- .../src/components/deployment-targets.tsx | 90 ++- apps/dashboard/src/lib/cloud-tags.test.ts | 19 +- apps/dashboard/src/lib/cloud-targets.test.ts | 103 ++- apps/dashboard/src/lib/cloud-targets.ts | 77 ++- .../dashboard/src/pages/cloud-detail.test.tsx | 6 +- apps/dashboard/src/pages/cloud-detail.tsx | 2 +- apps/dashboard/src/pages/clouds.test.tsx | 197 +++--- apps/dashboard/src/pages/clouds.tsx | 17 +- .../src/pages/project-detail.page.test.tsx | 2 +- apps/dashboard/src/pages/project-detail.tsx | 8 +- apps/docs/content/docs/ai/models.mdx | 2 +- .../docs/clouds/adopting-and-moving.mdx | 8 +- .../content/docs/clouds/cloud-targets.mdx | 29 +- apps/docs/content/docs/reference/loomctl.mdx | 2 +- .../content/docs/reference/loomplane-yaml.mdx | 2 +- .../20261228000100_project_default_cloud.go | 542 ++++++++++++++++ .../migrations/project_default_cloud_test.go | 101 +++ extensions/planning/clouds.go | 46 +- extensions/realtime/filter_test.go | 2 +- extensions/realtime/handlers.go | 2 +- extensions/realtime/routes.go | 6 +- internal/agentknowledge/docs.json | 14 +- internal/cloudinfra/cluster_reconcile_test.go | 8 +- internal/cloudprofiles/change.go | 79 +-- internal/cloudprofiles/events.go | 13 +- internal/cloudprofiles/grants.go | 62 +- internal/cloudprofiles/model.go | 35 +- internal/cloudprofiles/pgstore.go | 119 ++-- internal/cloudprofiles/service.go | 16 +- internal/cloudprofiles/service_test.go | 4 +- internal/cloudprofiles/sync_store.go | 80 ++- internal/cloudprofiles/usage.go | 29 +- internal/ctl/clouds.go | 22 +- internal/ctl/clouds_test.go | 16 +- .../currentauthority/fleet_schema_test.go | 3 +- .../testdata/project_schema_sources.json | 3 +- internal/deployments/cloud_targets.go | 19 +- internal/deployments/cloud_targets_test.go | 15 +- internal/deployments/platform_test.go | 6 +- .../route_runtime_integration_test.go | 8 +- internal/models/server_first.go | 12 +- internal/models/server_first_test.go | 14 +- internal/planning/capacity_intent.go | 31 +- internal/planning/capacity_intent_test.go | 9 +- internal/planning/cloud_default_switch.go | 4 +- .../planning/cloud_default_switch_test.go | 12 +- internal/planning/cloud_locations_test.go | 4 +- .../planning/cloud_platform_owned_test.go | 28 +- internal/planning/cloud_servers_test.go | 6 +- internal/planning/cloud_sync.go | 107 ++-- internal/planning/cloud_sync_plan.go | 10 +- internal/planning/cloud_sync_plan_test.go | 6 +- internal/planning/cloud_sync_revert.go | 13 +- internal/planning/cloud_sync_revert_test.go | 10 +- internal/planning/cloud_sync_routes.go | 4 +- internal/planning/cloud_tags_test.go | 6 +- internal/planning/cloud_targets.go | 52 +- .../planning/cloud_targets_service_test.go | 8 +- internal/planning/cloud_targets_test.go | 26 +- internal/planning/composition_test.go | 2 +- internal/planning/dbgateway.go | 2 +- internal/planning/dbgateway_test.go | 12 +- internal/planning/location_evidence.go | 6 +- internal/planning/location_migration.go | 2 +- internal/planning/location_placement_test.go | 22 +- internal/planning/location_requirements.go | 2 +- internal/planning/planner_test.go | 2 +- internal/planning/platform.go | 12 +- internal/planning/platform_targets_test.go | 4 +- internal/planning/server_pools_test.go | 2 +- internal/planning/service.go | 9 +- internal/planning/service_test.go | 12 +- internal/publicplan/plan.go | 22 +- pkg/client/clouds.go | 92 +-- pkg/client/clouds_test.go | 10 +- tests/integration/azure_test.go | 15 +- tests/integration/capacity_planning_test.go | 4 +- tests/integration/cloud_acceptance_test.go | 4 +- tests/integration/cloud_api_test.go | 98 ++- .../integration/cloud_default_switch_test.go | 21 +- tests/integration/cloud_flow_test.go | 14 +- .../cloud_location_placement_test.go | 12 +- tests/integration/cloud_metadata_test.go | 4 +- tests/integration/cloud_profiles_test.go | 49 +- tests/integration/cloud_sync_test.go | 129 +++- tests/integration/cloud_tags_test.go | 22 +- tests/integration/cloud_usage_test.go | 39 +- .../cloudsql_partial_revert_test.go | 8 +- .../cluster_workload_planning_test.go | 2 +- .../deployment_capacity_wait_test.go | 2 +- tests/integration/fleet_scope_guards_test.go | 12 +- .../managed_cleanup_effects_test.go | 2 +- .../managed_cleanup_issuer_test.go | 4 +- .../managed_cleanup_targets_test.go | 18 +- ...naged_cluster_maintenance_recovery_test.go | 4 +- .../managed_cluster_service_recovery_test.go | 4 +- .../managed_clusters_store_test.go | 6 +- .../managed_lifecycle_cleanup_fixture_test.go | 4 +- .../managed_workload_installed_test.go | 3 +- tests/integration/nodes_test.go | 7 +- .../integration/server_admission_lock_test.go | 15 +- tests/integration/server_pool_sizing_test.go | 7 +- tests/integration/server_pools_test.go | 11 +- .../integration/shared_cloud_combined_test.go | 7 +- .../shared_cloud_live_acceptance_test.go | 8 +- .../shared_cloud_recovery_fixture_test.go | 9 +- tests/integration/shared_clouds_test.go | 119 ++-- .../shared_sync_acceptance_test.go | 35 ++ .../shared_sync_compensation_test.go | 2 +- .../pre_allocation_pool_functions.sql | 3 +- 152 files changed, 2893 insertions(+), 2021 deletions(-) delete mode 100644 apps/dashboard/src/client/forge/loomplane/codecs/Assignment.ts create mode 100644 apps/dashboard/src/client/forge/loomplane/codecs/DefaultCloud.ts create mode 100644 apps/dashboard/src/client/forge/loomplane/codecs/DefaultCloudInputBody.ts delete mode 100644 apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloud.ts delete mode 100644 apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloudEvent.ts delete mode 100644 apps/dashboard/src/client/forge/loomplane/codecs/EnvironmentCloudInputBody.ts rename apps/dashboard/src/client/forge/loomplane/codecs/{Assignment.targets.ts => ProjectCloud.targets.ts} (51%) create mode 100644 apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloud.ts create mode 100644 apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloudEvent.ts create mode 100644 apps/dashboard/src/client/forge/loomplane/hooks/useDefaultCloudGet.ts create mode 100644 apps/dashboard/src/client/forge/loomplane/hooks/useDefaultCloudPreview.ts delete mode 100644 apps/dashboard/src/client/forge/loomplane/hooks/useEnvironmentCloudsGet.ts delete mode 100644 apps/dashboard/src/client/forge/loomplane/hooks/useEnvironmentCloudsPreview.ts create mode 100644 apps/dashboard/src/client/forge/loomplane/ops/defaultCloud.get.ts rename apps/dashboard/src/client/forge/loomplane/ops/{environmentClouds.preview.ts => defaultCloud.preview.ts} (52%) delete mode 100644 apps/dashboard/src/client/forge/loomplane/ops/environmentClouds.get.ts create mode 100644 database/migrations/20261228000100_project_default_cloud.go create mode 100644 database/migrations/project_default_cloud_test.go diff --git a/apps/dashboard/specs/loomplane.asyncapi.json b/apps/dashboard/specs/loomplane.asyncapi.json index d471fc122..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" @@ -708,13 +708,13 @@ "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", @@ -722,7 +722,7 @@ "invalidates": [ "Sync:{id}", "Sync[]", - "EnvironmentCloud" + "DefaultCloud:{projectId}" ], "message": "cloud_sync.updated", "type": "github.com/xraph/loomplane/internal/cloudprofiles.CloudSyncEvent" @@ -1138,13 +1138,13 @@ "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", @@ -1152,7 +1152,7 @@ "invalidates": [ "Sync:{id}", "Sync[]", - "EnvironmentCloud" + "DefaultCloud:{projectId}" ], "message": "cloud_sync.updated", "type": "github.com/xraph/loomplane/internal/cloudprofiles.CloudSyncEvent" @@ -1415,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" }, @@ -1448,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" }, @@ -1895,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" }, @@ -2096,7 +2092,6 @@ "account_identity", "cloud_id", "cloud_revision", - "assignment_revision", "target_id", "target_revision", "target_name", @@ -2110,9 +2105,6 @@ "allocation": { "type": "string" }, - "assignment_revision": { - "type": "integer" - }, "cloud_id": { "type": "string" }, @@ -5988,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": [ @@ -6470,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": [ @@ -9011,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", @@ -9861,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 689d81353..707671339 100644 --- a/apps/dashboard/specs/loomplane.openapi.json +++ b/apps/dashboard/specs/loomplane.openapi.json @@ -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": [ @@ -20407,51 +20389,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": [ @@ -21607,16 +21544,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" }, @@ -22217,12 +22150,12 @@ "default": { "type": "boolean" }, - "environment_id": { - "type": "string" - }, "pool_id": { "type": "string" }, + "project_default": { + "type": "boolean" + }, "provider": { "type": "string" }, @@ -22256,12 +22189,12 @@ "default": { "type": "boolean" }, - "environment_id": { - "type": "string" - }, "pool_id": { "type": "string" }, + "project_default": { + "type": "boolean" + }, "provider": { "type": "string" }, @@ -23048,7 +22981,6 @@ "account_identity", "cloud_id", "cloud_revision", - "assignment_revision", "target_id", "target_revision", "target_name", @@ -23062,9 +22994,6 @@ "allocation": { "type": "string" }, - "assignment_revision": { - "type": "integer" - }, "cloud_id": { "type": "string" }, @@ -25891,6 +25820,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": [ @@ -27673,47 +27648,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": [ @@ -27752,11 +27686,11 @@ "project_name", "environment_id", "environment_name", - "assigned", + "default", "placements" ], "properties": { - "assigned": { + "default": { "type": "boolean" }, "environment_id": { @@ -35538,8 +35472,8 @@ "after": { "$ref": "#/components/schemas/CloudprofilesTarget" }, - "after_assignment": { - "$ref": "#/components/schemas/Assignment" + "after_cloud": { + "$ref": "#/components/schemas/ProjectCloud" }, "after_default": { "$ref": "#/components/schemas/DefaultPlacement" @@ -35547,8 +35481,8 @@ "before": { "$ref": "#/components/schemas/CloudprofilesTarget" }, - "before_assignment": { - "$ref": "#/components/schemas/Assignment" + "before_cloud": { + "$ref": "#/components/schemas/ProjectCloud" }, "before_default": { "$ref": "#/components/schemas/DefaultPlacement" @@ -35754,6 +35688,47 @@ } } }, + "ProjectCloud": { + "type": "object", + "required": [ + "grant_revision", + "cloud_revision", + "org_id", + "project_id", + "cloud_id", + "default", + "targets" + ], + "properties": { + "cloud_id": { + "type": "string" + }, + "cloud_revision": { + "type": "integer" + }, + "default": { + "type": "boolean" + }, + "default_placement": { + "$ref": "#/components/schemas/DefaultPlacement" + }, + "grant_revision": { + "type": "integer" + }, + "org_id": { + "type": "string" + }, + "project_id": { + "type": "string" + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CloudprofilesTarget" + } + } + } + }, "ProjectDomain": { "type": "object", "required": [ @@ -35813,12 +35788,16 @@ "project_id", "target_ids", "revision", - "revoked" + "revoked", + "default" ], "properties": { "cloud_id": { "type": "string" }, + "default": { + "type": "boolean" + }, "org_id": { "type": "string" }, diff --git a/apps/dashboard/src/client/cache-contract.test.ts b/apps/dashboard/src/client/cache-contract.test.ts index d775a3aac..7f7c66bae 100644 --- a/apps/dashboard/src/client/cache-contract.test.ts +++ b/apps/dashboard/src/client/cache-contract.test.ts @@ -46,8 +46,6 @@ for (const [, op] of reads) { // 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 = { - EnvironmentCloud: - "the environment Cloud read has no identity; it goes when Clouds stop being per environment", "Watch[]": "release watches are only read one at a time, by deployment", "Collection[]": "build output collections are delivered to the log view, not listed", diff --git a/apps/dashboard/src/client/forge/loomplane/codecs.ts b/apps/dashboard/src/client/forge/loomplane/codecs.ts index a8ea7db12..f84a3180a 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"}, @@ -465,14 +465,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"]}, @@ -880,7 +877,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"]}, @@ -888,11 +885,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"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "targets": {"ts": "targets", "codec": () => CODECS["ProjectCloud.targets"]}}, "required": ["cloud_id", "cloud_revision", "default", "grant_revision", "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/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/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..e3cc06210 --- /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"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "targets": {"ts": "targets", "codec": () => codec_ProjectCloud_targets}}, "required": ["cloud_id", "cloud_revision", "default", "grant_revision", "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 1e776bb8d..8afe7422d 100644 --- a/apps/dashboard/src/client/forge/loomplane/entities.ts +++ b/apps/dashboard/src/client/forge/loomplane/entities.ts @@ -7,7 +7,6 @@ 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' }, @@ -45,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' } }, @@ -60,7 +60,6 @@ export const entities = { 'EntryDetail': { idField: 'id' }, 'EntrySummary': { idField: 'id' }, 'Environment': { idField: 'id' }, - 'EnvironmentCloud': { fields: { 'assignment': 'Assignment' } }, 'EnvironmentList': { fields: { 'environments': 'Environment' } }, 'EventPage': { fields: { 'items': 'FleetEvent' } }, 'Expansion': { idField: 'id' }, @@ -129,9 +128,10 @@ export const entities = { 'PolicyList': { fields: { 'policies': 'Policy' } }, 'Pool': { idField: 'id' }, 'PoolList': { fields: { 'pools': 'Pool' } }, - 'Preview': { idField: 'id', fields: { 'after': 'CloudprofilesTarget', 'afterAssignment': 'Assignment', 'before': 'CloudprofilesTarget', 'beforeAssignment': 'Assignment' } }, + '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' }, diff --git a/apps/dashboard/src/client/forge/loomplane/hooks.ts b/apps/dashboard/src/client/forge/loomplane/hooks.ts index 2eae3dd2d..e86dd40a4 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, 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, 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']); @@ -312,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']); 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/ops.ts b/apps/dashboard/src/client/forge/loomplane/ops.ts index feab7ad95..f1bbac32f 100644 --- a/apps/dashboard/src/client/forge/loomplane/ops.ts +++ b/apps/dashboard/src/client/forge/loomplane/ops.ts @@ -2664,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', @@ -2706,24 +2725,6 @@ export const ops = { provides: [], invalidates: ['Environment[]'], }, - 'environmentClouds.get': { - method: 'GET', - path: '/api/v1/projects/{id}/environments/{environmentId}/cloud', - rootType: 'EnvironmentCloud', - 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', @@ -3952,7 +3953,6 @@ 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' }, @@ -3990,6 +3990,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' } }, @@ -4005,7 +4006,6 @@ export const entities = { 'EntryDetail': { idField: 'id' }, 'EntrySummary': { idField: 'id' }, 'Environment': { idField: 'id' }, - 'EnvironmentCloud': { fields: { 'assignment': 'Assignment' } }, 'EnvironmentList': { fields: { 'environments': 'Environment' } }, 'EventPage': { fields: { 'items': 'FleetEvent' } }, 'Expansion': { idField: 'id' }, @@ -4074,9 +4074,10 @@ export const entities = { 'PolicyList': { fields: { 'policies': 'Policy' } }, 'Pool': { idField: 'id' }, 'PoolList': { fields: { 'pools': 'Pool' } }, - 'Preview': { idField: 'id', fields: { 'after': 'CloudprofilesTarget', 'afterAssignment': 'Assignment', 'before': 'CloudprofilesTarget', 'beforeAssignment': 'Assignment' } }, + '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' }, @@ -4382,11 +4383,11 @@ export const streams = [ { 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', @@ -4394,7 +4395,7 @@ export const streams = [ message: 'cloud_sync.updated', entity: 'CloudSyncEvent', intent: 'patch', - invalidates: ['Sync:{id}', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'DefaultCloud:{projectId}'], decode: (payload: unknown) => decode(payload, CODECS['CloudSyncEvent']), }, { @@ -4760,11 +4761,11 @@ export const streams = [ { 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', @@ -4772,7 +4773,7 @@ export const streams = [ message: 'cloud_sync.updated', entity: 'CloudSyncEvent', intent: 'patch', - invalidates: ['Sync:{id}', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'DefaultCloud:{projectId}'], decode: (payload: unknown) => decode(payload, CODECS['CloudSyncEvent']), }, { 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/environmentClouds.get.ts b/apps/dashboard/src/client/forge/loomplane/ops/environmentClouds.get.ts deleted file mode 100644 index ca01dadfe..000000000 --- a/apps/dashboard/src/client/forge/loomplane/ops/environmentClouds.get.ts +++ /dev/null @@ -1,11 +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', - rootType: 'EnvironmentCloud', - provides: [], - invalidates: [], - responseCodec: codec_EnvironmentCloud, -} 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 bb7a6d492..0f8c5caab 100644 --- a/apps/dashboard/src/client/forge/loomplane/rest.ts +++ b/apps/dashboard/src/client/forge/loomplane/rest.ts @@ -3015,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 @@ -3948,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 diff --git a/apps/dashboard/src/client/forge/loomplane/sse.ts b/apps/dashboard/src/client/forge/loomplane/sse.ts index 498efed2f..6e3d98025 100644 --- a/apps/dashboard/src/client/forge/loomplane/sse.ts +++ b/apps/dashboard/src/client/forge/loomplane/sse.ts @@ -655,15 +655,6 @@ export class RealtimeEventsSSEClient extends EventEmitter { } }); - 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) => { try { const data: types.RealtimeForgeGap = decode(JSON.parse(event.data), "RealtimeForgeGap"); @@ -754,6 +745,15 @@ export class RealtimeEventsSSEClient extends EventEmitter { } }); + 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"); @@ -1270,22 +1270,6 @@ export class RealtimeEventsSSEClient extends EventEmitter { 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); - } - /** * Register a handler for forge.gap events. * @param handler - Function to call when forge.gap event is received @@ -1446,6 +1430,22 @@ export class RealtimeEventsSSEClient extends EventEmitter { 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); + } + /** * Register a handler for realtime.snapshot events. * @param handler - Function to call when realtime.snapshot event is received diff --git a/apps/dashboard/src/client/forge/loomplane/stream-bindings.ts b/apps/dashboard/src/client/forge/loomplane/stream-bindings.ts index 63eb0b638..d002ca3ba 100644 --- a/apps/dashboard/src/client/forge/loomplane/stream-bindings.ts +++ b/apps/dashboard/src/client/forge/loomplane/stream-bindings.ts @@ -238,11 +238,11 @@ export const streams = [ { 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:{id}', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'DefaultCloud:{projectId}'], decode: (payload: unknown) => decode(payload, CODECS['CloudSyncEvent']), }, { @@ -616,11 +616,11 @@ export const streams = [ { 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:{id}', 'Sync[]', 'EnvironmentCloud'], + invalidates: ['Sync:{id}', 'Sync[]', 'DefaultCloud:{projectId}'], decode: (payload: unknown) => decode(payload, CODECS['CloudSyncEvent']), }, { diff --git a/apps/dashboard/src/client/forge/loomplane/types.ts b/apps/dashboard/src/client/forge/loomplane/types.ts index b157795f9..5365140fd 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; @@ -2405,24 +2402,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; @@ -2433,7 +2412,7 @@ export interface EnvironmentList { } export interface EnvironmentUsage { - assigned: boolean; + default: boolean; environmentId: string; environmentName: string; placements: PlacementUsage[]; @@ -4620,10 +4599,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; @@ -4674,6 +4653,23 @@ export interface Project { updatedAt: string; } +export interface ProjectCloud { + cloudId: string; + cloudRevision: number; + default: boolean; + defaultPlacement?: DefaultPlacement; + grantRevision: number; + orgId: string; + projectId: string; + targets: CloudprofilesTarget[]; +} + +export interface ProjectCloudEvent { + cloudId: string | null; + orgId: string; + projectId: string; +} + export interface ProjectDomain { hostnames: HostnameUse[]; mode: string; @@ -4690,6 +4686,7 @@ export interface ProjectDomainList { export interface ProjectGrant { cloudId: string; + default: boolean; orgId: string; projectId: string; revision: number; diff --git a/apps/dashboard/src/components/cloud-detail/environments.tsx b/apps/dashboard/src/components/cloud-detail/environments.tsx index da5d7ea37..1794c4dd1 100644 --- a/apps/dashboard/src/components/cloud-detail/environments.tsx +++ b/apps/dashboard/src/components/cloud-detail/environments.tsx @@ -46,14 +46,14 @@ export function envState( return { label: "Change failed", tone: "failed" } return { label: syncLabel(change.status), tone: "flight" } } - if (!env.assigned) return { label: "Left, services remain", tone: "waiting" } + if (!env.default) return { label: "Services placed here", tone: "waiting" } return { label: "In sync", tone: "live" } } /** - * EnvironmentsOnCloud lists the environments that use the Cloud. An - * environment belongs to its project, so each row opens the project's Cloud - * tab, where it takes or leaves the Cloud and chooses targets. + * EnvironmentsOnCloud lists the environments that use the Cloud: every + * environment of a project whose default it is, and any environment still + * running services placed on it. Each row opens its project's Clouds tab. */ export function EnvironmentsOnCloud({ usage, @@ -68,14 +68,14 @@ export function EnvironmentsOnCloud({ projects: Project[] }) { const envs = usage.data?.environments ?? [] - const assigned = envs.filter((e) => e.assigned) + const onDefault = envs.filter((e) => e.default) const projectOf = (id: string) => projects.find((p) => p.id === id) return (
{usage.status === "error" ? ( {grants && grants.length === 0 - ? "Give a project access first, then choose this Cloud from that project's Cloud tab." - : "Choose this Cloud for an environment from its project's Cloud tab. Its services then run on this Cloud's targets."} + ? "Give a project access. A project's first Cloud becomes its default, and all its environments use it." + : "Make this a project's default Cloud from that project's Clouds tab. All its environments then use it."} ) : ( } > diff --git a/apps/dashboard/src/components/cloud-detail/projects.tsx b/apps/dashboard/src/components/cloud-detail/projects.tsx index 76083497e..acd138e96 100644 --- a/apps/dashboard/src/components/cloud-detail/projects.tsx +++ b/apps/dashboard/src/components/cloud-detail/projects.tsx @@ -136,7 +136,7 @@ export function Projects({ const style = p ? projectStyle(p) : null const allowed = targets.filter((t) => g.targetIds.includes(t.id)) const envs = (usage?.environments ?? []).filter( - (e) => e.projectId === g.projectId && e.assigned + (e) => e.projectId === g.projectId && e.default ) return ( @@ -165,6 +165,7 @@ export function Projects({ ) } + meta={g.default ? "Default Cloud" : undefined} /> {g.targetIds.length === 0 ? ( @@ -187,7 +188,9 @@ export function Projects({ "…" ) : envs.length === 0 ? ( - None chose this Cloud yet + {g.default + ? "No environments yet" + : "Not its default Cloud"} ) : ( envs.map((e) => { diff --git a/apps/dashboard/src/components/cloud-targets/change-review.tsx b/apps/dashboard/src/components/cloud-targets/change-review.tsx index 94c7dd536..05b1a570b 100644 --- a/apps/dashboard/src/components/cloud-targets/change-review.tsx +++ b/apps/dashboard/src/components/cloud-targets/change-review.tsx @@ -2,7 +2,11 @@ import { CloudLoading } from "./infrastructure-ui" import { Alert, AlertDescription } from "@/components/ui/alert" import { useEffect, useRef, useState } from "react" import * as api from "@/client/forge/loomplane/hooks" -import type { ChangeInputBody, Preview } from "@/client/forge/loomplane/types" +import type { + ChangeInputBody, + Preview, + Target, +} from "@/client/forge/loomplane/types" import { useMutation, useQuery } from "@/client/hooks" import { messageOf, statusOf } from "@/client/errors" import { Button } from "@/components/ui/button" @@ -17,8 +21,11 @@ import { import { EnvironmentProgress } from "./organization-activity" import { useOrganization } from "@/lib/organization" -type AssignmentIntent = { - environmentId: string +/** + * DefaultCloudIntent makes cloudId the project's default Cloud, or with "" + * leaves the project without one. revision is the current default's. + */ +type DefaultCloudIntent = { cloudId: string revision: number } @@ -27,7 +34,7 @@ type ReviewProps = { projectId: string title: string change?: ChangeInputBody - assignment?: AssignmentIntent + defaultCloud?: DefaultCloudIntent revert?: string onClose: () => void onApplied: () => void @@ -38,7 +45,7 @@ export function ChangeReview(props: ReviewProps) { key={JSON.stringify([ props.projectId, props.change, - props.assignment, + props.defaultCloud, props.revert, ])} {...props} @@ -49,7 +56,7 @@ function ReviewContent({ projectId, title, change, - assignment, + defaultCloud, revert, onClose, onApplied, @@ -58,7 +65,7 @@ function ReviewContent({ const accountName = (id: string) => accounts.data?.connections.find((c) => c.id === id)?.name ?? id const previewChange = useMutation(api.useCloudChangesPreview) - const previewAssignment = useMutation(api.useEnvironmentCloudsPreview) + const previewDefaultCloud = useMutation(api.useDefaultCloudPreview) const previewRevert = useMutation(api.useCloudSyncsPreviewRevert) const apply = useMutation(api.useCloudChangesApply) const previewOrgChange = useMutation(api.useOrganizationCloudChangesPreview) @@ -73,27 +80,24 @@ function ReviewContent({ const [loading, setLoading] = useState(true) const [version, setVersion] = useState(0) const [latestChange, setLatestChange] = useState(change) - const [latestAssignment, setLatestAssignment] = useState(assignment) + const [latestDefault, setLatestDefault] = useState(defaultCloud) const idempotency = useRef(crypto.randomUUID()) const intent = JSON.stringify({ projectId, latestChange, - latestAssignment, + latestDefault, revert, }) useEffect(() => { let current = true const load = revert ? previewRevert.mutateAsync({ path: { id: projectId, syncId: revert } }) - : latestAssignment - ? previewAssignment.mutateAsync({ - path: { - id: projectId, - environmentId: latestAssignment!.environmentId, - }, + : latestDefault + ? previewDefaultCloud.mutateAsync({ + path: { id: projectId }, body: { - cloudId: latestAssignment!.cloudId, - revision: latestAssignment!.revision, + cloudId: latestDefault.cloudId, + revision: latestDefault.revision, }, }) : org @@ -152,13 +156,11 @@ function ReviewContent({ }) ).refetch() setLatestChange({ ...change, revision: current.revision }) - } else if (assignment) { + } else if (defaultCloud) { const current = await api - .useEnvironmentCloudsGet({ - path: { id: projectId, environmentId: assignment.environmentId }, - }) + .useDefaultCloudGet({ path: { id: projectId } }) .refetch() - setLatestAssignment({ ...assignment, revision: current.revision }) + setLatestDefault({ ...defaultCloud, revision: current.revision }) } setVersion((v) => v + 1) } catch (err) { @@ -241,10 +243,11 @@ function ReviewContent({ {preview.after.region ? ` / ${preview.after.region}` : ""}

)} - {(assignment || - preview.beforeAssignment || - preview.afterAssignment) && ( - + {(defaultCloud || preview.beforeCloud || preview.afterCloud) && ( + )} {(preview.blockers ?? []).map((blocker, i) => ( @@ -330,7 +333,12 @@ function ReviewContent({ ) } -function AssignmentPreview({ +/** + * DefaultCloudPreview shows a project default change: which Cloud every + * environment resolves through before and after, and what each target + * name a service may use points at on either side. + */ +function DefaultCloudPreview({ preview, accountName, }: { @@ -342,53 +350,56 @@ function AssignmentPreview({ }) const name = (id: string) => clouds.data?.clouds?.find((cloud) => cloud?.id === id)?.name ?? id - const before = preview.beforeAssignment - const after = preview.afterAssignment + const before = preview.beforeCloud + const after = preview.afterCloud + const where = (t: Target) => + `${t.provider} / ${accountName(t.connectionId)}${t.region ? ` / ${t.region}` : ""}` const targetNames = [ ...new Set([ ...(before?.targets ?? []).map((t) => t.name), ...(after?.targets ?? []).map((t) => t.name), ]), - ] + ].sort() return ( -
-

- Current Cloud:{" "} - {before - ? `${name(before.cloudId)} (revision ${before.cloudRevision})` - : "Direct placement"} -

+

- Desired Cloud:{" "} - {after - ? `${name(after.cloudId)} (revision ${after.cloudRevision})` - : preview.input.cloudId - ? name(preview.input.cloudId) - : "Direct placement"} + Every environment moves from{" "} + + {before ? name(before.cloudId) : "no default Cloud"} + {" "} + to{" "} + + {after + ? name(after.cloudId) + : preview.input.cloudId + ? name(preview.input.cloudId) + : "no default Cloud"} + + .

- {targetNames.map((slug) => { - const current = before?.targets.find((target) => target.name === slug) - const desired = after?.targets.find((target) => target.name === slug) - return ( -
-

{slug}

-

- Current:{" "} - {current - ? `${current.provider} / ${accountName(current.connectionId)}${current.region ? ` / ${current.region}` : ""}` - : "Not assigned"} -

-

- Desired:{" "} - {desired - ? `${desired.provider} / ${accountName(desired.connectionId)}${desired.region ? ` / ${desired.region}` : ""}` - : !after && preview.input.cloudId - ? "Unavailable until blockers are resolved" - : "Target removed from this environment"} -

-
- ) - })} + {targetNames.length > 0 && ( +
+ {targetNames.map((slug) => { + const current = before?.targets.find((t) => t.name === slug) + const desired = after?.targets.find((t) => t.name === slug) + return ( +
+ {slug} + + {current ? where(current) : "Not in the current Cloud"} + {" → "} + {desired + ? where(desired) + : "Not in the new Cloud: services that name it stop planning"} + +
+ ) + })} +
+ )}
) } diff --git a/apps/dashboard/src/components/cloud-targets/service-adoption.tsx b/apps/dashboard/src/components/cloud-targets/service-adoption.tsx index ae042ee56..287bc6f85 100644 --- a/apps/dashboard/src/components/cloud-targets/service-adoption.tsx +++ b/apps/dashboard/src/components/cloud-targets/service-adoption.tsx @@ -9,7 +9,7 @@ import { } from "@/components/ui/select" import { useState } from "react" import * as api from "@/client/forge/loomplane/hooks" -import type { Environment, Target } from "@/client/forge/loomplane/types" +import type { DefaultPlacement, Target } from "@/client/forge/loomplane/types" import { useInvalidate, useMutation, useQuery } from "@/client/hooks" import { messageOf, statusOf } from "@/client/errors" import { Button } from "@/components/ui/button" @@ -74,32 +74,32 @@ function TagOutcome({ targets, tags }: { targets: Target[]; tags: string[] }) { ) } +/** + * ServiceAdoption puts each service on one of the default Cloud's targets, in + * every environment. An environment can still override a service from the + * deploy screen; those overrides are listed here and cleared by a change. + */ export function ServiceAdoption({ projectId, - environment, - environments, targets, + fallback, onSaved, }: { projectId: string - environment: Environment - environments: Environment[] targets: Target[] - onSaved: () => Promise + /** fallback is the default Cloud's default placement, when it has one. */ + fallback?: DefaultPlacement | null + onSaved?: () => void }) { const manifest = useQuery(api.useManifestsCurrent, { path: { id: projectId }, }) - const assignment = useQuery(api.useEnvironmentCloudsGet, { - path: { id: projectId, environmentId: environment.id }, - }) const connections = useQuery(api.useConnectionsList) const save = useMutation(api.useManifestsSave) const invalidate = useInvalidate() const { can } = useOrganization() const [choices, setChoices] = useState>({}) const [modes, setModes] = useState>({}) - const fallback = assignment.data?.assignment?.defaultPlacement const fallbackAccount = (connections.data?.connections ?? []).find( (c) => c.id === fallback?.connectionId ) @@ -112,8 +112,6 @@ export function ServiceAdoption({ reviewing && manifest.data?.manifest ? adoptServiceTarget( manifest.data.manifest, - environments, - environment.name, reviewing, choices[reviewing] ) @@ -130,7 +128,7 @@ export function ServiceAdoption({ invalidate(api.useManifestsCurrent) setReviewing(null) setChoices({}) - await onSaved() + onSaved?.() } catch (err) { setError(messageOf(err, "The service target wasn't saved.")) if (statusOf(err) === 409) { @@ -158,9 +156,7 @@ export function ServiceAdoption({ return Loading service placement... return (
-

- Services in {environment.name} -

+

Services

{!services.length ? ( + > ) + .filter(([, o]) => + [ + "provider", + "target", + "cloud_target", + "cloudTarget", + "cloud_tags", + "cloudTags", + ].some((k) => o?.[k] !== undefined) + ) + .map(([env]) => env) const mode: Mode = modes[name] ?? (settings.cloudTags ? "tags" : "name") const choice = choices[name] @@ -198,6 +211,8 @@ export function ServiceAdoption({

{name}

{current} + {overridden.length > 0 && + ` · ${overridden.join(", ")} ${overridden.length === 1 ? "sets its own" : "set their own"}`}

{ - setChosen(e ?? "") - window.localStorage.setItem(preference, e ?? "") - }} - > - - - - - {environments.data.environments.map((e) => ( - - {e.name} - - ))} - - - - - } - /> - ) -} -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. Put a service + on one of its targets here, or with{" "} + 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 && ( +
+ + {isDefault && ( + !!t + )} + 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() - }} - /> - )} -
- ) -} - -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 ? ( - setEditing(null)} /> - ) : ( -
- {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 - - )} -
- ))} -
)}
) diff --git a/apps/dashboard/src/components/deploy-dialog.tsx b/apps/dashboard/src/components/deploy-dialog.tsx index 8e7a40663..9cf17b837 100644 --- a/apps/dashboard/src/components/deploy-dialog.tsx +++ b/apps/dashboard/src/components/deploy-dialog.tsx @@ -408,10 +408,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 fd46f2249..39426d4f1 100644 --- a/apps/dashboard/src/components/deploy.tsx +++ b/apps/dashboard/src/components/deploy.tsx @@ -343,10 +343,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.tsx b/apps/dashboard/src/components/deployment-targets.tsx index 1673db968..a420687ee 100644 --- a/apps/dashboard/src/components/deployment-targets.tsx +++ b/apps/dashboard/src/components/deployment-targets.tsx @@ -7,8 +7,9 @@ import { toast } from "sonner" import { messageOf } from "@/client/errors" import { + useCloudsList, useConnectionsList, - useEnvironmentCloudsGet, + useDefaultCloudGet, useEnvironmentConnectionsChoose, useEnvironmentConnectionsGet, useManifestsCurrent, @@ -147,8 +148,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[], @@ -157,13 +158,10 @@ function placedManifest( const choice = cloudChoice(e.changes) if (!choice || e.row.section !== "services") return applyPlacement(m, e.row, e.environment, e.changes) - const adopted = adoptServiceTarget( - m, + const adopted = adoptServiceTarget(m, e.row.name, choice, { + environment: e.environment, environments, - e.environment, - e.row.name, - choice - ) + }) const rest = { ...e.changes } for (const key of cloudOwnedFields) delete rest[key] return applyPlacement(adopted, e.row, e.environment, rest) @@ -171,24 +169,25 @@ 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) - // The assignment changes on the Clouds page, not here, and its read has no - // cache identity, so read it fresh each time a placement panel opens. - const cloud = useQuery( - useEnvironmentCloudsGet, - { path: { id: projectId, environmentId: environmentId ?? "" } }, - { staleTime: 0 } - ) + 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 ?? [], - cloudAssigned: !!cloud.data?.assignment, - cloudTargets: (cloud.data?.assignment?.targets ?? []).filter( + /** 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 ), } @@ -321,11 +320,7 @@ function PlacementForm({ onClose: () => void onPendingChange?: (pending: boolean) => void }) { - const environmentId = environments.find((e) => e.name === environment)?.id - const { providers, cloudTargets, cloudAssigned } = usePlacementContext( - projectId, - environmentId - ) + const { providers, cloudTargets, cloudName } = usePlacementContext(projectId) return ( <> @@ -357,11 +352,10 @@ function PlacementForm({ revision={revision} row={row} environment={environment} - environmentId={environmentId} environments={environments} catalog={providers.data.providers} cloudTargets={cloudTargets} - cloudAssigned={cloudAssigned} + cloudName={cloudName} mode={mode} pending={pending} onUse={onUse} @@ -382,11 +376,10 @@ function PlacementChoices({ revision, row, environment, - environmentId, environments, catalog, cloudTargets, - cloudAssigned, + cloudName, mode, pending, onUse, @@ -399,11 +392,10 @@ function PlacementChoices({ revision: number row: PlacementRow environment: string - environmentId?: string environments: Environment[] catalog: Provider[] cloudTargets: Target[] - cloudAssigned: boolean + cloudName?: string mode: "pending" | "save" pending?: PendingPlacement onUse?: (change: PendingPlacement) => void @@ -411,7 +403,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) @@ -509,17 +501,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 (
0 && ( - Cloud targets + {cloudName ?? "Cloud targets"} {cloudChoices.map((t) => ( {t.displayName || t.name} @@ -723,25 +709,23 @@ function PlacementChoices({ )} {row.section === "services" && cloudTargets.length === 0 && (

- {cloudAssigned - ? `The Cloud ${environment} uses has no targets this project may use yet.` - : `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."}{" "} - {cloudAssigned ? "Add a target" : "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/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..1971fe23f 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,69 @@ 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"], + }) +}) diff --git a/apps/dashboard/src/lib/cloud-targets.ts b/apps/dashboard/src/lib/cloud-targets.ts index 54f052f0c..56d906eb6 100644 --- a/apps/dashboard/src/lib/cloud-targets.ts +++ b/apps/dashboard/src/lib/cloud-targets.ts @@ -43,19 +43,67 @@ 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[] } ): Manifest { + if (only) + return adoptInEnvironment( + manifest, + only.environments, + only.environment, + service, + choice + ) 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 (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 = [ + "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 +120,19 @@ export function adoptServiceTarget( delete next.defaults.provider delete next.defaults.region } +} + +function adoptInEnvironment( + manifest: Manifest, + environments: Environment[], + environment: string, + service: string, + choice: CloudChoice +): 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 } @@ -142,7 +203,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/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..eff528df0 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( 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/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..991396739 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,20 @@ 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. ## Pick a target by tags @@ -88,4 +99,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/reference/loomctl.mdx b/apps/docs/content/docs/reference/loomctl.mdx index 74c91e2fa..8853b737b 100644 --- a/apps/docs/content/docs/reference/loomctl.mdx +++ b/apps/docs/content/docs/reference/loomctl.mdx @@ -139,7 +139,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..a33ae7abf 100644 --- a/apps/docs/content/docs/reference/loomplane-yaml.mdx +++ b/apps/docs/content/docs/reference/loomplane-yaml.mdx @@ -41,7 +41,7 @@ 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_target` | string | A named target in the project's default Cloud, the same in every environment unless an environment override names another. 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/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 d89401321..81ca5ebfb 100644 --- a/extensions/realtime/routes.go +++ b/extensions/realtime/routes.go @@ -57,8 +57,8 @@ func streamBindings() forge.RouteOption { 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:{id}", "Sync[]", "EnvironmentCloud"), + 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[]"), @@ -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 14c31101c..5a19cd7e1 100644 --- a/internal/agentknowledge/docs.json +++ b/internal/agentknowledge/docs.json @@ -1,6 +1,6 @@ { "version": 1, - "digest": "102663f515395175200de8becb102012cfe2189aa91266a11b0d9b5a127b3acd", + "digest": "1c186cae47be86b0060f56acf29d058dd867874687d6c616477f9d8211d28a35", "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## 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", @@ -441,14 +441,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_ID --kind K --name RESOURCE --target CONN [--provider P] [--version V] [--env E]` | Plans a catalog service added to an existing project (`server` or `kubernetes`) |\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_ID --kind K --name RESOURCE --target CONN [--provider P] [--version V] [--env E]` | Plans a catalog service added to an existing project (`server` or `kubernetes`) |\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_target` | string | A named target in the project's default Cloud, the same in every environment unless an environment override names another. 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..6eca7dfb9 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,30 @@ 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"` + // 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) } diff --git a/internal/cloudprofiles/pgstore.go b/internal/cloudprofiles/pgstore.go index 4cc0dda95..e694aa523 100644 --- a/internal/cloudprofiles/pgstore.go +++ b/internal/cloudprofiles/pgstore.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/xraph/loomplane/internal/projects" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" @@ -153,17 +154,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 +275,85 @@ 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) } -// 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) +// 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) } -// 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 +// 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 } -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 *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.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.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, &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, 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 +406,17 @@ 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) + _ 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/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/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_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..1b8109d03 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 } @@ -538,12 +553,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 +968,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..283c1bbd6 100644 --- a/internal/planning/cloud_sync_plan.go +++ b/internal/planning/cloud_sync_plan.go @@ -15,15 +15,15 @@ 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 { +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 { 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] @@ -359,7 +359,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 +379,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..2b30676ca 100644 --- a/internal/planning/cloud_targets.go +++ b/internal/planning/cloud_targets.go @@ -33,12 +33,16 @@ 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"` @@ -71,8 +75,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 +146,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 +202,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,7 +225,7 @@ 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 } @@ -264,7 +268,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 == "" } @@ -280,7 +284,7 @@ func cloudPath(name string, set manifest.Settings) string { // 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] @@ -289,7 +293,7 @@ func ResolveCloudTargets(m *manifest.Manifest, environment string, assignment *c } // 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) { +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) { raw, err := json.Marshal(m) if err != nil { return nil, nil, err @@ -348,15 +352,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 { @@ -606,15 +610,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..1dd27207e 100644 --- a/internal/planning/location_migration.go +++ b/internal/planning/location_migration.go @@ -11,7 +11,7 @@ import ( // 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, assignment *cloudprofiles.ProjectCloud, 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 { 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..fe72b2366 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 { @@ -154,21 +154,21 @@ func platformPlacement(name, path string, set manifest.Settings, a *cloudprofile // 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..3de368271 100644 --- a/internal/planning/service.go +++ b/internal/planning/service.go @@ -853,18 +853,19 @@ 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{} 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/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/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..ac4b6307b 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,33 @@ 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) } 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; From fd9ad325b72a21201bca8e6e24200ff2d70cd6c2 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Fri, 20 Nov 2026 18:43:26 -0600 Subject: [PATCH 3/5] feat(clouds): let a service name the Cloud it runs on A project resolves through its default Cloud; a service can now name any other Cloud granted to the project: trainer: cloud: GPU Lab cloud_target: a100 environments: preview: {cloud_target: eu-run} # the default Cloud's eu-run staging: {cloud: GPU Lab EU} # same target, another Cloud `cloud` alone uses that Cloud's default placement. 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; one with only cloud keeps the target. Clouds are named by name, unique per organization. Planning: - One resolution pass per Cloud: the default, then each Cloud a service names. A pass holds the other Clouds' services, so the single-Cloud resolution (pools, capacity intents, Loomplane Cloud rooms, location constraints) runs unchanged and the placements merge. The database gateway and composed resources stay on the default Cloud. - A Cloud the project can't use fails at services..cloud (cloud-unknown), and so does a named Cloud with no target and no default placement (cloud-default-missing) rather than silently skipping. Errors say which Cloud a target was looked up in. - Placements record named. A project default change keeps named placements; a change to a Cloud itself still reaches every service on it. Pool relocation and location moves revalidate each pin against its own Cloud. API, CLI and dashboard: - ProjectCloud carries the Cloud's name; placement edits accept cloud. - The deploy drawer's "Runs on" lists every granted Cloud's targets under the Cloud's name, and choosing one writes cloud and cloud_target together. Every Cloud on the Clouds tab can take services. CI: FORGE_CLI moves to cmd/forge v1.14.3. cmd/forge v1.14.2 still required the pre-release root module, so its generator lacks the cache-tag fixes this client was generated with (xraph/forge#134). Verified: go build/vet, the Go unit suite and golangci-lint pass; new tests cover the merge rule, named-Cloud planning and findings, the default change keeping named services, and ResolveNamedCloud against Postgres; dashboard typecheck, lint and 2,217 tests pass, with new ones for choosing another Cloud's target in the drawer and on the Clouds tab; the integration tests matching Cloud, Shared, Pool, Capacity, Location, Server, Managed, Default, Tags, Usage, Placement and Cluster pass (six timed out under load in the batch run and pass on their own); a CLI built from xraph/forge#134 regenerates the client with no diff. --- .github/workflows/ci.yml | 2 +- apps/dashboard/specs/loomplane.openapi.json | 7 + .../src/client/forge/loomplane/codecs.ts | 4 +- .../codecs/EditInputBody.placement.ts | 2 +- .../forge/loomplane/codecs/ProjectCloud.ts | 2 +- .../src/client/forge/loomplane/types.ts | 2 + .../cloud-targets/service-adoption.tsx | 18 ++- .../components/cloud-targets/workspace.tsx | 22 ++-- .../components/deployment-targets.test.tsx | 86 +++++++++++++ .../src/components/deployment-targets.tsx | 121 +++++++++++++++--- apps/dashboard/src/lib/cloud-targets.test.ts | 67 ++++++++++ apps/dashboard/src/lib/cloud-targets.ts | 17 ++- apps/dashboard/src/lib/placement.ts | 16 +++ apps/dashboard/src/pages/clouds.test.tsx | 42 ++++++ .../content/docs/clouds/cloud-targets.mdx | 24 ++++ .../content/docs/reference/loomplane-yaml.mdx | 3 +- internal/agentknowledge/docs.json | 6 +- internal/cloudprofiles/model.go | 10 ++ internal/cloudprofiles/pgstore.go | 22 +++- internal/planning/cloud_named.go | 116 +++++++++++++++++ internal/planning/cloud_named_test.go | 111 ++++++++++++++++ internal/planning/cloud_sync.go | 7 +- internal/planning/cloud_sync_plan.go | 23 +++- internal/planning/cloud_targets.go | 66 ++++++++-- internal/planning/location_migration.go | 5 +- internal/planning/platform.go | 2 +- internal/planning/service.go | 34 ++--- pkg/manifest/cloud_field_test.go | 54 ++++++++ pkg/manifest/edit.go | 13 +- pkg/manifest/manifest.go | 26 +++- pkg/manifest/schema.json | 8 +- tests/integration/cloud_profiles_test.go | 11 ++ 32 files changed, 841 insertions(+), 108 deletions(-) create mode 100644 internal/planning/cloud_named.go create mode 100644 internal/planning/cloud_named_test.go create mode 100644 pkg/manifest/cloud_field_test.go 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.openapi.json b/apps/dashboard/specs/loomplane.openapi.json index 707671339..3e5d51884 100644 --- a/apps/dashboard/specs/loomplane.openapi.json +++ b/apps/dashboard/specs/loomplane.openapi.json @@ -27068,6 +27068,9 @@ "build": { "$ref": "#/components/schemas/Build" }, + "cloud": { + "type": "string" + }, "cloud_sql_network": { "$ref": "#/components/schemas/CloudSQLApplicationNetwork" }, @@ -35696,6 +35699,7 @@ "org_id", "project_id", "cloud_id", + "name", "default", "targets" ], @@ -35715,6 +35719,9 @@ "grant_revision": { "type": "integer" }, + "name": { + "type": "string" + }, "org_id": { "type": "string" }, diff --git a/apps/dashboard/src/client/forge/loomplane/codecs.ts b/apps/dashboard/src/client/forge/loomplane/codecs.ts index f84a3180a..d4c1965a4 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs.ts @@ -436,7 +436,7 @@ export const CODECS: Record = { "EditInputBody.add_resource.uses": {"kind": "record"}, "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"]}, @@ -885,7 +885,7 @@ 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"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "targets": {"ts": "targets", "codec": () => CODECS["ProjectCloud.targets"]}}, "required": ["cloud_id", "cloud_revision", "default", "grant_revision", "org_id", "project_id", "targets"]}, + "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"]}, 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/ProjectCloud.ts b/apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloud.ts index e3cc06210..a910a3c03 100644 --- a/apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloud.ts +++ b/apps/dashboard/src/client/forge/loomplane/codecs/ProjectCloud.ts @@ -2,4 +2,4 @@ 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"}, "org_id": {"ts": "orgId"}, "project_id": {"ts": "projectId"}, "targets": {"ts": "targets", "codec": () => codec_ProjectCloud_targets}}, "required": ["cloud_id", "cloud_revision", "default", "grant_revision", "org_id", "project_id", "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/types.ts b/apps/dashboard/src/client/forge/loomplane/types.ts index 5365140fd..9a0d244c2 100644 --- a/apps/dashboard/src/client/forge/loomplane/types.ts +++ b/apps/dashboard/src/client/forge/loomplane/types.ts @@ -2238,6 +2238,7 @@ export interface EditInputBody { }; placement?: { build?: Build; + cloud?: string; cloudSqlNetwork?: CloudSQLApplicationNetwork; cloudTags?: string[]; cloudTarget?: string; @@ -4659,6 +4660,7 @@ export interface ProjectCloud { default: boolean; defaultPlacement?: DefaultPlacement; grantRevision: number; + name: string; orgId: string; projectId: string; targets: CloudprofilesTarget[]; diff --git a/apps/dashboard/src/components/cloud-targets/service-adoption.tsx b/apps/dashboard/src/components/cloud-targets/service-adoption.tsx index 287bc6f85..8592eb403 100644 --- a/apps/dashboard/src/components/cloud-targets/service-adoption.tsx +++ b/apps/dashboard/src/components/cloud-targets/service-adoption.tsx @@ -37,9 +37,11 @@ type Mode = "name" | "tags" /** sameChoice reports whether a pending choice changes nothing. */ function sameChoice( choice: CloudChoice | undefined, - current: { cloudTarget?: string; cloudTags?: string[] } + current: { cloud?: string; cloudTarget?: string; cloudTags?: string[] }, + cloud?: string ): boolean { if (choice === undefined) return true + if ((current.cloud ?? "") !== (cloud ?? "")) return false if (typeof choice === "string") return !choice || choice === current.cloudTarget return ( @@ -82,11 +84,14 @@ function TagOutcome({ targets, tags }: { targets: Target[]; tags: string[] }) { export function ServiceAdoption({ projectId, targets, + cloud, fallback, onSaved, }: { projectId: string targets: Target[] + /** cloud names the Cloud these targets are in, unless it's the default. */ + cloud?: string /** fallback is the default Cloud's default placement, when it has one. */ fallback?: DefaultPlacement | null onSaved?: () => void @@ -113,7 +118,9 @@ export function ServiceAdoption({ ? adoptServiceTarget( manifest.data.manifest, reviewing, - choices[reviewing] + choices[reviewing], + undefined, + cloud ) : null const pending = reviewing ? choices[reviewing] : undefined @@ -195,10 +202,11 @@ export function ServiceAdoption({ typeof choice === "object" ? choice.tags : (settings.cloudTags ?? []) + const where = settings.cloud ? ` in ${settings.cloud}` : "" const current = settings.cloudTarget - ? `Target: ${settings.cloudTarget}` + ? `Target: ${settings.cloudTarget}${where}` : settings.cloudTags - ? `Tags: ${settings.cloudTags.join(", ")}` + ? `Tags: ${settings.cloudTags.join(", ")}${where}` : settings.provider ? `Direct: ${settings.provider}` : fallback @@ -269,7 +277,7 @@ export function ServiceAdoption({