-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathindex.ts
More file actions
1123 lines (986 loc) · 38.9 KB
/
index.ts
File metadata and controls
1123 lines (986 loc) · 38.9 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, type Redis } from "@internal/redis";
import {
startSpan,
type Counter,
type Histogram,
type Meter,
type ObservableGauge,
type Span,
type Tracer,
} from "@internal/tracing";
import { Logger } from "@trigger.dev/core/logger";
import {
BatchedSpanManager,
CallbackFairQueueKeyProducer,
DRRScheduler,
FairQueue,
ExponentialBackoffRetry,
isAbortError,
WorkerQueueManager,
type FairQueueOptions,
type GlobalRateLimiter,
} from "@trigger.dev/redis-worker";
import { BatchCompletionTracker } from "./completionTracker.js";
import type {
BatchCompletionCallback,
BatchItem,
BatchItemPayload,
BatchMeta,
BatchQueueOptions,
CompleteBatchResult,
InitializeBatchOptions,
ProcessBatchItemCallback,
} from "./types.js";
import { BatchItemPayload as BatchItemPayloadSchema } from "./types.js";
export { BatchCompletionTracker } from "./completionTracker.js";
export type { BatchQueueOptions, CompleteBatchResult, InitializeBatchOptions } from "./types.js";
/**
* BatchQueue manages batch trigger processing with fair scheduling using
* Deficit Round Robin (DRR) algorithm.
*
* This implementation uses FairQueue from @trigger.dev/redis-worker internally
* for message queueing and fair scheduling. Batch completion tracking is handled
* separately via BatchCompletionTracker.
*
* Key features:
* - Fair processing across environments via DRR
* - Atomic operations using Lua scripts
* - Graceful error handling with per-item failure tracking
* - Each batch becomes a FairQueue "queue" (queueId = batchId, tenantId = envId)
* - OpenTelemetry metrics for observability
*/
// Redis key for environment concurrency limits
const ENV_CONCURRENCY_KEY_PREFIX = "batch:env_concurrency";
// Single worker queue ID for all batch items
// BatchQueue uses a single shared worker queue - FairQueue handles fair scheduling,
// then all messages are routed to this queue for BatchQueue's own consumer loop.
const BATCH_WORKER_QUEUE_ID = "batch-worker-queue";
export class BatchQueue {
private fairQueue: FairQueue<typeof BatchItemPayloadSchema>;
private workerQueueManager: WorkerQueueManager;
private completionTracker: BatchCompletionTracker;
private logger: Logger;
private tracer?: Tracer;
private concurrencyRedis: Redis;
private defaultConcurrency: number;
private maxAttempts: number;
private processItemCallback?: ProcessBatchItemCallback;
private completionCallback?: BatchCompletionCallback;
// Consumer loop state
private isRunning = false;
private abortController: AbortController;
private workerQueueConsumerLoops: Promise<void>[] = [];
private workerQueueBlockingTimeoutSeconds: number;
private globalRateLimiter?: GlobalRateLimiter;
private batchedSpanManager: BatchedSpanManager;
// Metrics
private batchesEnqueuedCounter?: Counter;
private itemsEnqueuedCounter?: Counter;
private itemsProcessedCounter?: Counter;
private itemsFailedCounter?: Counter;
private batchCompletedCounter?: Counter;
private batchProcessingDurationHistogram?: Histogram;
private itemQueueTimeHistogram?: Histogram;
private workerQueueLengthGauge?: ObservableGauge;
private rateLimitDeniedCounter?: Counter;
constructor(private options: BatchQueueOptions) {
this.logger = options.logger ?? new Logger("BatchQueue", options.logLevel ?? "info");
this.tracer = options.tracer;
this.defaultConcurrency = options.defaultConcurrency ?? 10;
this.maxAttempts = options.retry?.maxAttempts ?? 1;
this.abortController = new AbortController();
this.workerQueueBlockingTimeoutSeconds = options.workerQueueBlockingTimeoutSeconds ?? 10;
this.globalRateLimiter = options.globalRateLimiter;
// Initialize metrics if meter is provided
if (options.meter) {
this.#initializeMetrics(options.meter);
}
// Create key producer that extracts envId as tenantId from batchId
// Queue IDs are formatted as: env:{envId}:batch:{batchId}
const keyProducer = new CallbackFairQueueKeyProducer({
prefix: "batch",
extractTenantId: (queueId: string) => {
// Format: env:{envId}:batch:{batchId}
const parts = queueId.split(":");
if (parts.length >= 2 && parts[0] === "env" && parts[1]) {
return parts[1];
}
return queueId;
},
extractGroupId: (groupName: string, queueId: string) => {
const parts = queueId.split(":");
// Extract envId for the "tenant" concurrency group
if (groupName === "tenant" && parts.length >= 2 && parts[0] === "env" && parts[1]) {
return parts[1];
}
return "";
},
});
// Create a separate Redis client for concurrency lookups
this.concurrencyRedis = createRedisClient(options.redis);
const scheduler = new DRRScheduler({
redis: options.redis,
keys: keyProducer,
quantum: options.drr.quantum,
maxDeficit: options.drr.maxDeficit,
masterQueueLimit: options.drr.masterQueueLimit,
logger: {
debug: (msg, ctx) => this.logger.debug(msg, ctx),
error: (msg, ctx) => this.logger.error(msg, ctx),
},
});
// Create FairQueue with telemetry and environment-based concurrency limiting
// FairQueue handles fair scheduling and routes messages to the batch worker queue
// BatchQueue runs its own consumer loop to process messages from the worker queue
const fairQueueOptions: FairQueueOptions<typeof BatchItemPayloadSchema> = {
redis: options.redis,
keys: keyProducer,
scheduler,
payloadSchema: BatchItemPayloadSchema,
validateOnEnqueue: false, // We control the payload
shardCount: options.shardCount ?? 1,
consumerCount: options.consumerCount,
consumerIntervalMs: options.consumerIntervalMs,
visibilityTimeoutMs: 60_000, // 1 minute for batch item processing
startConsumers: false, // We control when to start
cooloff: {
enabled: false,
},
// Worker queue configuration - FairQueue routes all messages to our single worker queue
workerQueue: {
// All batch items go to the same worker queue - BatchQueue handles consumption
resolveWorkerQueue: () => BATCH_WORKER_QUEUE_ID,
},
// Concurrency group based on tenant (environment)
// This limits how many batch items can be processed concurrently per environment
// Items wait in queue until capacity frees up
// Note: Must use "tenant" as the group name - this is what FairQueue expects
concurrencyGroups: [
{
name: "tenant",
extractGroupId: (queue) => queue.tenantId, // tenantId = envId
defaultLimit: this.defaultConcurrency,
getLimit: async (envId: string) => {
return this.getEnvConcurrency(envId);
},
},
],
// Worker queue depth cap to prevent unbounded growth (protects visibility timeouts)
workerQueueMaxDepth: options.workerQueueMaxDepth,
workerQueueDepthCheckId: BATCH_WORKER_QUEUE_ID,
// Enable retry with DLQ disabled when retry config is provided.
// BatchQueue handles the "final failure" in its own processing loop,
// so we don't need the DLQ - we just need the retry scheduling.
...(options.retry
? {
retry: {
strategy: new ExponentialBackoffRetry({
maxAttempts: options.retry.maxAttempts,
minTimeoutInMs: options.retry.minTimeoutInMs ?? 1_000,
maxTimeoutInMs: options.retry.maxTimeoutInMs ?? 30_000,
factor: options.retry.factor ?? 2,
randomize: options.retry.randomize ?? true,
}),
deadLetterQueue: false,
},
}
: {}),
logger: this.logger,
tracer: options.tracer,
meter: options.meter,
name: "batch-queue",
};
this.fairQueue = new FairQueue(fairQueueOptions);
// Create worker queue manager for consuming from the batch worker queue
this.workerQueueManager = new WorkerQueueManager({
redis: options.redis,
keys: keyProducer,
logger: {
debug: (msg, ctx) => this.logger.debug(msg, ctx),
error: (msg, ctx) => this.logger.error(msg, ctx),
},
});
// Initialize batched span manager for worker queue consumer tracing
this.batchedSpanManager = new BatchedSpanManager({
tracer: options.tracer,
name: "batch-queue-worker",
maxIterations: options.consumerTraceMaxIterations ?? 1000,
timeoutSeconds: options.consumerTraceTimeoutSeconds ?? 60,
});
// Create completion tracker
this.completionTracker = new BatchCompletionTracker({
redis: options.redis,
logger: {
debug: (msg, ctx) => this.logger.debug(msg, ctx),
info: (msg, ctx) => this.logger.info(msg, ctx),
error: (msg, ctx) => this.logger.error(msg, ctx),
},
});
// Register telemetry gauge callbacks for observable metrics
// Note: observedTenants is not provided since tenant list is dynamic
this.fairQueue.registerTelemetryGauges();
if (options.startConsumers !== false) {
this.start();
}
}
// ============================================================================
// Public API - Callbacks
// ============================================================================
/**
* Set the callback for processing batch items.
* This is called for each item dequeued from the batch queue.
*/
onProcessItem(callback: ProcessBatchItemCallback): void {
this.processItemCallback = callback;
}
/**
* Set the callback for batch completion.
* This is called when all items in a batch have been processed.
*/
onBatchComplete(callback: BatchCompletionCallback): void {
this.completionCallback = callback;
}
// ============================================================================
// Public API - Enqueueing (2-Phase API)
// ============================================================================
/**
* Initialize a batch for 2-phase processing (Phase 1).
*
* This stores batch metadata in the completion tracker WITHOUT enqueueing
* any items. Items are streamed separately via enqueueBatchItem().
*
* Use this for the v3 streaming batch API where items are sent via NDJSON stream.
*/
async initializeBatch(options: InitializeBatchOptions): Promise<void> {
const now = Date.now();
// Prepare batch metadata
const meta: BatchMeta = {
batchId: options.batchId,
friendlyId: options.friendlyId,
environmentId: options.environmentId,
environmentType: options.environmentType,
organizationId: options.organizationId,
projectId: options.projectId,
runCount: options.runCount,
createdAt: now,
parentRunId: options.parentRunId,
resumeParentOnCompletion: options.resumeParentOnCompletion,
triggerVersion: options.triggerVersion,
traceContext: options.traceContext,
spanParentAsLink: options.spanParentAsLink,
realtimeStreamsVersion: options.realtimeStreamsVersion,
idempotencyKey: options.idempotencyKey,
processingConcurrency: options.processingConcurrency,
triggerSource: options.triggerSource,
};
// Store metadata in completion tracker
await this.completionTracker.storeMeta(options.batchId, meta);
// Store per-environment concurrency limit if provided
// This is used by the ConcurrencyManager to limit concurrent processing
if (options.processingConcurrency !== undefined) {
await this.storeEnvConcurrency(options.environmentId, options.processingConcurrency);
}
// Record metric
this.batchesEnqueuedCounter?.add(1, {
environment_type: options.environmentType,
streaming: true,
});
this.logger.debug("Batch initialized for streaming", {
batchId: options.batchId,
friendlyId: options.friendlyId,
envId: options.environmentId,
runCount: options.runCount,
processingConcurrency: options.processingConcurrency,
});
}
/**
* Enqueue a single item to an existing batch (Phase 2).
*
* This is used for streaming batch item ingestion in the v3 API.
* Returns whether the item was enqueued (true) or deduplicated (false).
*
* @param batchId - The batch ID (internal format)
* @param envId - The environment ID (needed for queue routing)
* @param itemIndex - Zero-based index of this item
* @param item - The batch item to enqueue
* @returns Object with enqueued status
*/
async enqueueBatchItem(
batchId: string,
envId: string,
itemIndex: number,
item: BatchItem
): Promise<{ enqueued: boolean }> {
// Get batch metadata to verify it exists and get friendlyId
const meta = await this.completionTracker.getMeta(batchId);
if (!meta) {
throw new Error(`Batch ${batchId} not found or not initialized`);
}
// Atomically check and mark as enqueued for idempotency
const isNewItem = await this.completionTracker.markItemEnqueued(batchId, itemIndex);
if (!isNewItem) {
// Item was already enqueued, deduplicate
this.logger.debug("Batch item deduplicated", { batchId, itemIndex });
return { enqueued: false };
}
// Create queue ID in format: env:{envId}:batch:{batchId}
const queueId = this.#makeQueueId(envId, batchId);
// Build message payload
const payload: BatchItemPayload = {
batchId,
friendlyId: meta.friendlyId,
itemIndex,
item,
};
// Enqueue single message
await this.fairQueue.enqueue({
queueId,
tenantId: envId,
payload,
timestamp: meta.createdAt + itemIndex, // Preserve ordering by index
metadata: {
batchId,
friendlyId: meta.friendlyId,
envId,
},
});
// Record metric
this.itemsEnqueuedCounter?.add(1, { environment_type: meta.environmentType });
this.logger.debug("Batch item enqueued", {
batchId,
itemIndex,
task: item.task,
});
return { enqueued: true };
}
/**
* Get the count of items that have been enqueued for a batch.
* Useful for progress tracking during streaming ingestion.
*/
async getEnqueuedCount(batchId: string): Promise<number> {
return this.completionTracker.getEnqueuedCount(batchId);
}
// ============================================================================
// Public API - Query
// ============================================================================
/**
* Get batch metadata.
*/
async getBatchMeta(batchId: string): Promise<BatchMeta | null> {
return this.completionTracker.getMeta(batchId);
}
/**
* Get the number of remaining items in a batch.
*/
async getBatchRemainingCount(batchId: string): Promise<number> {
const meta = await this.completionTracker.getMeta(batchId);
if (!meta) return 0;
const processedCount = await this.completionTracker.getProcessedCount(batchId);
return Math.max(0, meta.runCount - processedCount);
}
/**
* Get the successful runs for a batch.
*/
async getBatchRuns(batchId: string): Promise<string[]> {
return this.completionTracker.getSuccessfulRuns(batchId);
}
/**
* Get the failures for a batch.
*/
async getBatchFailures(batchId: string): Promise<CompleteBatchResult["failures"]> {
return this.completionTracker.getFailures(batchId);
}
/**
* Get the live processed count for a batch from Redis.
* This is useful for displaying real-time progress in the UI.
*/
async getBatchProcessedCount(batchId: string): Promise<number> {
return this.completionTracker.getProcessedCount(batchId);
}
/**
* Get the live progress for a batch from Redis.
* Returns success count, failure count, and processed count.
* This is useful for displaying real-time progress in the UI.
*/
async getBatchProgress(batchId: string): Promise<{
successCount: number;
failureCount: number;
processedCount: number;
}> {
const [successfulRuns, failures, processedCount] = await Promise.all([
this.completionTracker.getSuccessfulRuns(batchId),
this.completionTracker.getFailures(batchId),
this.completionTracker.getProcessedCount(batchId),
]);
return {
successCount: successfulRuns.length,
failureCount: failures.length,
processedCount,
};
}
// ============================================================================
// Public API - Lifecycle
// ============================================================================
/**
* Start the consumer loops.
* FairQueue runs the master queue consumer loop (claim and push to worker queue).
* BatchQueue runs its own worker queue consumer loops to process messages.
*/
start(): void {
if (this.isRunning) {
return;
}
this.isRunning = true;
this.abortController = new AbortController();
// Start FairQueue's master queue consumers (routes messages to worker queue)
this.fairQueue.start();
// Start worker queue consumer loops
for (let consumerId = 0; consumerId < this.options.consumerCount; consumerId++) {
const loop = this.#runWorkerQueueConsumerLoop(consumerId);
this.workerQueueConsumerLoops.push(loop);
}
this.logger.info("BatchQueue consumers started", {
consumerCount: this.options.consumerCount,
intervalMs: this.options.consumerIntervalMs,
drrQuantum: this.options.drr.quantum,
workerQueueId: BATCH_WORKER_QUEUE_ID,
});
}
/**
* Stop the consumer loops gracefully.
*/
async stop(): Promise<void> {
if (!this.isRunning) {
return;
}
this.isRunning = false;
this.abortController.abort();
// Stop FairQueue's master queue consumers
await this.fairQueue.stop();
// Wait for worker queue consumer loops to finish
await Promise.allSettled(this.workerQueueConsumerLoops);
this.workerQueueConsumerLoops = [];
this.logger.info("BatchQueue consumers stopped");
}
/**
* Close the BatchQueue and all Redis connections.
*/
async close(): Promise<void> {
await this.stop();
// Clean up any remaining batched spans (safety net for spans not cleaned up by consumer loops)
this.batchedSpanManager.cleanupAll();
await this.fairQueue.close();
await this.workerQueueManager.close();
await this.completionTracker.close();
await this.concurrencyRedis.quit();
}
// ============================================================================
// Private - Environment Concurrency Management
// ============================================================================
/**
* Store the concurrency limit for an environment.
* This is called when a batch is initialized with a specific concurrency limit.
* The limit expires after 24 hours to prevent stale data.
*/
private async storeEnvConcurrency(envId: string, concurrency: number): Promise<void> {
const key = `${ENV_CONCURRENCY_KEY_PREFIX}:${envId}`;
// Set with 24 hour expiry - batches should complete well before this
await this.concurrencyRedis.set(key, concurrency.toString(), "EX", 86400);
this.logger.debug("Stored environment concurrency limit", { envId, concurrency });
}
/**
* Get the concurrency limit for an environment.
* Returns the stored limit or the default if not set.
*/
private async getEnvConcurrency(envId: string): Promise<number> {
const key = `${ENV_CONCURRENCY_KEY_PREFIX}:${envId}`;
const stored = await this.concurrencyRedis.get(key);
if (stored) {
const limit = parseInt(stored, 10);
if (!isNaN(limit) && limit > 0) {
return limit;
}
}
return this.defaultConcurrency;
}
// ============================================================================
// Private - Metrics Initialization
// ============================================================================
#initializeMetrics(meter: Meter): void {
this.batchesEnqueuedCounter = meter.createCounter("batch_queue.batches_enqueued", {
description: "Number of batches enqueued",
unit: "batches",
});
this.itemsProcessedCounter = meter.createCounter("batch_queue.items_processed", {
description: "Number of batch items successfully processed",
unit: "items",
});
this.itemsFailedCounter = meter.createCounter("batch_queue.items_failed", {
description: "Number of batch items that failed processing",
unit: "items",
});
this.batchCompletedCounter = meter.createCounter("batch_queue.batches_completed", {
description: "Number of batches completed",
unit: "batches",
});
this.batchProcessingDurationHistogram = meter.createHistogram(
"batch_queue.batch_processing_duration",
{
description: "Duration from batch creation to completion",
unit: "ms",
}
);
this.itemsEnqueuedCounter = meter.createCounter("batch_queue.items_enqueued", {
description: "Number of batch items enqueued",
unit: "items",
});
this.itemQueueTimeHistogram = meter.createHistogram("batch_queue.item_queue_time", {
description: "Time from item enqueue to processing start",
unit: "ms",
});
this.rateLimitDeniedCounter = meter.createCounter("batch_queue.rate_limit_denied", {
description: "Number of times the global rate limiter denied processing",
unit: "denials",
});
this.workerQueueLengthGauge = meter.createObservableGauge("batch_queue.worker_queue.length", {
description: "Number of items waiting in the batch worker queue",
unit: "items",
});
this.workerQueueLengthGauge.addCallback(async (observableResult) => {
const length = await this.workerQueueManager.getLength(BATCH_WORKER_QUEUE_ID);
observableResult.observe(length);
});
}
// ============================================================================
// Private - Worker Queue Consumer Loop
// ============================================================================
/**
* Run a worker queue consumer loop.
* This pops messages from the batch worker queue and processes them.
*/
async #runWorkerQueueConsumerLoop(consumerId: number): Promise<void> {
const loopId = `batch-worker-${consumerId}`;
// Initialize batched span tracking for this loop
this.batchedSpanManager.initializeLoop(loopId);
try {
while (this.isRunning) {
if (!this.processItemCallback) {
await new Promise((resolve) => setTimeout(resolve, 100));
continue;
}
try {
// Rate limit per-item at the processing level (1 token per message).
// Loop until allowed so multiple consumers don't all rush through after one sleep.
if (this.globalRateLimiter) {
while (this.isRunning) {
const result = await this.globalRateLimiter.limit();
if (result.allowed) {
break;
}
this.rateLimitDeniedCounter?.add(1);
const waitMs = Math.max(10, (result.resetAt ?? Date.now()) - Date.now());
if (waitMs > 0) {
await new Promise<void>((resolve, reject) => {
const onAbort = () => {
clearTimeout(timer);
reject(this.abortController.signal.reason);
};
const timer = setTimeout(() => {
// Must remove listener when timeout fires, otherwise listeners accumulate
// (the { once: true } option only removes on abort, not on timeout)
this.abortController.signal.removeEventListener("abort", onAbort);
resolve();
}, waitMs);
if (this.abortController.signal.aborted) {
clearTimeout(timer);
reject(this.abortController.signal.reason);
return;
}
this.abortController.signal.addEventListener("abort", onAbort, { once: true });
});
}
}
if (!this.isRunning) {
break;
}
}
await this.batchedSpanManager.withBatchedSpan(
loopId,
async (span) => {
span.setAttribute("consumer_id", consumerId);
// Blocking pop from worker queue
const messageKey = await this.workerQueueManager.blockingPop(
BATCH_WORKER_QUEUE_ID,
this.workerQueueBlockingTimeoutSeconds,
this.abortController.signal
);
if (!messageKey) {
this.batchedSpanManager.incrementStat(loopId, "empty_iterations");
return false; // Timeout, no work
}
// Parse message key (format: "messageId:queueId")
const colonIndex = messageKey.indexOf(":");
if (colonIndex === -1) {
this.logger.error("Invalid message key format", { messageKey });
this.batchedSpanManager.incrementStat(loopId, "invalid_message_keys");
return false;
}
const messageId = messageKey.substring(0, colonIndex);
const queueId = messageKey.substring(colonIndex + 1);
await this.#handleMessage(loopId, messageId, queueId);
this.batchedSpanManager.incrementStat(loopId, "messages_processed");
return true; // Had work
},
{
iterationSpanName: "processWorkerQueueMessage",
attributes: { consumer_id: consumerId },
}
);
} catch (error) {
if (this.abortController.signal.aborted) {
break;
}
this.logger.error("Worker queue consumer error", {
loopId,
error: error instanceof Error ? error.message : String(error),
});
this.batchedSpanManager.markForRotation(loopId);
}
}
} catch (error) {
if (isAbortError(error)) {
this.logger.debug("Worker queue consumer aborted", { loopId });
this.batchedSpanManager.cleanup(loopId);
return;
}
throw error;
} finally {
this.batchedSpanManager.cleanup(loopId);
}
}
// ============================================================================
// Private - Message Handling
// ============================================================================
async #handleMessage(consumerId: string, messageId: string, queueId: string): Promise<void> {
// Get message data from FairQueue's in-flight storage
const storedMessage = await this.fairQueue.getMessageData(messageId, queueId);
if (!storedMessage) {
this.logger.error("Message not found in in-flight data", { messageId, queueId });
await this.fairQueue.completeMessage(messageId, queueId);
return;
}
const { batchId, friendlyId, itemIndex, item } = storedMessage.payload;
return this.#startSpan("BatchQueue.handleMessage", async (span) => {
span?.setAttributes({
"batch.id": batchId,
"batch.friendlyId": friendlyId,
"batch.itemIndex": itemIndex,
"batch.task": item.task,
"batch.consumerId": consumerId,
"batch.attempt": storedMessage.attempt,
});
// Calculate queue time (time from enqueue to processing)
const queueTimeMs = Date.now() - storedMessage.timestamp;
span?.setAttribute("batch.queueTimeMs", queueTimeMs);
this.logger.debug("Processing batch item", {
batchId,
friendlyId,
itemIndex,
task: item.task,
consumerId,
attempt: storedMessage.attempt,
queueTimeMs,
});
if (!this.processItemCallback) {
this.logger.error("No process item callback set", { batchId, itemIndex });
// Still complete the message to avoid blocking
await this.fairQueue.completeMessage(messageId, queueId);
return;
}
// Get batch metadata
const meta = await this.#startSpan("BatchQueue.getMeta", async () => {
return this.completionTracker.getMeta(batchId);
});
if (!meta) {
this.logger.error("Batch metadata not found", { batchId, itemIndex });
await this.fairQueue.completeMessage(messageId, queueId);
return;
}
// Record queue time metric (requires meta for environment_type)
this.itemQueueTimeHistogram?.record(queueTimeMs, { environment_type: meta.environmentType });
span?.setAttributes({
"batch.runCount": meta.runCount,
"batch.environmentId": meta.environmentId,
});
const attempt = storedMessage.attempt;
const isFinalAttempt = attempt >= this.maxAttempts;
let processedCount: number;
try {
const result = await this.#startSpan(
"BatchQueue.processItemCallback",
async (innerSpan) => {
innerSpan?.setAttributes({
"batch.id": batchId,
"batch.itemIndex": itemIndex,
"batch.task": item.task,
});
return this.processItemCallback!({
batchId,
friendlyId,
itemIndex,
item,
meta,
attempt,
isFinalAttempt,
});
}
);
if (result.success) {
span?.setAttribute("batch.result", "success");
span?.setAttribute("batch.runId", result.runId);
// Pass itemIndex for idempotency - prevents double-counting on redelivery
processedCount = await this.#startSpan("BatchQueue.recordSuccess", async () => {
return this.completionTracker.recordSuccess(batchId, result.runId, itemIndex);
});
this.itemsProcessedCounter?.add(1, { environment_type: meta.environmentType });
this.logger.debug("Batch item processed successfully", {
batchId,
itemIndex,
runId: result.runId,
processedCount,
expectedCount: meta.runCount,
attempt,
});
} else {
span?.setAttribute("batch.result", "failure");
span?.setAttribute("batch.error", result.error);
if (result.errorCode) {
span?.setAttribute("batch.errorCode", result.errorCode);
}
// If retries are available, use FairQueue retry scheduling
if (!isFinalAttempt) {
span?.setAttribute("batch.retry", true);
span?.setAttribute("batch.attempt", attempt);
this.logger.warn("Batch item failed, scheduling retry via FairQueue", {
batchId,
itemIndex,
attempt,
maxAttempts: this.maxAttempts,
error: result.error,
});
await this.#startSpan("BatchQueue.failMessage", async () => {
return this.fairQueue.failMessage(
messageId,
queueId,
new Error(result.error)
);
});
// Don't record failure or check completion - message will be retried
return;
}
// Final attempt exhausted - record permanent failure
const payloadStr = await this.#startSpan(
"BatchQueue.serializePayload",
async (innerSpan) => {
const str =
item.payload === undefined || item.payload === null
? "{}"
: typeof item.payload === "string"
? item.payload
: JSON.stringify(item.payload);
innerSpan?.setAttribute("batch.payloadSize", str.length);
return str;
}
);
processedCount = await this.#startSpan("BatchQueue.recordFailure", async () => {
return this.completionTracker.recordFailure(batchId, {
index: itemIndex,
taskIdentifier: item.task,
payload: payloadStr,
options: item.options,
error: result.error,
errorCode: result.errorCode,
});
});
this.itemsFailedCounter?.add(1, {
environment_type: meta.environmentType,
errorCode: result.errorCode,
});
this.logger.error("Batch item processing failed after all attempts", {
batchId,
itemIndex,
error: result.error,
processedCount,
expectedCount: meta.runCount,
attempts: attempt,
});
}
} catch (error) {
span?.setAttribute("batch.result", "unexpected_error");
span?.setAttribute("batch.error", error instanceof Error ? error.message : String(error));
// If retries are available, use FairQueue retry scheduling for unexpected errors too
if (!isFinalAttempt) {
span?.setAttribute("batch.retry", true);
span?.setAttribute("batch.attempt", attempt);
this.logger.warn("Batch item threw unexpected error, scheduling retry", {
batchId,
itemIndex,
attempt,
maxAttempts: this.maxAttempts,
error: error instanceof Error ? error.message : String(error),
});
await this.#startSpan("BatchQueue.failMessage", async () => {
return this.fairQueue.failMessage(
messageId,
queueId,
error instanceof Error ? error : new Error(String(error))
);
});
return;
}
// Final attempt - record permanent failure
const payloadStr = await this.#startSpan(
"BatchQueue.serializePayload",
async (innerSpan) => {
const str =
item.payload === undefined || item.payload === null
? "{}"
: typeof item.payload === "string"
? item.payload
: JSON.stringify(item.payload);
innerSpan?.setAttribute("batch.payloadSize", str.length);
return str;
}
);
processedCount = await this.#startSpan("BatchQueue.recordFailure", async () => {
return this.completionTracker.recordFailure(batchId, {
index: itemIndex,
taskIdentifier: item.task,
payload: payloadStr,
options: item.options,
error: error instanceof Error ? error.message : String(error),
errorCode: "UNEXPECTED_ERROR",
});
});
this.itemsFailedCounter?.add(1, {
environment_type: meta.environmentType,
errorCode: "UNEXPECTED_ERROR",
});
this.logger.error("Unexpected error processing batch item after all attempts", {
batchId,
itemIndex,
error: error instanceof Error ? error.message : String(error),
processedCount,
expectedCount: meta.runCount,
attempts: attempt,
});
}