-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathroute.ts
150 lines (138 loc) · 4.51 KB
/
route.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import { NextResponse } from "next/server";
import httpStatus from "http-status";
import { z } from "zod";
import {
and,
buildConflictUpdateColumns,
eq,
takeFirst,
takeFirstOrNull,
} from "@ctrlplane/db";
import { db } from "@ctrlplane/db/client";
import * as schema from "@ctrlplane/db/schema";
import {
cancelOldReleaseJobTriggersOnJobDispatch,
createJobApprovals,
createReleaseJobTriggers,
dispatchReleaseJobTriggers,
isPassingAllPolicies,
isPassingChannelSelectorPolicy,
} from "@ctrlplane/job-dispatch";
import { logger } from "@ctrlplane/logger";
import { Permission } from "@ctrlplane/validators/auth";
import { DeploymentVersionStatus } from "@ctrlplane/validators/releases";
import { authn, authz } from "~/app/api/v1/auth";
import { parseBody } from "~/app/api/v1/body-parser";
import { request } from "~/app/api/v1/middleware";
const bodySchema = schema.createDeploymentVersion.and(
z.object({
metadata: z.record(z.string()).optional(),
status: z.nativeEnum(DeploymentVersionStatus).optional(),
}),
);
export const POST = request()
.use(authn)
.use(parseBody(bodySchema))
.use(
authz(({ ctx, can }) =>
can
.perform(Permission.DeploymentVersionCreate)
.on({ type: "deployment", id: ctx.body.deploymentId }),
),
)
.handle<{ user: schema.User; body: z.infer<typeof bodySchema> }>(
async (ctx) => {
const { req, body } = ctx;
const { name, tag, metadata = {} } = body;
const versionName = name ?? tag;
try {
const prevVersion = await db
.select()
.from(schema.deploymentVersion)
.where(
and(
eq(schema.deploymentVersion.deploymentId, body.deploymentId),
eq(schema.deploymentVersion.tag, tag),
),
)
.then(takeFirstOrNull);
const depVersion = await db
.insert(schema.deploymentVersion)
.values({ ...body, name: versionName, tag })
.onConflictDoUpdate({
target: [
schema.deploymentVersion.deploymentId,
schema.deploymentVersion.tag,
],
set: buildConflictUpdateColumns(schema.deploymentVersion, [
"name",
"status",
"message",
"config",
"jobAgentConfig",
]),
})
.returning()
.then(takeFirst);
if (Object.keys(metadata).length > 0)
await db
.insert(schema.deploymentVersionMetadata)
.values(
Object.entries(metadata).map(([key, value]) => ({
versionId: depVersion.id,
key,
value,
})),
)
.onConflictDoUpdate({
target: [
schema.deploymentVersionMetadata.versionId,
schema.deploymentVersionMetadata.key,
],
set: buildConflictUpdateColumns(
schema.deploymentVersionMetadata,
["value"],
),
});
const shouldTrigger =
prevVersion == null ||
(prevVersion.status !== DeploymentVersionStatus.Ready &&
depVersion.status === DeploymentVersionStatus.Ready);
if (shouldTrigger)
await createReleaseJobTriggers(db, "new_version")
.causedById(ctx.user.id)
.filter(isPassingChannelSelectorPolicy)
.versions([depVersion.id])
.then(createJobApprovals)
.insert()
.then((releaseJobTriggers) => {
dispatchReleaseJobTriggers(db)
.releaseTriggers(releaseJobTriggers)
.filter(isPassingAllPolicies)
.then(cancelOldReleaseJobTriggersOnJobDispatch)
.dispatch();
})
.then(() =>
logger.info(
`Jobs for deployment version ${depVersion.id} created and dispatched.`,
req,
),
);
return NextResponse.json(
{ ...depVersion, metadata },
{ status: httpStatus.CREATED },
);
} catch (error) {
if (error instanceof z.ZodError)
return NextResponse.json(
{ error: error.errors },
{ status: httpStatus.BAD_REQUEST },
);
logger.error("Error creating deployment version:", error);
return NextResponse.json(
{ error: "Internal Server Error" },
{ status: httpStatus.INTERNAL_SERVER_ERROR },
);
}
},
);