-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathdeployment.server.ts
More file actions
323 lines (301 loc) · 10.7 KB
/
deployment.server.ts
File metadata and controls
323 lines (301 loc) · 10.7 KB
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import { type AuthenticatedEnvironment } from "~/services/apiAuth.server";
import { BaseService } from "./baseService.server";
import { errAsync, fromPromise, okAsync } from "neverthrow";
import { type WorkerDeployment } from "@trigger.dev/database";
import { logger, type GitMeta } from "@trigger.dev/core/v3";
import { TimeoutDeploymentService } from "./timeoutDeployment.server";
import { env } from "~/env.server";
import { createRemoteImageBuild } from "../remoteImageBuilder.server";
import { FINAL_DEPLOYMENT_STATUSES } from "./failDeployment.server";
import { generateRegistryCredentials } from "~/services/platform.v3.server";
export class DeploymentService extends BaseService {
/**
* Progresses a deployment from PENDING to INSTALLING and then to BUILDING.
* Also extends the deployment timeout.
*
* When progressing to BUILDING, the remote Depot build is also created.
*
* Only acts when the current status allows. Not idempotent.
*
* @param authenticatedEnv The environment which the deployment belongs to.
* @param friendlyId The friendly deployment ID.
* @param updates Optional deployment details to persist.
*/
public progressDeployment(
authenticatedEnv: AuthenticatedEnvironment,
friendlyId: string,
updates: Partial<Pick<WorkerDeployment, "contentHash" | "runtime"> & { git: GitMeta }>
) {
const getDeployment = () =>
fromPromise(
this._prisma.workerDeployment.findFirst({
where: {
friendlyId,
environmentId: authenticatedEnv.id,
},
select: {
status: true,
id: true,
},
}),
(error) => ({
type: "other" as const,
cause: error,
})
).andThen((deployment) => {
if (!deployment) {
return errAsync({ type: "deployment_not_found" as const });
}
return okAsync(deployment);
});
const validateDeployment = (deployment: Pick<WorkerDeployment, "id" | "status">) => {
if (deployment.status !== "PENDING" && deployment.status !== "INSTALLING") {
logger.warn(
"Attempted progressing deployment that is not in PENDING or INSTALLING status",
{
deployment,
}
);
return errAsync({ type: "deployment_cannot_be_progressed" as const });
}
return okAsync(deployment);
};
const progressToInstalling = (deployment: Pick<WorkerDeployment, "id">) =>
fromPromise(
this._prisma.workerDeployment.updateMany({
where: { id: deployment.id, status: "PENDING" }, // status could've changed in the meantime, we're not locking the row
data: {
...updates,
status: "INSTALLING",
startedAt: new Date(),
},
}),
(error) => ({
type: "other" as const,
cause: error,
})
).andThen((result) => {
if (result.count === 0) {
return errAsync({ type: "deployment_cannot_be_progressed" as const });
}
return okAsync({ id: deployment.id, status: "INSTALLING" as const });
});
const createRemoteBuild = (deployment: Pick<WorkerDeployment, "id">) =>
fromPromise(createRemoteImageBuild(authenticatedEnv.project), (error) => ({
type: "failed_to_create_remote_build" as const,
cause: error,
}));
const progressToBuilding = (deployment: Pick<WorkerDeployment, "id">) =>
createRemoteBuild(deployment)
.andThen((externalBuildData) =>
fromPromise(
this._prisma.workerDeployment.updateMany({
where: { id: deployment.id, status: "INSTALLING" }, // status could've changed in the meantime, we're not locking the row
data: {
...updates,
externalBuildData,
status: "BUILDING",
installedAt: new Date(),
},
}),
(error) => ({
type: "other" as const,
cause: error,
})
)
)
.andThen((result) => {
if (result.count === 0) {
return errAsync({ type: "deployment_cannot_be_progressed" as const });
}
return okAsync({ id: deployment.id, status: "BUILDING" as const });
});
const extendTimeout = (deployment: Pick<WorkerDeployment, "id" | "status">) =>
fromPromise(
TimeoutDeploymentService.enqueue(
deployment.id,
deployment.status,
deployment.status === "INSTALLING"
? "Installing dependencies timed out"
: "Building timed out",
new Date(Date.now() + env.DEPLOY_TIMEOUT_MS)
),
(error) => ({
type: "failed_to_extend_deployment_timeout" as const,
cause: error,
})
);
return getDeployment()
.andThen(validateDeployment)
.andThen((deployment) => {
if (deployment.status === "PENDING") {
return progressToInstalling(deployment);
}
return progressToBuilding(deployment);
})
.andThen(extendTimeout)
.map(() => undefined);
}
/**
* Cancels a deployment that is not yet in a final state.
*
* Only acts when the current status is not final. Not idempotent.
*
* @param authenticatedEnv The environment which the deployment belongs to.
* @param friendlyId The friendly deployment ID.
* @param data Cancelation reason.
*/
public cancelDeployment(
authenticatedEnv: Pick<AuthenticatedEnvironment, "projectId">,
friendlyId: string,
data?: Partial<Pick<WorkerDeployment, "canceledReason">>
) {
const getDeployment = () =>
fromPromise(
this._prisma.workerDeployment.findFirst({
where: {
friendlyId,
projectId: authenticatedEnv.projectId,
},
select: {
status: true,
id: true,
},
}),
(error) => ({
type: "other" as const,
cause: error,
})
).andThen((deployment) => {
if (!deployment) {
return errAsync({ type: "deployment_not_found" as const });
}
return okAsync(deployment);
});
const validateDeployment = (deployment: Pick<WorkerDeployment, "id" | "status">) => {
if (FINAL_DEPLOYMENT_STATUSES.includes(deployment.status)) {
logger.warn("Attempted cancelling deployment in a final state", {
deployment,
});
return errAsync({ type: "deployment_cannot_be_cancelled" as const });
}
return okAsync(deployment);
};
const cancelDeployment = (deployment: Pick<WorkerDeployment, "id">) =>
fromPromise(
this._prisma.workerDeployment.updateMany({
where: {
id: deployment.id,
status: {
notIn: FINAL_DEPLOYMENT_STATUSES, // status could've changed in the meantime, we're not locking the row
},
},
data: {
status: "CANCELED",
canceledAt: new Date(),
canceledReason: data?.canceledReason,
},
}),
(error) => ({
type: "other" as const,
cause: error,
})
).andThen((result) => {
if (result.count === 0) {
return errAsync({ type: "deployment_cannot_be_cancelled" as const });
}
return okAsync({ id: deployment.id });
});
const deleteTimeout = (deployment: Pick<WorkerDeployment, "id">) =>
fromPromise(TimeoutDeploymentService.dequeue(deployment.id, this._prisma), (error) => ({
type: "failed_to_delete_deployment_timeout" as const,
cause: error,
}));
return getDeployment()
.andThen(validateDeployment)
.andThen(cancelDeployment)
.andThen(deleteTimeout)
.map(() => undefined);
}
/**
* Generates registry credentials for a deployment. Returns an error if the deployment is in a final state.
*
* Uses the `platform` package, only available in cloud.
*
* @param authenticatedEnv The environment which the deployment belongs to.
* @param friendlyId The friendly deployment ID.
*/
public generateRegistryCredentials(
authenticatedEnv: Pick<AuthenticatedEnvironment, "projectId">,
friendlyId: string
) {
const validateDeployment = (
deployment: Pick<WorkerDeployment, "id" | "status" | "imageReference">
) => {
if (FINAL_DEPLOYMENT_STATUSES.includes(deployment.status)) {
return errAsync({ type: "deployment_is_already_final" as const });
}
return okAsync(deployment);
};
const getDeploymentRegion = (deployment: Pick<WorkerDeployment, "imageReference">) => {
if (!deployment.imageReference) {
return errAsync({ type: "deployment_has_no_image_reference" as const });
}
if (!deployment.imageReference.includes("amazonaws.com")) {
return errAsync({ type: "registry_not_supported" as const });
}
// we should connect the deployment to a region more explicitly in the future
// for now we just use the image reference to determine the region
if (deployment.imageReference.includes("us-east-1")) {
return okAsync({ region: "us-east-1" as const });
}
if (deployment.imageReference.includes("eu-central-1")) {
return okAsync({ region: "eu-central-1" as const });
}
return errAsync({ type: "registry_region_not_supported" as const });
};
const generateCredentials = ({ region }: { region: "us-east-1" | "eu-central-1" }) =>
fromPromise(generateRegistryCredentials(authenticatedEnv.projectId, region), (error) => ({
type: "other" as const,
cause: error,
})).andThen((result) => {
if (!result || !result.success) {
return errAsync({ type: "missing_registry_credentials" as const });
}
return okAsync({
username: result.username,
password: result.password,
expiresAt: new Date(result.expiresAt),
repositoryUri: result.repositoryUri,
});
});
return this.getDeployment(authenticatedEnv.projectId, friendlyId)
.andThen(validateDeployment)
.andThen(getDeploymentRegion)
.andThen(generateCredentials);
}
private getDeployment(projectId: string, friendlyId: string) {
return fromPromise(
this._prisma.workerDeployment.findFirst({
where: {
friendlyId,
projectId,
},
select: {
status: true,
id: true,
imageReference: true,
},
}),
(error) => ({
type: "other" as const,
cause: error,
})
).andThen((deployment) => {
if (!deployment) {
return errAsync({ type: "deployment_not_found" as const });
}
return okAsync(deployment);
});
}
}