Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions apps/api/openapi/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,22 @@
"format": "date-time",
"type": "string"
},
"dependencies": {
"additionalProperties": {
"properties": {
"versionSelector": {
"description": "CEL expression evaluated against the dependency deployment's current release version on the same resource.",
"type": "string"
}
},
"required": [
"versionSelector"
],
"type": "object"
},
"description": "Map of dependency deployment ID to a CEL version selector evaluated against that deployment's current release on the same resource. Inserted atomically with the version so reconciliation cannot fire before edges are attached.",
"type": "object"
},
"jobAgentConfig": {
"additionalProperties": true,
"type": "object"
Expand Down Expand Up @@ -5430,15 +5446,15 @@
"required": true
},
"responses": {
"202": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/DeploymentVersion"
}
}
},
"description": "Accepted response"
"description": "Deployment version created"
},
"400": {
"content": {
Expand All @@ -5449,6 +5465,16 @@
}
},
"description": "Invalid request"
},
"404": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Resource not found"
}
},
"summary": "Create a deployment version"
Expand Down
6 changes: 5 additions & 1 deletion apps/api/openapi/paths/deploymentversions.jsonnet
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ local openapi = import '../lib/openapi.libsonnet';
},
},
},
responses: openapi.acceptedResponse(openapi.schemaRef('DeploymentVersion'))
responses: openapi.okResponse(
openapi.schemaRef('DeploymentVersion'),
'Deployment version created',
)
+ openapi.notFoundResponse()
+ openapi.badRequestResponse(),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
},
},
Expand Down
14 changes: 14 additions & 0 deletions apps/api/openapi/schemas/deploymentversions.jsonnet
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,20 @@ local openapi = import '../lib/openapi.libsonnet';
type: 'object',
additionalProperties: { type: 'string' },
},
dependencies: {
type: 'object',
description: "Map of dependency deployment ID to a CEL version selector evaluated against that deployment's current release on the same resource. Inserted atomically with the version so reconciliation cannot fire before edges are attached.",
additionalProperties: {
type: 'object',
required: ['versionSelector'],
properties: {
versionSelector: {
type: 'string',
description: "CEL expression evaluated against the dependency deployment's current release version on the same resource.",
},
},
},
},
},
},

Expand Down
129 changes: 115 additions & 14 deletions apps/api/src/routes/v1/workspaces/deployments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { ApiError, asyncHandler } from "@/types/api.js";
import { evaluate } from "cel-js";
import { Router } from "express";
import { v4 as uuidv4 } from "uuid";
import { z } from "zod";

import type { Tx } from "@ctrlplane/db";
import { and, asc, count, desc, eq, inArray, takeFirst } from "@ctrlplane/db";
import { db } from "@ctrlplane/db/client";
import {
Expand All @@ -14,8 +16,6 @@ import {
import * as schema from "@ctrlplane/db/schema";
import { getClientFor } from "@ctrlplane/workspace-engine-sdk";

// 1 hour

import { validResourceSelector } from "../valid-selector.js";
import { listDeploymentVariablesByDeploymentRouter } from "./deployment-variables.js";

Expand Down Expand Up @@ -377,33 +377,134 @@ const listDeploymentVersions: AsyncTypedHandler<
});
};

const assertDeploymentExistsInWorkspace = async (
workspaceId: string,
deploymentId: string,
) => {
const found = await db.query.deployment.findFirst({
where: and(
eq(schema.deployment.id, deploymentId),
eq(schema.deployment.workspaceId, workspaceId),
),
});
if (found == null) throw new ApiError("Deployment not found", 404);
};

const validateDependencyEntries = (
entries: [string, { versionSelector: string }][],
parentDeploymentId: string,
) => {
for (const [depDeploymentId, edge] of entries) {
if (!z.string().uuid().safeParse(depDeploymentId).success)
throw new ApiError(
`Invalid dependency deployment id "${depDeploymentId}"`,
400,
);
if (depDeploymentId === parentDeploymentId)
throw new ApiError(
"A deployment version cannot depend on its own deployment",
400,
);
const { versionSelector: selector } = edge;
if (selector.trim() === "")
throw new ApiError(
`Missing versionSelector for dependency ${depDeploymentId}`,
400,
);
if (!validResourceSelector(selector))
throw new ApiError(
`Invalid versionSelector CEL expression for dependency ${depDeploymentId}`,
400,
);
}
};

const assertDependencyDeploymentsExistInWorkspace = async (
tx: Tx,
workspaceId: string,
dependencyDeploymentIds: string[],
) => {
if (dependencyDeploymentIds.length === 0) return;
const found = await tx
.select({ id: schema.deployment.id })
.from(schema.deployment)
.where(
and(
eq(schema.deployment.workspaceId, workspaceId),
inArray(schema.deployment.id, dependencyDeploymentIds),
),
);
const foundIds = new Set(found.map((d) => d.id));
for (const id of dependencyDeploymentIds) {
if (!foundIds.has(id))
throw new ApiError(`Dependency deployment ${id} not found`, 404);
}
};

const insertDeploymentVersionOrThrowConflict = async (
tx: Tx,
data: typeof schema.deploymentVersion.$inferInsert,
) => {
const insertedRows = await tx
.insert(schema.deploymentVersion)
.values(data)
.onConflictDoNothing()
.returning();
const inserted = insertedRows[0];
if (inserted == null)
throw new ApiError(
`Deployment version with tag "${data.tag}" already exists for this deployment`,
409,
);
return inserted;
};

const createDeploymentVersion: AsyncTypedHandler<
"/v1/workspaces/{workspaceId}/deployments/{deploymentId}/versions",
"post"
> = async (req, res) => {
const { workspaceId, deploymentId } = req.params;
const { body } = req;
const { dependencies, ...versionFields } = body;

Copy link

Copilot AI Apr 30, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This handler does not verify that deploymentId belongs to workspaceId (or even exists) before inserting a deployment version and enqueuing work. That allows cross-workspace writes if a caller can guess a deployment ID from another workspace. Add a lookup on schema.deployment scoped by (workspaceId, deploymentId) and return 404 when not found before proceeding.

Suggested change
const deployment = await db
.select({ id: schema.deployment.id })
.from(schema.deployment)
.where(
and(
eq(schema.deployment.workspaceId, workspaceId),
eq(schema.deployment.id, deploymentId),
),
)
.then(takeFirst);
if (!deployment)
throw new ApiError(`Deployment ${deploymentId} not found`, 404);

Copilot uses AI. Check for mistakes.
await assertDeploymentExistsInWorkspace(workspaceId, deploymentId);

const dependencyEntries = Object.entries(dependencies ?? {});
validateDependencyEntries(dependencyEntries, deploymentId);

const dependencyDeploymentIds = dependencyEntries.map(([id]) => id);

const data = {
...body,
name: body.name === "" ? body.tag : body.name,
config: body.config ?? {},
jobAgentConfig: body.jobAgentConfig ?? {},
metadata: body.metadata ?? {},
...versionFields,
name: versionFields.name === "" ? versionFields.tag : versionFields.name,
config: versionFields.config ?? {},
jobAgentConfig: versionFields.jobAgentConfig ?? {},
metadata: versionFields.metadata ?? {},
deploymentId,
createdAt: new Date(),
id: uuidv4(),
};

const version = await db.transaction(async (tx) => {
const version = await tx
.insert(schema.deploymentVersion)
.values(data)
.onConflictDoNothing()
.returning()
.then(takeFirst);
await assertDependencyDeploymentsExistInWorkspace(
tx,
workspaceId,
dependencyDeploymentIds,
);

const inserted = await insertDeploymentVersionOrThrowConflict(tx, data);

if (dependencyEntries.length > 0) {
await tx.insert(schema.deploymentVersionDependency).values(
dependencyEntries.map(([dependencyDeploymentId, edge]) => ({
deploymentVersionId: inserted.id,
dependencyDeploymentId,
versionSelector: edge.versionSelector,
})),
);
}

return version;
return inserted;
});

enqueueReleaseTargetsForDeployment(db, workspaceId, deploymentId);
Expand Down
20 changes: 18 additions & 2 deletions apps/api/src/types/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1154,6 +1154,13 @@ export interface components {
};
/** Format: date-time */
createdAt?: string;
/** @description Map of dependency deployment ID to a CEL version selector evaluated against that deployment's current release on the same resource. Inserted atomically with the version so reconciliation cannot fire before edges are attached. */
dependencies?: {
[key: string]: {
/** @description CEL expression evaluated against the dependency deployment's current release version on the same resource. */
versionSelector: string;
};
};
jobAgentConfig?: {
[key: string]: unknown;
};
Expand Down Expand Up @@ -3644,8 +3651,8 @@ export interface operations {
};
};
responses: {
/** @description Accepted response */
202: {
/** @description Deployment version created */
200: {
headers: {
[name: string]: unknown;
};
Expand All @@ -3662,6 +3669,15 @@ export interface operations {
"application/json": components["schemas"]["ErrorResponse"];
};
};
/** @description Resource not found */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ErrorResponse"];
};
};
};
};
requestDeploymentVersionUpdate: {
Expand Down
Loading
Loading