-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathwaitpointSystem.ts
More file actions
703 lines (640 loc) · 21.1 KB
/
waitpointSystem.ts
File metadata and controls
703 lines (640 loc) · 21.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
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
697
698
699
700
701
702
703
import { timeoutError, tryCatch } from "@trigger.dev/core/v3";
import { WaitpointId } from "@trigger.dev/core/v3/isomorphic";
import {
$transaction,
Prisma,
PrismaClientOrTransaction,
TaskRunExecutionSnapshot,
TaskRunExecutionStatus,
Waitpoint,
} from "@trigger.dev/database";
import { nanoid } from "nanoid";
import { sendNotificationToWorker } from "../eventBus.js";
import { isExecuting, isFinishedOrPendingFinished } from "../statuses.js";
import { EnqueueSystem } from "./enqueueSystem.js";
import { ExecutionSnapshotSystem, getLatestExecutionSnapshot } from "./executionSnapshotSystem.js";
import { SystemResources } from "./systems.js";
import { ReleaseConcurrencySystem } from "./releaseConcurrencySystem.js";
export type WaitpointSystemOptions = {
resources: SystemResources;
executionSnapshotSystem: ExecutionSnapshotSystem;
enqueueSystem: EnqueueSystem;
releaseConcurrencySystem: ReleaseConcurrencySystem;
};
export class WaitpointSystem {
private readonly $: SystemResources;
private readonly executionSnapshotSystem: ExecutionSnapshotSystem;
private readonly releaseConcurrencySystem: ReleaseConcurrencySystem;
private readonly enqueueSystem: EnqueueSystem;
constructor(private readonly options: WaitpointSystemOptions) {
this.$ = options.resources;
this.executionSnapshotSystem = options.executionSnapshotSystem;
this.enqueueSystem = options.enqueueSystem;
this.releaseConcurrencySystem = options.releaseConcurrencySystem;
}
public async clearBlockingWaitpoints({
runId,
tx,
}: {
runId: string;
tx?: PrismaClientOrTransaction;
}) {
const prisma = tx ?? this.$.prisma;
const deleted = await prisma.taskRunWaitpoint.deleteMany({
where: {
taskRunId: runId,
},
});
return deleted.count;
}
/** This completes a waitpoint and updates all entries so the run isn't blocked,
* if they're no longer blocked. This doesn't suffer from race conditions. */
async completeWaitpoint({
id,
output,
}: {
id: string;
output?: {
value: string;
type?: string;
isError: boolean;
};
}): Promise<Waitpoint> {
// 1. Complete the Waitpoint (if not completed)
let [waitpointError, waitpoint] = await tryCatch(
this.$.prisma.waitpoint.update({
where: { id, status: "PENDING" },
data: {
status: "COMPLETED",
completedAt: new Date(),
output: output?.value,
outputType: output?.type,
outputIsError: output?.isError,
},
})
);
if (waitpointError) {
if (
waitpointError instanceof Prisma.PrismaClientKnownRequestError &&
waitpointError.code === "P2025"
) {
waitpoint = await this.$.prisma.waitpoint.findFirst({
where: { id },
});
} else {
this.$.logger.log("completeWaitpoint: error updating waitpoint:", { waitpointError });
throw waitpointError;
}
}
if (!waitpoint) {
throw new Error(`Waitpoint ${id} not found`);
}
if (waitpoint.status !== "COMPLETED") {
this.$.logger.error(`completeWaitpoint: waitpoint is not completed`, {
waitpointId: id,
});
throw new Error(`Waitpoint ${id} is not completed`);
}
// 2. Find the TaskRuns blocked by this waitpoint
const affectedTaskRuns = await this.$.prisma.taskRunWaitpoint.findMany({
where: { waitpointId: id },
select: { taskRunId: true, spanIdToComplete: true, createdAt: true },
});
if (affectedTaskRuns.length === 0) {
this.$.logger.debug(`completeWaitpoint: no TaskRunWaitpoints found for waitpoint`, {
waitpointId: id,
});
}
// 3. Schedule trying to continue the runs
for (const run of affectedTaskRuns) {
const jobId = `continueRunIfUnblocked:${run.taskRunId}`;
//50ms in the future
const availableAt = new Date(Date.now() + 50);
this.$.logger.debug(`completeWaitpoint: enqueueing continueRunIfUnblocked`, {
waitpointId: id,
runId: run.taskRunId,
jobId,
availableAt,
});
await this.$.worker.enqueue({
//this will debounce the call
id: jobId,
job: "continueRunIfUnblocked",
payload: { runId: run.taskRunId },
availableAt,
});
// emit an event to complete associated cached runs
if (run.spanIdToComplete) {
this.$.eventBus.emit("cachedRunCompleted", {
time: new Date(),
span: {
id: run.spanIdToComplete,
createdAt: run.createdAt,
},
blockedRunId: run.taskRunId,
hasError: output?.isError ?? false,
});
}
}
return waitpoint;
}
/**
* This creates a DATETIME waitpoint, that will be completed automatically when the specified date is reached.
* If you pass an `idempotencyKey`, the waitpoint will be created only if it doesn't already exist.
*/
async createDateTimeWaitpoint({
projectId,
environmentId,
completedAfter,
idempotencyKey,
idempotencyKeyExpiresAt,
tx,
}: {
projectId: string;
environmentId: string;
completedAfter: Date;
idempotencyKey?: string;
idempotencyKeyExpiresAt?: Date;
tx?: PrismaClientOrTransaction;
}) {
const prisma = tx ?? this.$.prisma;
const existingWaitpoint = idempotencyKey
? await prisma.waitpoint.findFirst({
where: {
environmentId,
idempotencyKey,
},
})
: undefined;
if (existingWaitpoint) {
if (
existingWaitpoint.idempotencyKeyExpiresAt &&
new Date() > existingWaitpoint.idempotencyKeyExpiresAt
) {
//the idempotency key has expired
//remove the waitpoint idempotencyKey
await prisma.waitpoint.update({
where: {
id: existingWaitpoint.id,
},
data: {
idempotencyKey: nanoid(24),
inactiveIdempotencyKey: existingWaitpoint.idempotencyKey,
},
});
//let it fall through to create a new waitpoint
} else {
return { waitpoint: existingWaitpoint, isCached: true };
}
}
const waitpoint = await prisma.waitpoint.upsert({
where: {
environmentId_idempotencyKey: {
environmentId,
idempotencyKey: idempotencyKey ?? nanoid(24),
},
},
create: {
...WaitpointId.generate(),
type: "DATETIME",
idempotencyKey: idempotencyKey ?? nanoid(24),
idempotencyKeyExpiresAt,
userProvidedIdempotencyKey: !!idempotencyKey,
environmentId,
projectId,
completedAfter,
},
update: {},
});
await this.$.worker.enqueue({
id: `finishWaitpoint.${waitpoint.id}`,
job: "finishWaitpoint",
payload: { waitpointId: waitpoint.id },
availableAt: completedAfter,
});
return { waitpoint, isCached: false };
}
/** This creates a MANUAL waitpoint, that can be explicitly completed (or failed).
* If you pass an `idempotencyKey` and it already exists, it will return the existing waitpoint.
*/
async createManualWaitpoint({
environmentId,
projectId,
idempotencyKey,
idempotencyKeyExpiresAt,
timeout,
tags,
}: {
environmentId: string;
projectId: string;
idempotencyKey?: string;
idempotencyKeyExpiresAt?: Date;
timeout?: Date;
tags?: string[];
}): Promise<{ waitpoint: Waitpoint; isCached: boolean }> {
const existingWaitpoint = idempotencyKey
? await this.$.prisma.waitpoint.findFirst({
where: {
environmentId,
idempotencyKey,
},
})
: undefined;
if (existingWaitpoint) {
if (
existingWaitpoint.idempotencyKeyExpiresAt &&
new Date() > existingWaitpoint.idempotencyKeyExpiresAt
) {
//the idempotency key has expired
//remove the waitpoint idempotencyKey
await this.$.prisma.waitpoint.update({
where: {
id: existingWaitpoint.id,
},
data: {
idempotencyKey: nanoid(24),
inactiveIdempotencyKey: existingWaitpoint.idempotencyKey,
},
});
//let it fall through to create a new waitpoint
} else {
return { waitpoint: existingWaitpoint, isCached: true };
}
}
const maxRetries = 5;
let attempts = 0;
while (attempts < maxRetries) {
try {
const waitpoint = await this.$.prisma.waitpoint.upsert({
where: {
environmentId_idempotencyKey: {
environmentId,
idempotencyKey: idempotencyKey ?? nanoid(24),
},
},
create: {
...WaitpointId.generate(),
type: "MANUAL",
idempotencyKey: idempotencyKey ?? nanoid(24),
idempotencyKeyExpiresAt,
userProvidedIdempotencyKey: !!idempotencyKey,
environmentId,
projectId,
completedAfter: timeout,
tags,
},
update: {},
});
//schedule the timeout
if (timeout) {
await this.$.worker.enqueue({
id: `finishWaitpoint.${waitpoint.id}`,
job: "finishWaitpoint",
payload: {
waitpointId: waitpoint.id,
error: JSON.stringify(timeoutError(timeout)),
},
availableAt: timeout,
});
}
return { waitpoint, isCached: false };
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
// Handle unique constraint violation (conflict)
attempts++;
if (attempts >= maxRetries) {
throw new Error(
`Failed to create waitpoint after ${maxRetries} attempts due to conflicts.`
);
}
} else {
throw error; // Re-throw other errors
}
}
}
throw new Error(`Failed to create waitpoint after ${maxRetries} attempts due to conflicts.`);
}
/**
* Prevents a run from continuing until the waitpoint is completed.
*/
async blockRunWithWaitpoint({
runId,
waitpoints,
projectId,
organizationId,
releaseConcurrency,
timeout,
spanIdToComplete,
batch,
workerId,
runnerId,
tx,
}: {
runId: string;
waitpoints: string | string[];
projectId: string;
organizationId: string;
releaseConcurrency?: boolean;
timeout?: Date;
spanIdToComplete?: string;
batch?: { id: string; index?: number };
workerId?: string;
runnerId?: string;
tx?: PrismaClientOrTransaction;
}): Promise<TaskRunExecutionSnapshot> {
const prisma = tx ?? this.$.prisma;
await this.$.raceSimulationSystem.waitForRacepoint({ runId });
let $waitpoints = typeof waitpoints === "string" ? [waitpoints] : waitpoints;
return await this.$.runLock.lock("blockRunWithWaitpoint", [runId], 5000, async () => {
let snapshot: TaskRunExecutionSnapshot = await getLatestExecutionSnapshot(prisma, runId);
//block the run with the waitpoints, returning how many waitpoints are pending
const insert = await prisma.$queryRaw<{ pending_count: BigInt }[]>`
WITH inserted AS (
INSERT INTO "TaskRunWaitpoint" ("id", "taskRunId", "waitpointId", "projectId", "createdAt", "updatedAt", "spanIdToComplete", "batchId", "batchIndex")
SELECT
gen_random_uuid(),
${runId},
w.id,
${projectId},
NOW(),
NOW(),
${spanIdToComplete ?? null},
${batch?.id ?? null},
${batch?.index ?? null}
FROM "Waitpoint" w
WHERE w.id IN (${Prisma.join($waitpoints)})
ON CONFLICT DO NOTHING
RETURNING "waitpointId"
),
connected_runs AS (
INSERT INTO "_WaitpointRunConnections" ("A", "B")
SELECT ${runId}, w.id
FROM "Waitpoint" w
WHERE w.id IN (${Prisma.join($waitpoints)})
ON CONFLICT DO NOTHING
)
SELECT COUNT(*) as pending_count
FROM inserted i
JOIN "Waitpoint" w ON w.id = i."waitpointId"
WHERE w.status = 'PENDING';`;
const isRunBlocked = Number(insert.at(0)?.pending_count ?? 0) > 0;
let newStatus: TaskRunExecutionStatus = "SUSPENDED";
if (
snapshot.executionStatus === "EXECUTING" ||
snapshot.executionStatus === "EXECUTING_WITH_WAITPOINTS"
) {
newStatus = "EXECUTING_WITH_WAITPOINTS";
}
//if the state has changed, create a new snapshot
if (newStatus !== snapshot.executionStatus) {
snapshot = await this.executionSnapshotSystem.createExecutionSnapshot(prisma, {
run: {
id: snapshot.runId,
status: snapshot.runStatus,
attemptNumber: snapshot.attemptNumber,
},
snapshot: {
executionStatus: newStatus,
description: "Run was blocked by a waitpoint.",
metadata: {
releaseConcurrency,
},
},
previousSnapshotId: snapshot.id,
environmentId: snapshot.environmentId,
environmentType: snapshot.environmentType,
projectId: snapshot.projectId,
organizationId,
// Do NOT carry over the batchId from the previous snapshot
batchId: batch?.id,
workerId,
runnerId,
});
// Let the worker know immediately, so it can suspend the run
await sendNotificationToWorker({ runId, snapshot, eventBus: this.$.eventBus });
if (isRunBlocked) {
//release concurrency
await this.releaseConcurrencySystem.releaseConcurrencyForSnapshot(snapshot);
}
}
if (timeout) {
for (const waitpoint of $waitpoints) {
await this.$.worker.enqueue({
id: `finishWaitpoint.${waitpoint}`,
job: "finishWaitpoint",
payload: {
waitpointId: waitpoint,
error: JSON.stringify(timeoutError(timeout)),
},
availableAt: timeout,
});
}
}
//no pending waitpoint, schedule unblocking the run
//debounce if we're rapidly adding waitpoints
if (!isRunBlocked) {
await this.$.worker.enqueue({
//this will debounce the call
id: `continueRunIfUnblocked:${runId}`,
job: "continueRunIfUnblocked",
payload: { runId: runId },
//in the near future
availableAt: new Date(Date.now() + 50),
});
}
return snapshot;
});
}
public async continueRunIfUnblocked({ runId }: { runId: string }) {
this.$.logger.debug(`continueRunIfUnblocked: start`, {
runId,
});
// 1. Get the any blocking waitpoints
const blockingWaitpoints = await this.$.prisma.taskRunWaitpoint.findMany({
where: { taskRunId: runId },
select: {
id: true,
batchId: true,
batchIndex: true,
waitpoint: {
select: { id: true, status: true },
},
},
});
await this.$.raceSimulationSystem.waitForRacepoint({ runId });
// 2. There are blockers still, so do nothing
if (blockingWaitpoints.some((w) => w.waitpoint.status !== "COMPLETED")) {
this.$.logger.debug(`continueRunIfUnblocked: blocking waitpoints still exist`, {
runId,
blockingWaitpoints,
});
return;
}
// 3. Get the run with environment
const run = await this.$.prisma.taskRun.findFirst({
where: {
id: runId,
},
include: {
runtimeEnvironment: {
select: {
id: true,
type: true,
maximumConcurrencyLimit: true,
project: { select: { id: true } },
organization: { select: { id: true } },
},
},
},
});
if (!run) {
this.$.logger.error(`continueRunIfUnblocked: run not found`, {
runId,
});
throw new Error(`continueRunIfUnblocked: run not found: ${runId}`);
}
//4. Continue the run whether it's executing or not
await this.$.runLock.lock("continueRunIfUnblocked", [runId], 5000, async () => {
const snapshot = await getLatestExecutionSnapshot(this.$.prisma, runId);
if (isFinishedOrPendingFinished(snapshot.executionStatus)) {
this.$.logger.debug(`continueRunIfUnblocked: run is finished, skipping`, {
runId,
snapshot,
});
return;
}
//run is still executing, send a message to the worker
if (isExecuting(snapshot.executionStatus)) {
const result = await this.$.runQueue.reacquireConcurrency(
run.runtimeEnvironment.organization.id,
runId
);
if (result) {
const newSnapshot = await this.executionSnapshotSystem.createExecutionSnapshot(
this.$.prisma,
{
run: {
id: runId,
status: snapshot.runStatus,
attemptNumber: snapshot.attemptNumber,
},
snapshot: {
executionStatus: "EXECUTING",
description: "Run was continued, whilst still executing.",
},
previousSnapshotId: snapshot.id,
environmentId: snapshot.environmentId,
environmentType: snapshot.environmentType,
projectId: snapshot.projectId,
organizationId: snapshot.organizationId,
batchId: snapshot.batchId ?? undefined,
completedWaitpoints: blockingWaitpoints.map((b) => ({
id: b.waitpoint.id,
index: b.batchIndex ?? undefined,
})),
}
);
await this.releaseConcurrencySystem.refillTokensForSnapshot(snapshot);
this.$.logger.debug(
`continueRunIfUnblocked: run was still executing, sending notification`,
{
runId,
snapshot,
newSnapshot,
}
);
await sendNotificationToWorker({
runId,
snapshot: newSnapshot,
eventBus: this.$.eventBus,
});
} else {
// Because we cannot reacquire the concurrency, we need to enqueue the run again
// and because the run is still executing, we need to set the status to QUEUED_EXECUTING
const newSnapshot = await this.enqueueSystem.enqueueRun({
run,
env: run.runtimeEnvironment,
snapshot: {
status: "QUEUED_EXECUTING",
description: "Run can continue, but is waiting for concurrency",
},
previousSnapshotId: snapshot.id,
batchId: snapshot.batchId ?? undefined,
completedWaitpoints: blockingWaitpoints.map((b) => ({
id: b.waitpoint.id,
index: b.batchIndex ?? undefined,
})),
});
this.$.logger.debug(`continueRunIfUnblocked: run goes to QUEUED_EXECUTING`, {
runId,
snapshot,
newSnapshot,
});
}
} else {
if (snapshot.executionStatus !== "RUN_CREATED" && !snapshot.checkpointId) {
// TODO: We're screwed, should probably fail the run immediately
this.$.logger.error(`continueRunIfUnblocked: run has no checkpoint`, {
runId: run.id,
snapshot,
blockingWaitpoints,
});
throw new Error(`continueRunIfUnblocked: run has no checkpoint: ${run.id}`);
}
//put it back in the queue, with the original timestamp (w/ priority)
//this prioritizes dequeuing waiting runs over new runs
const newSnapshot = await this.enqueueSystem.enqueueRun({
run,
env: run.runtimeEnvironment,
snapshot: {
description: "Run was QUEUED, because all waitpoints are completed",
},
batchId: snapshot.batchId ?? undefined,
completedWaitpoints: blockingWaitpoints.map((b) => ({
id: b.waitpoint.id,
index: b.batchIndex ?? undefined,
})),
checkpointId: snapshot.checkpointId ?? undefined,
});
this.$.logger.debug(`continueRunIfUnblocked: run goes to QUEUED`, {
runId,
snapshot,
newSnapshot,
});
}
});
if (blockingWaitpoints.length > 0) {
//5. Remove the blocking waitpoints
await this.$.prisma.taskRunWaitpoint.deleteMany({
where: {
taskRunId: runId,
id: { in: blockingWaitpoints.map((b) => b.id) },
},
});
this.$.logger.debug(`continueRunIfUnblocked: removed blocking waitpoints`, {
runId,
});
}
}
public async createRunAssociatedWaitpoint(
tx: PrismaClientOrTransaction,
{
projectId,
environmentId,
completedByTaskRunId,
}: { projectId: string; environmentId: string; completedByTaskRunId: string }
) {
return tx.waitpoint.create({
data: {
...WaitpointId.generate(),
type: "RUN",
status: "PENDING",
idempotencyKey: nanoid(24),
userProvidedIdempotencyKey: false,
projectId,
environmentId,
completedByTaskRunId,
},
});
}
}