-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathindex.ts
More file actions
2472 lines (2267 loc) · 75.7 KB
/
index.ts
File metadata and controls
2472 lines (2267 loc) · 75.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
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createRedisClient, Redis } from "@internal/redis";
import { getMeter, Meter, startSpan, trace, Tracer } from "@internal/tracing";
import { Logger } from "@trigger.dev/core/logger";
import {
CheckpointInput,
CompleteRunAttemptResult,
CreateCheckpointResult,
DequeuedMessage,
ExecutionResult,
formatDurationMilliseconds,
RunExecutionData,
StartRunAttemptResult,
TaskRunContext,
TaskRunExecutionResult,
TaskRunInternalError,
} from "@trigger.dev/core/v3";
import { TaskRunError } from "@trigger.dev/core/v3/schemas";
import {
parseNaturalLanguageDurationInMs,
RunId,
WaitpointId,
} from "@trigger.dev/core/v3/isomorphic";
import {
Prisma,
PrismaClient,
PrismaClientOrTransaction,
PrismaReplicaClient,
RuntimeEnvironmentType,
TaskRun,
TaskRunExecutionSnapshot,
Waitpoint,
} from "@trigger.dev/database";
import { Worker } from "@trigger.dev/redis-worker";
import { assertNever } from "assert-never";
import { EventEmitter } from "node:events";
import { BatchQueue } from "../batch-queue/index.js";
import type {
BatchItem,
CompleteBatchResult,
InitializeBatchOptions,
ProcessBatchItemCallback,
BatchCompletionCallback,
} from "../batch-queue/types.js";
import { FairQueueSelectionStrategy } from "../run-queue/fairQueueSelectionStrategy.js";
import { RunQueue } from "../run-queue/index.js";
import { RunQueueFullKeyProducer } from "../run-queue/keyProducer.js";
import { AuthenticatedEnvironment, MinimalAuthenticatedEnvironment } from "../shared/index.js";
import { BillingCache } from "./billingCache.js";
import { NotImplementedError, RunDuplicateIdempotencyKeyError } from "./errors.js";
import { EventBus, EventBusEvents } from "./eventBus.js";
import { RunLocker } from "./locking.js";
import { getFinalRunStatuses } from "./statuses.js";
import { BatchSystem } from "./systems/batchSystem.js";
import { CheckpointSystem } from "./systems/checkpointSystem.js";
import { DebounceSystem } from "./systems/debounceSystem.js";
import { DelayedRunSystem } from "./systems/delayedRunSystem.js";
import { DequeueSystem } from "./systems/dequeueSystem.js";
import { EnqueueSystem } from "./systems/enqueueSystem.js";
import {
executionDataFromSnapshot,
ExecutionSnapshotSystem,
getExecutionSnapshotsSince,
getLatestExecutionSnapshot,
} from "./systems/executionSnapshotSystem.js";
import { PendingVersionSystem } from "./systems/pendingVersionSystem.js";
import { RaceSimulationSystem } from "./systems/raceSimulationSystem.js";
import { RunAttemptSystem } from "./systems/runAttemptSystem.js";
import { SystemResources } from "./systems/systems.js";
import { TtlSystem } from "./systems/ttlSystem.js";
import { WaitpointSystem } from "./systems/waitpointSystem.js";
import {
EngineWorker,
HeartbeatTimeouts,
ReportableQueue,
RunEngineOptions,
TriggerParams,
} from "./types.js";
import { createTtlWorkerCatalog } from "./ttlWorkerCatalog.js";
import { workerCatalog } from "./workerCatalog.js";
import pMap from "p-map";
export class RunEngine {
private runLockRedis: Redis;
private runLock: RunLocker;
private worker: EngineWorker;
private ttlWorker: Worker<ReturnType<typeof createTtlWorkerCatalog>>;
private logger: Logger;
private tracer: Tracer;
private meter: Meter;
private heartbeatTimeouts: HeartbeatTimeouts;
private repairSnapshotTimeoutMs: number;
private batchQueue: BatchQueue;
prisma: PrismaClient;
readOnlyPrisma: PrismaReplicaClient;
runQueue: RunQueue;
eventBus: EventBus = new EventEmitter<EventBusEvents>();
executionSnapshotSystem: ExecutionSnapshotSystem;
runAttemptSystem: RunAttemptSystem;
dequeueSystem: DequeueSystem;
waitpointSystem: WaitpointSystem;
batchSystem: BatchSystem;
enqueueSystem: EnqueueSystem;
checkpointSystem: CheckpointSystem;
delayedRunSystem: DelayedRunSystem;
debounceSystem: DebounceSystem;
ttlSystem: TtlSystem;
pendingVersionSystem: PendingVersionSystem;
raceSimulationSystem: RaceSimulationSystem = new RaceSimulationSystem();
private readonly billingCache: BillingCache;
constructor(private readonly options: RunEngineOptions) {
this.logger = options.logger ?? new Logger("RunEngine", this.options.logLevel ?? "info");
this.prisma = options.prisma;
this.readOnlyPrisma = options.readOnlyPrisma ?? this.prisma;
this.runLockRedis = createRedisClient(
{
...options.runLock.redis,
keyPrefix: `${options.runLock.redis.keyPrefix}runlock:`,
},
{
onError: (error) => {
this.logger.error(`RunLock redis client error:`, {
error,
keyPrefix: options.runLock.redis.keyPrefix,
});
},
}
);
this.runLock = new RunLocker({
redis: this.runLockRedis,
logger: this.logger,
tracer: trace.getTracer("RunLocker"),
meter: options.meter,
duration: options.runLock.duration ?? 5000,
automaticExtensionThreshold: options.runLock.automaticExtensionThreshold ?? 1000,
retryConfig: {
maxAttempts: 10,
baseDelay: 100,
maxDelay: 3000,
backoffMultiplier: 1.8,
jitterFactor: 0.15,
maxTotalWaitTime: 15000,
...options.runLock.retryConfig,
},
});
const keys = new RunQueueFullKeyProducer();
const queueSelectionStrategyOptions = {
keys,
redis: { ...options.queue.redis, keyPrefix: `${options.queue.redis.keyPrefix}runqueue:` },
defaultEnvConcurrencyLimit: options.queue?.defaultEnvConcurrency ?? 10,
...options.queue?.queueSelectionStrategyOptions,
};
this.logger.log("RunEngine FairQueueSelectionStrategy queueSelectionStrategyOptions", {
options: queueSelectionStrategyOptions,
});
this.runQueue = new RunQueue({
name: "rq",
tracer: trace.getTracer("rq"),
keys,
queueSelectionStrategy: new FairQueueSelectionStrategy(queueSelectionStrategyOptions),
defaultEnvConcurrency: options.queue?.defaultEnvConcurrency ?? 10,
defaultEnvConcurrencyBurstFactor: options.queue?.defaultEnvConcurrencyBurstFactor,
logger: new Logger("RunQueue", options.queue?.logLevel ?? "info"),
redis: { ...options.queue.redis, keyPrefix: `${options.queue.redis.keyPrefix}runqueue:` },
retryOptions: options.queue?.retryOptions,
workerOptions: {
disabled: options.worker.disabled,
concurrency: options.worker,
pollIntervalMs: options.worker.pollIntervalMs,
immediatePollIntervalMs: options.worker.immediatePollIntervalMs,
shutdownTimeoutMs: options.worker.shutdownTimeoutMs,
},
concurrencySweeper: {
scanSchedule: options.queue?.concurrencySweeper?.scanSchedule,
processMarkedSchedule: options.queue?.concurrencySweeper?.processMarkedSchedule,
scanJitterInMs: options.queue?.concurrencySweeper?.scanJitterInMs,
processMarkedJitterInMs: options.queue?.concurrencySweeper?.processMarkedJitterInMs,
callback: this.#concurrencySweeperCallback.bind(this),
},
shardCount: options.queue?.shardCount,
masterQueueConsumersDisabled: options.queue?.masterQueueConsumersDisabled,
masterQueueConsumersIntervalMs: options.queue?.masterQueueConsumersIntervalMs,
processWorkerQueueDebounceMs: options.queue?.processWorkerQueueDebounceMs,
dequeueBlockingTimeoutSeconds: options.queue?.dequeueBlockingTimeoutSeconds,
meter: options.meter,
ttlSystem: options.queue?.ttlSystem?.disabled
? undefined
: {
shardCount: options.queue?.ttlSystem?.shardCount,
pollIntervalMs: options.queue?.ttlSystem?.pollIntervalMs,
batchSize: options.queue?.ttlSystem?.batchSize,
consumersDisabled: options.queue?.ttlSystem?.consumersDisabled,
workerQueueSuffix: "ttl-worker:{queue:ttl-expiration:}queue",
workerItemsSuffix: "ttl-worker:{queue:ttl-expiration:}items",
visibilityTimeoutMs: options.queue?.ttlSystem?.visibilityTimeoutMs ?? 30_000,
},
});
this.worker = new Worker({
name: "run-engine-worker",
redisOptions: {
...options.worker.redis,
keyPrefix: `${options.worker.redis.keyPrefix}worker:`,
},
catalog: workerCatalog,
concurrency: options.worker,
pollIntervalMs: options.worker.pollIntervalMs,
immediatePollIntervalMs: options.worker.immediatePollIntervalMs,
shutdownTimeoutMs: options.worker.shutdownTimeoutMs,
logger: new Logger("RunEngineWorker", options.logLevel ?? "info"),
jobs: {
finishWaitpoint: async ({ payload }) => {
await this.waitpointSystem.completeWaitpoint({
id: payload.waitpointId,
output: payload.error
? {
value: payload.error,
isError: true,
}
: undefined,
});
},
heartbeatSnapshot: async ({ payload }) => {
await this.#handleStalledSnapshot(payload);
},
repairSnapshot: async ({ payload }) => {
await this.#handleRepairSnapshot(payload);
},
expireRun: async ({ payload }) => {
await this.ttlSystem.expireRun({ runId: payload.runId });
},
cancelRun: async ({ payload }) => {
await this.runAttemptSystem.cancelRun({
runId: payload.runId,
completedAt: payload.completedAt,
reason: payload.reason,
});
},
queueRunsPendingVersion: async ({ payload }) => {
await this.pendingVersionSystem.enqueueRunsForBackgroundWorker(
payload.backgroundWorkerId
);
},
tryCompleteBatch: async ({ payload }) => {
await this.batchSystem.performCompleteBatch({ batchId: payload.batchId });
},
continueRunIfUnblocked: async ({ payload }) => {
await this.waitpointSystem.continueRunIfUnblocked({
runId: payload.runId,
});
},
enqueueDelayedRun: async ({ payload }) => {
await this.delayedRunSystem.enqueueDelayedRun({ runId: payload.runId });
},
},
});
if (!options.worker.disabled) {
console.log("✅ Starting run engine worker");
this.worker.start();
}
this.tracer = options.tracer;
this.meter = options.meter ?? getMeter("run-engine");
const defaultHeartbeatTimeouts: HeartbeatTimeouts = {
PENDING_EXECUTING: 60_000,
PENDING_CANCEL: 60_000,
EXECUTING: 60_000,
EXECUTING_WITH_WAITPOINTS: 60_000,
SUSPENDED: 60_000 * 10,
};
this.heartbeatTimeouts = {
...defaultHeartbeatTimeouts,
...(options.heartbeatTimeoutsMs ?? {}),
};
this.repairSnapshotTimeoutMs = options.repairSnapshotTimeoutMs ?? 60_000;
const resources: SystemResources = {
prisma: this.prisma,
readOnlyPrisma: this.readOnlyPrisma,
worker: this.worker,
eventBus: this.eventBus,
logger: this.logger,
tracer: this.tracer,
meter: this.meter,
runLock: this.runLock,
runQueue: this.runQueue,
raceSimulationSystem: this.raceSimulationSystem,
};
this.executionSnapshotSystem = new ExecutionSnapshotSystem({
resources,
heartbeatTimeouts: this.heartbeatTimeouts,
});
this.enqueueSystem = new EnqueueSystem({
resources,
executionSnapshotSystem: this.executionSnapshotSystem,
});
this.checkpointSystem = new CheckpointSystem({
resources,
executionSnapshotSystem: this.executionSnapshotSystem,
enqueueSystem: this.enqueueSystem,
});
this.delayedRunSystem = new DelayedRunSystem({
resources,
enqueueSystem: this.enqueueSystem,
});
this.debounceSystem = new DebounceSystem({
resources,
redis: options.debounce?.redis ?? options.runLock.redis,
executionSnapshotSystem: this.executionSnapshotSystem,
delayedRunSystem: this.delayedRunSystem,
maxDebounceDurationMs: options.debounce?.maxDebounceDurationMs ?? 60 * 60 * 1000, // Default 1 hour
});
this.pendingVersionSystem = new PendingVersionSystem({
resources,
enqueueSystem: this.enqueueSystem,
});
this.waitpointSystem = new WaitpointSystem({
resources,
executionSnapshotSystem: this.executionSnapshotSystem,
enqueueSystem: this.enqueueSystem,
});
this.ttlSystem = new TtlSystem({
resources,
waitpointSystem: this.waitpointSystem,
});
const ttlWorkerCatalog = createTtlWorkerCatalog({
visibilityTimeoutMs: options.queue?.ttlSystem?.visibilityTimeoutMs,
batchMaxSize: options.queue?.ttlSystem?.batchMaxSize,
batchMaxWaitMs: options.queue?.ttlSystem?.batchMaxWaitMs,
});
this.ttlWorker = new Worker({
name: "ttl-expiration",
redisOptions: {
...options.queue.redis,
keyPrefix: `${options.queue.redis.keyPrefix}runqueue:ttl-worker:`,
},
catalog: ttlWorkerCatalog,
concurrency: { limit: options.queue?.ttlSystem?.workerConcurrency ?? 1 },
pollIntervalMs: options.worker.pollIntervalMs ?? 1000,
immediatePollIntervalMs: options.worker.immediatePollIntervalMs ?? 100,
shutdownTimeoutMs: options.worker.shutdownTimeoutMs ?? 10_000,
logger: new Logger("RunEngineTtlWorker", options.logLevel ?? "info"),
jobs: {
expireTtlRun: async (items) => {
await this.ttlSystem.expireRunsBatch(items.map((i) => i.payload.runId));
},
},
});
// Start TTL worker whenever TTL system is enabled, so expired runs enqueued by the
// Lua script get processed even when the main engine worker is disabled (e.g. in tests).
if (options.queue?.ttlSystem && !options.queue.ttlSystem.disabled && !options.queue.ttlSystem.consumersDisabled) {
this.ttlWorker.start();
}
this.batchSystem = new BatchSystem({
resources,
waitpointSystem: this.waitpointSystem,
});
// Initialize BatchQueue for DRR-based batch processing (if configured)
// Only start consumers if consumerDisabled is not set or is false
const startBatchQueueConsumers = options.batchQueue?.consumerEnabled ?? true;
this.batchQueue = new BatchQueue({
redis: {
keyPrefix: `${options.batchQueue?.redis.keyPrefix ?? ""}batch-queue:`,
...options.batchQueue?.redis,
},
drr: {
quantum: options.batchQueue?.drr?.quantum ?? 5,
maxDeficit: options.batchQueue?.drr?.maxDeficit ?? 50,
masterQueueLimit: options.batchQueue?.drr?.masterQueueLimit,
},
shardCount: options.batchQueue?.shardCount,
workerQueueBlockingTimeoutSeconds: options.batchQueue?.workerQueueBlockingTimeoutSeconds,
consumerCount: options.batchQueue?.consumerCount ?? 2,
consumerIntervalMs: options.batchQueue?.consumerIntervalMs ?? 100,
defaultConcurrency: options.batchQueue?.defaultConcurrency ?? 10,
globalRateLimiter: options.batchQueue?.globalRateLimiter,
workerQueueMaxDepth: options.batchQueue?.workerQueueMaxDepth,
startConsumers: startBatchQueueConsumers,
retry: options.batchQueue?.retry,
tracer: options.tracer,
meter: options.meter,
});
this.logger.info("BatchQueue initialized", {
consumerCount: options.batchQueue?.consumerCount ?? 2,
drrQuantum: options.batchQueue?.drr?.quantum ?? 5,
defaultConcurrency: options.batchQueue?.defaultConcurrency ?? 10,
consumersEnabled: startBatchQueueConsumers,
});
this.runAttemptSystem = new RunAttemptSystem({
resources,
executionSnapshotSystem: this.executionSnapshotSystem,
batchSystem: this.batchSystem,
waitpointSystem: this.waitpointSystem,
delayedRunSystem: this.delayedRunSystem,
machines: this.options.machines,
retryWarmStartThresholdMs: this.options.retryWarmStartThresholdMs,
redisOptions: this.options.cache?.redis ?? this.options.runLock.redis,
});
this.billingCache = new BillingCache({
billingOptions: this.options.billing,
redisOptions: this.options.cache?.redis ?? this.options.runLock.redis,
logger: this.logger,
});
this.dequeueSystem = new DequeueSystem({
resources,
executionSnapshotSystem: this.executionSnapshotSystem,
runAttemptSystem: this.runAttemptSystem,
machines: this.options.machines,
billingCache: this.billingCache,
});
}
//MARK: - Run functions
/** "Triggers" one run. */
async trigger(
{
friendlyId,
environment,
idempotencyKey,
idempotencyKeyExpiresAt,
idempotencyKeyOptions,
taskIdentifier,
payload,
payloadType,
context,
traceContext,
traceId,
spanId,
parentSpanId,
lockedToVersionId,
taskVersion,
sdkVersion,
cliVersion,
concurrencyKey,
workerQueue,
enableFastPath,
queue,
lockedQueueId,
isTest,
delayUntil,
queuedAt,
maxAttempts,
taskEventStore,
priorityMs,
queueTimestamp,
ttl,
tags,
parentTaskRunId,
rootTaskRunId,
replayedFromTaskRunFriendlyId,
batch,
resumeParentOnCompletion,
depth,
metadata,
metadataType,
seedMetadata,
seedMetadataType,
oneTimeUseToken,
maxDurationInSeconds,
machine,
workerId,
runnerId,
scheduleId,
scheduleInstanceId,
createdAt,
bulkActionId,
planType,
realtimeStreamsVersion,
debounce,
annotations,
onDebounced,
}: TriggerParams,
tx?: PrismaClientOrTransaction
): Promise<TaskRun> {
const prisma = tx ?? this.prisma;
return startSpan(
this.tracer,
"trigger",
async (span) => {
// Handle debounce before creating a new run
// Store claimId if we successfully claimed the debounce key
let debounceClaimId: string | undefined;
if (debounce) {
const debounceResult = await this.debounceSystem.handleDebounce({
environmentId: environment.id,
taskIdentifier,
debounce:
debounce.mode === "trailing"
? {
...debounce,
updateData: {
payload,
payloadType,
metadata,
metadataType,
tags,
maxAttempts,
maxDurationInSeconds,
machine,
},
}
: debounce,
tx: prisma,
});
if (debounceResult.status === "existing") {
span.setAttribute("debounced", true);
span.setAttribute("existingRunId", debounceResult.run.id);
// For triggerAndWait, block the parent run with the existing run's waitpoint
if (resumeParentOnCompletion && parentTaskRunId) {
// Get or create waitpoint lazily (existing run may not have one if it was standalone)
let waitpoint = debounceResult.waitpoint;
if (!waitpoint) {
waitpoint = await this.waitpointSystem.getOrCreateRunWaitpoint({
runId: debounceResult.run.id,
projectId: environment.project.id,
environmentId: environment.id,
});
}
// Call the onDebounced callback to create a span and get spanIdToComplete
let spanIdToComplete: string | undefined;
if (onDebounced) {
spanIdToComplete = await onDebounced({
existingRun: debounceResult.run,
waitpoint,
debounceKey: debounce.key,
});
}
await this.waitpointSystem.blockRunWithWaitpoint({
runId: parentTaskRunId,
waitpoints: waitpoint.id,
spanIdToComplete,
projectId: environment.project.id,
organizationId: environment.organization.id,
batch,
workerId,
runnerId,
tx: prisma,
});
}
return debounceResult.run;
}
// If max_duration_exceeded, we continue to create a new run without debouncing
if (debounceResult.status === "max_duration_exceeded") {
span.setAttribute("debounceMaxDurationExceeded", true);
}
// Store the claimId for later registration
if (debounceResult.status === "new" && debounceResult.claimId) {
debounceClaimId = debounceResult.claimId;
span.setAttribute("debounceClaimId", debounceClaimId);
}
}
const status = delayUntil ? "DELAYED" : "PENDING";
// Apply defaultMaxTtl: use as default when no TTL is provided, clamp when larger
const resolvedTtl = this.#resolveMaxTtl(ttl);
//create run
let taskRun: TaskRun & { associatedWaitpoint: Waitpoint | null };
const taskRunId = RunId.fromFriendlyId(friendlyId);
try {
taskRun = await prisma.taskRun.create({
include: {
associatedWaitpoint: true,
},
data: {
id: taskRunId,
engine: "V2",
status,
friendlyId,
runtimeEnvironmentId: environment.id,
environmentType: environment.type,
organizationId: environment.organization.id,
projectId: environment.project.id,
idempotencyKey,
idempotencyKeyExpiresAt,
idempotencyKeyOptions,
taskIdentifier,
payload,
payloadType,
context,
traceContext,
traceId,
spanId,
parentSpanId,
lockedToVersionId,
taskVersion,
sdkVersion,
cliVersion,
concurrencyKey,
queue,
lockedQueueId,
workerQueue,
isTest,
delayUntil,
queuedAt,
maxAttempts,
taskEventStore,
priorityMs,
queueTimestamp: queueTimestamp ?? delayUntil ?? new Date(),
ttl: resolvedTtl,
tags:
tags.length === 0
? undefined
: {
connect: tags,
},
runTags: tags.length === 0 ? undefined : tags.map((tag) => tag.name),
oneTimeUseToken,
parentTaskRunId,
rootTaskRunId,
replayedFromTaskRunFriendlyId,
batchId: batch?.id,
resumeParentOnCompletion,
depth,
metadata,
metadataType,
seedMetadata,
seedMetadataType,
maxDurationInSeconds,
machinePreset: machine,
scheduleId,
scheduleInstanceId,
createdAt,
bulkActionGroupIds: bulkActionId ? [bulkActionId] : undefined,
planType,
realtimeStreamsVersion,
debounce: debounce
? {
key: debounce.key,
delay: debounce.delay,
createdAt: new Date(),
}
: undefined,
annotations,
executionSnapshots: {
create: {
engine: "V2",
executionStatus: delayUntil ? "DELAYED" : "RUN_CREATED",
description: delayUntil ? "Run is delayed" : "Run was created",
runStatus: status,
environmentId: environment.id,
environmentType: environment.type,
projectId: environment.project.id,
organizationId: environment.organization.id,
workerId,
runnerId,
},
},
// Only create waitpoint if parent is waiting for this run to complete
// For standalone triggers (no waiting parent), waitpoint is created lazily if needed later
associatedWaitpoint:
resumeParentOnCompletion && parentTaskRunId
? {
create: this.waitpointSystem.buildRunAssociatedWaitpoint({
projectId: environment.project.id,
environmentId: environment.id,
}),
}
: undefined,
},
});
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
this.logger.debug("engine.trigger(): Prisma transaction error", {
code: error.code,
message: error.message,
meta: error.meta,
idempotencyKey,
environmentId: environment.id,
});
if (error.code === "P2002") {
this.logger.debug("engine.trigger(): throwing RunDuplicateIdempotencyKeyError", {
code: error.code,
message: error.message,
meta: error.meta,
idempotencyKey,
environmentId: environment.id,
});
//this happens if a unique constraint failed, i.e. duplicate idempotency
throw new RunDuplicateIdempotencyKeyError(
`Run with idempotency key ${idempotencyKey} already exists`
);
}
}
throw error;
}
span.setAttribute("runId", taskRun.id);
//triggerAndWait or batchTriggerAndWait
if (resumeParentOnCompletion && parentTaskRunId && taskRun.associatedWaitpoint) {
if (batch) {
// Batch path: lockless insert. The parent is already EXECUTING_WITH_WAITPOINTS
// from blockRunWithCreatedBatch, so we only need to insert the TaskRunWaitpoint
// row without acquiring the parent run lock. This avoids lock contention when
// processing large batches with high concurrency.
await this.waitpointSystem.blockRunWithWaitpointLockless({
runId: parentTaskRunId,
waitpoints: taskRun.associatedWaitpoint.id,
projectId: taskRun.associatedWaitpoint.projectId,
batch,
tx: prisma,
});
} else {
// Single triggerAndWait: acquire the parent run lock to safely transition
// the snapshot and insert the waitpoint
await this.waitpointSystem.blockRunWithWaitpoint({
runId: parentTaskRunId,
waitpoints: taskRun.associatedWaitpoint.id,
projectId: taskRun.associatedWaitpoint.projectId,
organizationId: environment.organization.id,
batch,
workerId,
runnerId,
tx: prisma,
});
}
}
if (taskRun.delayUntil) {
// Schedule the run to be enqueued at the delayUntil time
await this.delayedRunSystem.scheduleDelayedRunEnqueuing({
runId: taskRun.id,
delayUntil: taskRun.delayUntil,
});
// Register debounced run in Redis for future lookups
if (debounce) {
const registered = await this.debounceSystem.registerDebouncedRun({
runId: taskRun.id,
environmentId: environment.id,
taskIdentifier,
debounceKey: debounce.key,
delayUntil: taskRun.delayUntil,
claimId: debounceClaimId,
});
if (!registered) {
// We lost the claim - this shouldn't normally happen, but log it
this.logger.warn("trigger: lost debounce claim after creating run", {
runId: taskRun.id,
debounceKey: debounce.key,
claimId: debounceClaimId,
});
}
}
} else {
try {
if (taskRun.ttl) {
await this.ttlSystem.scheduleExpireRun({ runId: taskRun.id, ttl: taskRun.ttl });
}
await this.enqueueSystem.enqueueRun({
run: taskRun,
env: environment,
workerId,
runnerId,
tx: prisma,
skipRunLock: true,
includeTtl: true,
enableFastPath,
});
} catch (enqueueError) {
this.logger.error("engine.trigger(): failed to schedule TTL or enqueue run", {
runId: taskRun.id,
friendlyId: taskRun.friendlyId,
taskIdentifier: taskRun.taskIdentifier,
environmentId: environment.id,
ttl: taskRun.ttl,
error: enqueueError,
});
throw enqueueError;
}
}
this.eventBus.emit("runCreated", {
time: new Date(),
runId: taskRun.id,
});
return taskRun;
},
{
attributes: {
friendlyId,
environmentId: environment.id,
projectId: environment.project.id,
taskIdentifier,
},
}
);
}
/**
* Creates a pre-failed TaskRun in SYSTEM_FAILURE status.
*
* Used when a batch item fails to trigger (e.g., queue limits, environment not found).
* Creates the run record so batch completion can track it, and if the batch has a
* waiting parent, creates and immediately completes a RUN waitpoint with the error.
*/
async createFailedTaskRun({
friendlyId,
environment,
taskIdentifier,
payload,
payloadType,
error,
parentTaskRunId,
rootTaskRunId,
depth,
resumeParentOnCompletion,
batch,
traceId,
spanId,
traceContext,
taskEventStore,
queue: queueOverride,
lockedQueueId: lockedQueueIdOverride,
}: {
friendlyId: string;
environment: {
id: string;
type: RuntimeEnvironmentType;
project: { id: string };
organization: { id: string };
};
taskIdentifier: string;
payload?: string;
payloadType?: string;
error: TaskRunError;
parentTaskRunId?: string;
/** The root run of the task tree. If the parent is already a child, this is the parent's root. */
rootTaskRunId?: string;
/** Depth in the task tree (0 for root, parentDepth+1 for children). */
depth?: number;
resumeParentOnCompletion?: boolean;
batch?: { id: string; index: number };
traceId?: string;
spanId?: string;
traceContext?: Record<string, unknown>;
taskEventStore?: string;
/** Resolved queue name (e.g. custom queue). When provided, used instead of task/${taskIdentifier}. */
queue?: string;
/** Resolved TaskQueue.id when the task is locked to a specific queue. */
lockedQueueId?: string;
}): Promise<TaskRun> {
return startSpan(
this.tracer,
"createFailedTaskRun",
async (span) => {
const taskRunId = RunId.fromFriendlyId(friendlyId);
// Build associated waitpoint data if parent is waiting for this run
const waitpointData =
resumeParentOnCompletion && parentTaskRunId
? this.waitpointSystem.buildRunAssociatedWaitpoint({
projectId: environment.project.id,
environmentId: environment.id,
})
: undefined;
// Create the run in terminal SYSTEM_FAILURE status.
// No execution snapshot is needed: this run never gets dequeued, executed,
// or heartbeated, so nothing will call getLatestExecutionSnapshot on it.
const taskRun = await this.prisma.taskRun.create({
include: {
associatedWaitpoint: true,
},
data: {
id: taskRunId,
engine: "V2",
status: "SYSTEM_FAILURE",
friendlyId,
runtimeEnvironmentId: environment.id,
environmentType: environment.type,
organizationId: environment.organization.id,
projectId: environment.project.id,
taskIdentifier,
payload: payload ?? "",
payloadType: payloadType ?? "application/json",
context: {},
traceContext: (traceContext ?? {}) as Record<string, string | undefined>,
traceId: traceId ?? "",
spanId: spanId ?? "",
queue: queueOverride ?? `task/${taskIdentifier}`,
lockedQueueId: lockedQueueIdOverride,
isTest: false,
completedAt: new Date(),
error: error as unknown as Prisma.InputJsonObject,
parentTaskRunId,
rootTaskRunId,
depth: depth ?? 0,
batchId: batch?.id,
resumeParentOnCompletion,
taskEventStore,
associatedWaitpoint: waitpointData
? { create: waitpointData }
: undefined,
},
});
span.setAttribute("runId", taskRun.id);
// If parent is waiting, block it with the waitpoint then immediately
// complete it with the error output so the parent can resume.
if (
resumeParentOnCompletion &&
parentTaskRunId &&
taskRun.associatedWaitpoint
) {
await this.waitpointSystem.blockRunAndCompleteWaitpoint({
runId: parentTaskRunId,
waitpointId: taskRun.associatedWaitpoint.id,
output: { value: JSON.stringify(error), isError: true },
projectId: environment.project.id,
organizationId: environment.organization.id,
batch,
});
}
return taskRun;
},
{
attributes: {
friendlyId,
environmentId: environment.id,
projectId: environment.project.id,
taskIdentifier,
},
}
);
}
/**
* Gets a fairly selected run from the specified master queue, returning the information required to run it.
* @param consumerId: The consumer that is pulling, allows multiple consumers to pull from the same queue
* @param workerQueue: The worker queue to pull from, can be an individual environment (for dev)
* @returns
*/
async dequeueFromWorkerQueue({
consumerId,
workerQueue,
backgroundWorkerId,
workerId,
runnerId,
tx,
skipObserving,
blockingPop,
blockingPopTimeoutSeconds,
}: {
consumerId: string;
workerQueue: string;
backgroundWorkerId?: string;
workerId?: string;
runnerId?: string;
tx?: PrismaClientOrTransaction;
skipObserving?: boolean;