-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathbatchTrigger.server.ts
More file actions
696 lines (617 loc) · 21.4 KB
/
batchTrigger.server.ts
File metadata and controls
696 lines (617 loc) · 21.4 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
import {
BatchTriggerTaskV2RequestBody,
BatchTriggerTaskV3RequestBody,
BatchTriggerTaskV3Response,
IOPacket,
packetRequiresOffloading,
parsePacket,
} from "@trigger.dev/core/v3";
import { BatchId, RunId } from "@trigger.dev/core/v3/isomorphic";
import { BatchTaskRun, Prisma } from "@trigger.dev/database";
import { z } from "zod";
import { $transaction, prisma, PrismaClientOrTransaction } from "~/db.server";
import { env } from "~/env.server";
import { AuthenticatedEnvironment } from "~/services/apiAuth.server";
import { logger } from "~/services/logger.server";
import { getEntitlement } from "~/services/platform.v3.server";
import { workerQueue } from "~/services/worker.server";
import { downloadPacketFromObjectStore, uploadPacketToObjectStore } from "../../v3/r2.server";
import { ServiceValidationError, WithRunEngine } from "../../v3/services/baseService.server";
import { OutOfEntitlementError, TriggerTaskService } from "../../v3/services/triggerTask.server";
import { startActiveSpan } from "../../v3/tracer.server";
const PROCESSING_BATCH_SIZE = 50;
const ASYNC_BATCH_PROCESS_SIZE_THRESHOLD = 20;
const MAX_ATTEMPTS = 10;
export const BatchProcessingStrategy = z.enum(["sequential", "parallel"]);
export type BatchProcessingStrategy = z.infer<typeof BatchProcessingStrategy>;
export const BatchProcessingOptions = z.object({
batchId: z.string(),
processingId: z.string(),
range: z.object({ start: z.number().int(), count: z.number().int() }),
attemptCount: z.number().int(),
strategy: BatchProcessingStrategy,
parentRunId: z.string().optional(),
resumeParentOnCompletion: z.boolean().optional(),
});
export type BatchProcessingOptions = z.infer<typeof BatchProcessingOptions>;
export type BatchTriggerTaskServiceOptions = {
triggerVersion?: string;
traceContext?: Record<string, string | undefined>;
spanParentAsLink?: boolean;
oneTimeUseToken?: string;
};
/**
* Larger batches, used in Run Engine v2
*/
export class RunEngineBatchTriggerService extends WithRunEngine {
private _batchProcessingStrategy: BatchProcessingStrategy;
constructor(
batchProcessingStrategy?: BatchProcessingStrategy,
protected readonly _prisma: PrismaClientOrTransaction = prisma
) {
super({ prisma });
// Eric note: We need to force sequential processing because when doing parallel, we end up with high-contention on the parent run lock
// becuase we are triggering a lot of runs at once, and each one is trying to lock the parent run.
// by forcing sequential, we are only ever locking the parent run for a single run at a time.
this._batchProcessingStrategy = "sequential";
}
public async call(
environment: AuthenticatedEnvironment,
body: BatchTriggerTaskV3RequestBody,
options: BatchTriggerTaskServiceOptions = {}
): Promise<BatchTriggerTaskV3Response> {
try {
return await this.traceWithEnv<BatchTriggerTaskV3Response>(
"call()",
environment,
async (span) => {
const { id, friendlyId } = BatchId.generate();
span.setAttribute("batchId", friendlyId);
if (environment.type !== "DEVELOPMENT") {
const result = await getEntitlement(environment.organizationId);
if (result && result.hasAccess === false) {
throw new OutOfEntitlementError();
}
}
// Upload to object store
const payloadPacket = await this.#handlePayloadPacket(
body.items,
`batch/${friendlyId}`,
environment
);
const batch = await this.#createAndProcessBatchTaskRun(
friendlyId,
payloadPacket,
environment,
body,
options
);
if (!batch) {
throw new Error("Failed to create batch");
}
return {
id: batch.friendlyId,
isCached: false,
idempotencyKey: batch.idempotencyKey ?? undefined,
runCount: body.items.length,
};
}
);
} catch (error) {
// Detect a prisma transaction Unique constraint violation
if (error instanceof Prisma.PrismaClientKnownRequestError) {
logger.debug("RunEngineBatchTrigger: Prisma transaction error", {
code: error.code,
message: error.message,
meta: error.meta,
});
if (error.code === "P2002") {
const target = error.meta?.target;
if (
Array.isArray(target) &&
target.length > 0 &&
typeof target[0] === "string" &&
target[0].includes("oneTimeUseToken")
) {
throw new ServiceValidationError(
"Cannot batch trigger with a one-time use token as it has already been used."
);
} else {
throw new ServiceValidationError(
"Cannot batch trigger as it has already been triggered with the same idempotency key."
);
}
}
}
throw error;
}
}
async #createAndProcessBatchTaskRun(
batchId: string,
payloadPacket: IOPacket,
environment: AuthenticatedEnvironment,
body: BatchTriggerTaskV2RequestBody,
options: BatchTriggerTaskServiceOptions = {}
) {
if (body.items.length <= ASYNC_BATCH_PROCESS_SIZE_THRESHOLD) {
const batch = await this._prisma.batchTaskRun.create({
data: {
id: BatchId.fromFriendlyId(batchId),
friendlyId: batchId,
runtimeEnvironmentId: environment.id,
runCount: body.items.length,
runIds: [],
payload: payloadPacket.data,
payloadType: payloadPacket.dataType,
options,
batchVersion: "runengine:v1",
oneTimeUseToken: options.oneTimeUseToken,
},
});
if (body.parentRunId && body.resumeParentOnCompletion) {
await this._engine.blockRunWithCreatedBatch({
runId: RunId.fromFriendlyId(body.parentRunId),
batchId: batch.id,
environmentId: environment.id,
projectId: environment.projectId,
organizationId: environment.organizationId,
});
}
const result = await this.#processBatchTaskRunItems({
batch,
environment,
currentIndex: 0,
batchSize: PROCESSING_BATCH_SIZE,
items: body.items,
options,
parentRunId: body.parentRunId,
resumeParentOnCompletion: body.resumeParentOnCompletion,
});
switch (result.status) {
case "COMPLETE": {
logger.debug("[RunEngineBatchTrigger][call] Batch inline processing complete", {
batchId: batch.friendlyId,
currentIndex: 0,
});
return batch;
}
case "INCOMPLETE": {
logger.debug("[RunEngineBatchTrigger][call] Batch inline processing incomplete", {
batchId: batch.friendlyId,
currentIndex: result.workingIndex,
});
// If processing inline does not finish for some reason, enqueue processing the rest of the batch
await this.#enqueueBatchTaskRun({
batchId: batch.id,
processingId: "0",
range: {
start: result.workingIndex,
count: PROCESSING_BATCH_SIZE,
},
attemptCount: 0,
strategy: "sequential",
parentRunId: body.parentRunId,
resumeParentOnCompletion: body.resumeParentOnCompletion,
});
return batch;
}
case "ERROR": {
logger.error("[RunEngineBatchTrigger][call] Batch inline processing error", {
batchId: batch.friendlyId,
currentIndex: result.workingIndex,
error: result.error,
});
await this.#enqueueBatchTaskRun({
batchId: batch.id,
processingId: "0",
range: {
start: result.workingIndex,
count: PROCESSING_BATCH_SIZE,
},
attemptCount: 0,
strategy: "sequential",
parentRunId: body.parentRunId,
resumeParentOnCompletion: body.resumeParentOnCompletion,
});
return batch;
}
}
} else {
return await $transaction(this._prisma, async (tx) => {
const batch = await tx.batchTaskRun.create({
data: {
id: BatchId.fromFriendlyId(batchId),
friendlyId: batchId,
runtimeEnvironmentId: environment.id,
runCount: body.items.length,
runIds: [],
payload: payloadPacket.data,
payloadType: payloadPacket.dataType,
options,
batchVersion: "runengine:v1",
oneTimeUseToken: options.oneTimeUseToken,
},
});
if (body.parentRunId && body.resumeParentOnCompletion) {
await this._engine.blockRunWithCreatedBatch({
runId: RunId.fromFriendlyId(body.parentRunId),
batchId: batch.id,
environmentId: environment.id,
projectId: environment.projectId,
organizationId: environment.organizationId,
tx,
});
}
switch (this._batchProcessingStrategy) {
case "sequential": {
await this.#enqueueBatchTaskRun(
{
batchId: batch.id,
processingId: batchId,
range: { start: 0, count: PROCESSING_BATCH_SIZE },
attemptCount: 0,
strategy: this._batchProcessingStrategy,
parentRunId: body.parentRunId,
resumeParentOnCompletion: body.resumeParentOnCompletion,
},
tx
);
break;
}
case "parallel": {
const ranges = Array.from({
length: Math.ceil(body.items.length / PROCESSING_BATCH_SIZE),
}).map((_, index) => ({
start: index * PROCESSING_BATCH_SIZE,
count: PROCESSING_BATCH_SIZE,
}));
await Promise.all(
ranges.map((range, index) =>
this.#enqueueBatchTaskRun(
{
batchId: batch.id,
processingId: `${index}`,
range,
attemptCount: 0,
strategy: this._batchProcessingStrategy,
parentRunId: body.parentRunId,
resumeParentOnCompletion: body.resumeParentOnCompletion,
},
tx
)
)
);
break;
}
}
return batch;
});
}
}
async #enqueueBatchTaskRun(options: BatchProcessingOptions, tx?: PrismaClientOrTransaction) {
await workerQueue.enqueue("runengine.processBatchTaskRun", options, {
tx,
jobKey: `RunEngineBatchTriggerService.process:${options.batchId}:${options.processingId}`,
});
}
// This is the function that the worker will call
async processBatchTaskRun(options: BatchProcessingOptions) {
logger.debug("[RunEngineBatchTrigger][processBatchTaskRun] Processing batch", {
options,
});
const $attemptCount = options.attemptCount + 1;
// Add early return if max attempts reached
if ($attemptCount > MAX_ATTEMPTS) {
logger.error("[RunEngineBatchTrigger][processBatchTaskRun] Max attempts reached", {
options,
attemptCount: $attemptCount,
});
// You might want to update the batch status to failed here
return;
}
const batch = await this._prisma.batchTaskRun.findFirst({
where: { id: options.batchId },
include: {
runtimeEnvironment: {
include: {
project: true,
organization: true,
},
},
},
});
if (!batch) {
return;
}
// Check to make sure the currentIndex is not greater than the runCount
if (options.range.start >= batch.runCount) {
logger.debug(
"[RunEngineBatchTrigger][processBatchTaskRun] currentIndex is greater than runCount",
{
options,
batchId: batch.friendlyId,
runCount: batch.runCount,
attemptCount: $attemptCount,
}
);
return;
}
// Resolve the payload
const payloadPacket = await downloadPacketFromObjectStore(
{
data: batch.payload ?? undefined,
dataType: batch.payloadType,
},
batch.runtimeEnvironment
);
const payload = await parsePacket(payloadPacket);
if (!payload) {
logger.debug("[RunEngineBatchTrigger][processBatchTaskRun] Failed to parse payload", {
options,
batchId: batch.friendlyId,
attemptCount: $attemptCount,
});
throw new Error("Failed to parse payload");
}
// Skip zod parsing
const $payload = payload as BatchTriggerTaskV2RequestBody["items"];
const $options = batch.options as BatchTriggerTaskServiceOptions;
const result = await this.#processBatchTaskRunItems({
batch,
environment: batch.runtimeEnvironment,
currentIndex: options.range.start,
batchSize: options.range.count,
items: $payload,
options: $options,
parentRunId: options.parentRunId,
resumeParentOnCompletion: options.resumeParentOnCompletion,
});
switch (result.status) {
case "COMPLETE": {
logger.debug("[RunEngineBatchTrigger][processBatchTaskRun] Batch processing complete", {
options,
batchId: batch.friendlyId,
attemptCount: $attemptCount,
});
return;
}
case "INCOMPLETE": {
logger.debug("[RunEngineBatchTrigger][processBatchTaskRun] Batch processing incomplete", {
batchId: batch.friendlyId,
currentIndex: result.workingIndex,
attemptCount: $attemptCount,
});
// Only enqueue the next batch task run if the strategy is sequential
// if the strategy is parallel, we will already have enqueued the next batch task run
if (options.strategy === "sequential") {
await this.#enqueueBatchTaskRun({
batchId: batch.id,
processingId: options.processingId,
range: {
start: result.workingIndex,
count: options.range.count,
},
attemptCount: 0,
strategy: options.strategy,
parentRunId: options.parentRunId,
resumeParentOnCompletion: options.resumeParentOnCompletion,
});
}
return;
}
case "ERROR": {
logger.error("[RunEngineBatchTrigger][processBatchTaskRun] Batch processing error", {
batchId: batch.friendlyId,
currentIndex: result.workingIndex,
error: result.error,
attemptCount: $attemptCount,
});
// if the strategy is sequential, we will requeue processing with a count of the PROCESSING_BATCH_SIZE
// if the strategy is parallel, we will requeue processing with a range starting at the workingIndex and a count that is the remainder of this "slice" of the batch
if (options.strategy === "sequential") {
await this.#enqueueBatchTaskRun({
batchId: batch.id,
processingId: options.processingId,
range: {
start: result.workingIndex,
count: options.range.count, // This will be the same as the original count
},
attemptCount: $attemptCount,
strategy: options.strategy,
parentRunId: options.parentRunId,
resumeParentOnCompletion: options.resumeParentOnCompletion,
});
} else {
await this.#enqueueBatchTaskRun({
batchId: batch.id,
processingId: options.processingId,
range: {
start: result.workingIndex,
// This will be the remainder of the slice
// for example if the original range was 0-50 and the workingIndex is 25, the new range will be 25-25
// if the original range was 51-100 and the workingIndex is 75, the new range will be 75-25
count: options.range.count - result.workingIndex - options.range.start,
},
attemptCount: $attemptCount,
strategy: options.strategy,
parentRunId: options.parentRunId,
resumeParentOnCompletion: options.resumeParentOnCompletion,
});
}
return;
}
}
}
async #processBatchTaskRunItems({
batch,
environment,
currentIndex,
batchSize,
items,
options,
parentRunId,
resumeParentOnCompletion,
}: {
batch: BatchTaskRun;
environment: AuthenticatedEnvironment;
currentIndex: number;
batchSize: number;
items: BatchTriggerTaskV2RequestBody["items"];
options?: BatchTriggerTaskServiceOptions;
parentRunId?: string | undefined;
resumeParentOnCompletion?: boolean | undefined;
}): Promise<
| { status: "COMPLETE" }
| { status: "INCOMPLETE"; workingIndex: number }
| { status: "ERROR"; error: string; workingIndex: number }
> {
// Grab the next PROCESSING_BATCH_SIZE items
const itemsToProcess = items.slice(currentIndex, currentIndex + batchSize);
logger.debug("[RunEngineBatchTrigger][processBatchTaskRun] Processing batch items", {
batchId: batch.friendlyId,
currentIndex,
runCount: batch.runCount,
});
let workingIndex = currentIndex;
let runIds: string[] = [];
for (const item of itemsToProcess) {
try {
const run = await this.#processBatchTaskRunItem({
batch,
environment,
item,
currentIndex: workingIndex,
options,
parentRunId,
resumeParentOnCompletion,
});
if (!run) {
logger.error("[RunEngineBatchTrigger][processBatchTaskRun] Failed to process item", {
batchId: batch.friendlyId,
currentIndex: workingIndex,
});
throw new Error("[RunEngineBatchTrigger][processBatchTaskRun] Failed to process item");
}
runIds.push(run.friendlyId);
workingIndex++;
} catch (error) {
logger.error("[RunEngineBatchTrigger][processBatchTaskRun] Failed to process item", {
batchId: batch.friendlyId,
currentIndex: workingIndex,
error,
});
return {
status: "ERROR",
error: error instanceof Error ? error.message : String(error),
workingIndex,
};
}
}
//add the run ids to the batch
const updatedBatch = await this._prisma.batchTaskRun.update({
where: { id: batch.id },
data: {
runIds: {
push: runIds,
},
processingJobsCount: {
increment: runIds.length,
},
},
select: {
processingJobsCount: true,
runCount: true,
},
});
//triggered all the runs
if (updatedBatch.processingJobsCount >= updatedBatch.runCount) {
logger.debug("[RunEngineBatchTrigger][processBatchTaskRun] All runs created", {
batchId: batch.friendlyId,
processingJobsCount: updatedBatch.processingJobsCount,
runCount: updatedBatch.runCount,
workingIndex,
});
//if all the runs were idempotent, it's possible the batch is already completed
await this._engine.tryCompleteBatch({ batchId: batch.id });
}
// if there are more items to process, requeue the batch
if (workingIndex < batch.runCount) {
return { status: "INCOMPLETE", workingIndex };
}
return { status: "COMPLETE" };
}
async #processBatchTaskRunItem({
batch,
environment,
item,
currentIndex,
options,
parentRunId,
resumeParentOnCompletion,
}: {
batch: BatchTaskRun;
environment: AuthenticatedEnvironment;
item: BatchTriggerTaskV2RequestBody["items"][number];
currentIndex: number;
options?: BatchTriggerTaskServiceOptions;
parentRunId: string | undefined;
resumeParentOnCompletion: boolean | undefined;
}) {
logger.debug("[RunEngineBatchTrigger][processBatchTaskRunItem] Processing item", {
batchId: batch.friendlyId,
currentIndex,
});
const triggerTaskService = new TriggerTaskService();
const result = await triggerTaskService.call(
item.task,
environment,
{
...item,
options: {
...item.options,
parentRunId,
resumeParentOnCompletion,
parentBatch: batch.id,
},
},
{
triggerVersion: options?.triggerVersion,
traceContext: options?.traceContext,
spanParentAsLink: options?.spanParentAsLink,
batchId: batch.id,
batchIndex: currentIndex,
},
"V2"
);
return result
? {
friendlyId: result.run.friendlyId,
}
: undefined;
}
async #handlePayloadPacket(
payload: any,
pathPrefix: string,
environment: AuthenticatedEnvironment
) {
return await startActiveSpan("handlePayloadPacket()", async (span) => {
const packet = { data: JSON.stringify(payload), dataType: "application/json" };
if (!packet.data) {
return packet;
}
const { needsOffloading } = packetRequiresOffloading(
packet,
env.TASK_PAYLOAD_OFFLOAD_THRESHOLD
);
if (!needsOffloading) {
return packet;
}
const filename = `${pathPrefix}/payload.json`;
await uploadPacketToObjectStore(filename, packet.data, packet.dataType, environment);
return {
data: filename,
dataType: "application/store",
};
});
}
}