-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathresumeBatchRun.server.ts
More file actions
372 lines (329 loc) · 11.1 KB
/
resumeBatchRun.server.ts
File metadata and controls
372 lines (329 loc) · 11.1 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import { PrismaClientOrTransaction } from "~/db.server";
import { workerQueue } from "~/services/worker.server";
import { marqs, MarQSPriorityLevel } from "~/v3/marqs/index.server";
import { BaseService } from "./baseService.server";
import { logger } from "~/services/logger.server";
import { BatchTaskRun } from "@trigger.dev/database";
const finishedBatchRunStatuses = ["COMPLETED", "FAILED", "CANCELED"];
type RetrieveBatchRunResult = NonNullable<Awaited<ReturnType<typeof retrieveBatchRun>>>;
export class ResumeBatchRunService extends BaseService {
public async call(batchRunId: string) {
const batchRun = await this._prisma.batchTaskRun.findFirst({
where: {
id: batchRunId,
},
include: {
runtimeEnvironment: {
include: {
project: true,
organization: true,
},
},
items: {
select: {
status: true,
taskRunAttemptId: true,
},
},
},
});
if (!batchRun) {
logger.error(
"ResumeBatchRunService: Batch run doesn't exist or doesn't have a dependent attempt",
{
batchRunId,
}
);
return "ERROR";
}
if (batchRun.batchVersion === "v3") {
return await this.#handleV3BatchRun(batchRun);
} else {
return await this.#handleLegacyBatchRun(batchRun);
}
}
async #handleV3BatchRun(batchRun: RetrieveBatchRunResult) {
// V3 batch runs should already be complete by the time this is called
if (batchRun.status !== "COMPLETED") {
logger.debug("ResumeBatchRunService: Batch run is already completed", {
batchRunId: batchRun.id,
batchRun: {
id: batchRun.id,
status: batchRun.status,
},
});
return "ERROR";
}
// Even though we are in v3, we still need to check if the batch run has a dependent attempt
if (!batchRun.dependentTaskAttemptId) {
logger.debug("ResumeBatchRunService: Batch run doesn't have a dependent attempt", {
batchRunId: batchRun.id,
});
return "ERROR";
}
return await this.#handleDependentTaskAttempt(batchRun, batchRun.dependentTaskAttemptId);
}
async #handleLegacyBatchRun(batchRun: RetrieveBatchRunResult) {
if (batchRun.status === "COMPLETED") {
logger.debug("ResumeBatchRunService: Batch run is already completed", {
batchRunId: batchRun.id,
batchRun: {
id: batchRun.id,
status: batchRun.status,
},
});
return "ERROR";
}
if (batchRun.batchVersion === "v2") {
// Make sure batchRun.items.length is equal to or greater than batchRun.runCount
if (batchRun.items.length < batchRun.runCount) {
logger.debug("ResumeBatchRunService: All items aren't yet completed [v2]", {
batchRunId: batchRun.id,
batchRun: {
id: batchRun.id,
status: batchRun.status,
itemsLength: batchRun.items.length,
runCount: batchRun.runCount,
},
});
return "PENDING";
}
}
if (batchRun.items.some((item) => !finishedBatchRunStatuses.includes(item.status))) {
logger.debug("ResumeBatchRunService: All items aren't yet completed [v1]", {
batchRunId: batchRun.id,
batchRun: {
id: batchRun.id,
status: batchRun.status,
},
});
return "PENDING";
}
// If we are in development, or there is no dependent attempt, we can just mark the batch as completed and return
if (batchRun.runtimeEnvironment.type === "DEVELOPMENT" || !batchRun.dependentTaskAttemptId) {
// We need to update the batchRun status so we don't resume it again
await this._prisma.batchTaskRun.update({
where: {
id: batchRun.id,
},
data: {
status: "COMPLETED",
},
});
return "COMPLETED";
}
return await this.#handleDependentTaskAttempt(batchRun, batchRun.dependentTaskAttemptId);
}
async #handleDependentTaskAttempt(
batchRun: RetrieveBatchRunResult,
dependentTaskAttemptId: string
) {
const dependentTaskAttempt = await this._prisma.taskRunAttempt.findFirst({
where: {
id: dependentTaskAttemptId,
},
select: {
status: true,
id: true,
taskRun: {
select: {
id: true,
queue: true,
taskIdentifier: true,
concurrencyKey: true,
createdAt: true,
queueTimestamp: true,
},
},
},
});
if (!dependentTaskAttempt) {
logger.error("ResumeBatchRunService: Dependent attempt not found", {
batchRunId: batchRun.id,
dependentTaskAttemptId: batchRun.dependentTaskAttemptId,
});
return "ERROR";
}
// This batch has a dependent attempt and just finalized, we should resume that attempt
const environment = batchRun.runtimeEnvironment;
const dependentRun = dependentTaskAttempt.taskRun;
if (dependentTaskAttempt.status === "PAUSED" && batchRun.checkpointEventId) {
logger.debug("ResumeBatchRunService: Attempt is paused and has a checkpoint event", {
batchRunId: batchRun.id,
dependentTaskAttempt: dependentTaskAttempt,
checkpointEventId: batchRun.checkpointEventId,
});
// We need to update the batchRun status so we don't resume it again
const wasUpdated = await this.#setBatchToResumedOnce(batchRun);
if (wasUpdated) {
logger.debug("ResumeBatchRunService: Resuming dependent run with checkpoint", {
batchRunId: batchRun.id,
dependentTaskAttemptId: dependentTaskAttempt.id,
});
// TODO: use the new priority queue thingie
await marqs?.enqueueMessage(
environment,
dependentRun.queue,
dependentRun.id,
{
type: "RESUME",
completedAttemptIds: [],
resumableAttemptId: dependentTaskAttempt.id,
checkpointEventId: batchRun.checkpointEventId,
taskIdentifier: dependentTaskAttempt.taskRun.taskIdentifier,
projectId: environment.projectId,
environmentId: environment.id,
environmentType: environment.type,
},
dependentRun.concurrencyKey ?? undefined,
dependentRun.queueTimestamp ?? dependentRun.createdAt,
undefined,
MarQSPriorityLevel.resume
);
return "COMPLETED";
} else {
logger.debug("ResumeBatchRunService: with checkpoint was already completed", {
batchRunId: batchRun.id,
dependentTaskAttempt: dependentTaskAttempt,
checkpointEventId: batchRun.checkpointEventId,
hasCheckpointEvent: !!batchRun.checkpointEventId,
});
return "ALREADY_COMPLETED";
}
} else {
logger.debug("ResumeBatchRunService: attempt is not paused or there's no checkpoint event", {
batchRunId: batchRun.id,
dependentTaskAttempt: dependentTaskAttempt,
checkpointEventId: batchRun.checkpointEventId,
hasCheckpointEvent: !!batchRun.checkpointEventId,
});
if (dependentTaskAttempt.status === "PAUSED" && !batchRun.checkpointEventId) {
// In case of race conditions the status can be PAUSED without a checkpoint event
// When the checkpoint is created, it will continue the run
logger.error("ResumeBatchRunService: attempt is paused but there's no checkpoint event", {
batchRunId: batchRun.id,
dependentTaskAttempt: dependentTaskAttempt,
checkpointEventId: batchRun.checkpointEventId,
hasCheckpointEvent: !!batchRun.checkpointEventId,
});
return "ERROR";
}
// We need to update the batchRun status so we don't resume it again
const wasUpdated = await this.#setBatchToResumedOnce(batchRun);
if (wasUpdated) {
logger.debug("ResumeBatchRunService: Resuming dependent run without checkpoint", {
batchRunId: batchRun.id,
dependentTaskAttempt: dependentTaskAttempt,
checkpointEventId: batchRun.checkpointEventId,
hasCheckpointEvent: !!batchRun.checkpointEventId,
});
await marqs?.requeueMessage(
dependentRun.id,
{
type: "RESUME",
completedAttemptIds: batchRun.items
.map((item) => item.taskRunAttemptId)
.filter(Boolean),
resumableAttemptId: dependentTaskAttempt.id,
checkpointEventId: batchRun.checkpointEventId ?? undefined,
taskIdentifier: dependentTaskAttempt.taskRun.taskIdentifier,
projectId: environment.projectId,
environmentId: environment.id,
environmentType: environment.type,
},
(
dependentTaskAttempt.taskRun.queueTimestamp ?? dependentTaskAttempt.taskRun.createdAt
).getTime(),
MarQSPriorityLevel.resume
);
return "COMPLETED";
} else {
logger.debug("ResumeBatchRunService: without checkpoint was already completed", {
batchRunId: batchRun.id,
dependentTaskAttempt: dependentTaskAttempt,
checkpointEventId: batchRun.checkpointEventId,
hasCheckpointEvent: !!batchRun.checkpointEventId,
});
return "ALREADY_COMPLETED";
}
}
}
async #setBatchToResumedOnce(batchRun: BatchTaskRun) {
// v3 batches don't use the status for deciding whether a batch has been resumed
if (batchRun.batchVersion === "v3") {
const result = await this._prisma.batchTaskRun.updateMany({
where: {
id: batchRun.id,
resumedAt: null,
},
data: {
resumedAt: new Date(),
},
});
// Check if any records were updated
if (result.count > 0) {
// The status was changed, so we return true
return true;
} else {
return false;
}
}
const result = await this._prisma.batchTaskRun.updateMany({
where: {
id: batchRun.id,
status: {
not: "COMPLETED", // Ensure the status is not already "COMPLETED"
},
},
data: {
status: "COMPLETED",
},
});
// Check if any records were updated
if (result.count > 0) {
// The status was changed, so we return true
return true;
} else {
return false;
}
}
static async enqueue(
batchRunId: string,
skipJobKey: boolean,
tx: PrismaClientOrTransaction,
runAt?: Date
) {
return await workerQueue.enqueue(
"v3.resumeBatchRun",
{
batchRunId,
},
{
tx,
runAt,
jobKey: skipJobKey ? undefined : `resumeBatchRun-${batchRunId}`,
}
);
}
}
async function retrieveBatchRun(id: string, prisma: PrismaClientOrTransaction) {
return await prisma.batchTaskRun.findFirst({
where: {
id,
},
include: {
runtimeEnvironment: {
include: {
project: true,
organization: true,
},
},
items: {
select: {
status: true,
taskRunAttemptId: true,
},
},
},
});
}