-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathindex.ts
More file actions
1970 lines (1718 loc) · 63 KB
/
index.ts
File metadata and controls
1970 lines (1718 loc) · 63 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, type RedisOptions } from "@internal/redis";
import { SpanKind, type Span } from "@internal/tracing";
import { Logger } from "@trigger.dev/core/logger";
import { nanoid } from "nanoid";
import { setInterval } from "node:timers/promises";
import { type z } from "zod";
import { ConcurrencyManager } from "./concurrency.js";
import { MasterQueue } from "./masterQueue.js";
import { TenantDispatch } from "./tenantDispatch.js";
import { type RetryStrategy, ExponentialBackoffRetry } from "./retry.js";
import { isAbortError } from "../utils.js";
import {
FairQueueTelemetry,
FairQueueAttributes,
MessagingAttributes,
BatchedSpanManager,
} from "./telemetry.js";
import type {
ConcurrencyGroupConfig,
DeadLetterMessage,
DispatchSchedulerContext,
EnqueueBatchOptions,
EnqueueOptions,
FairQueueKeyProducer,
FairQueueOptions,
FairScheduler,
GlobalRateLimiter,
QueueCooloffState,
QueueDescriptor,
SchedulerContext,
StoredMessage,
TenantQueues,
} from "./types.js";
import { VisibilityManager } from "./visibility.js";
import { WorkerQueueManager } from "./workerQueue.js";
// Re-export all types and components
export * from "./types.js";
export * from "./keyProducer.js";
export * from "./masterQueue.js";
export * from "./concurrency.js";
export * from "./visibility.js";
export * from "./workerQueue.js";
export * from "./scheduler.js";
export * from "./schedulers/index.js";
export * from "./retry.js";
export * from "./telemetry.js";
export * from "./tenantDispatch.js";
/**
* FairQueue is the main orchestrator for fair queue message routing.
*
* FairQueue handles:
* - Master queue with sharding (using jump consistent hash)
* - Fair scheduling via pluggable schedulers
* - Multi-level concurrency limiting
* - Visibility timeouts with heartbeats
* - Routing messages to worker queues
* - Retry strategies with dead letter queue
* - OpenTelemetry tracing and metrics
*
* External consumers are responsible for:
* - Running their own worker queue consumer loops
* - Calling complete/release/fail APIs after processing
*
* @typeParam TPayloadSchema - Zod schema for message payload validation
*/
export class FairQueue<TPayloadSchema extends z.ZodTypeAny = z.ZodUnknown> {
private redis: Redis;
private keys: FairQueueKeyProducer;
private scheduler: FairScheduler;
private masterQueue: MasterQueue;
private concurrencyManager?: ConcurrencyManager;
private visibilityManager: VisibilityManager;
private workerQueueManager: WorkerQueueManager;
private telemetry: FairQueueTelemetry;
private logger: Logger;
// Configuration
private payloadSchema?: TPayloadSchema;
private validateOnEnqueue: boolean;
private retryStrategy?: RetryStrategy;
private deadLetterQueueEnabled: boolean;
private shardCount: number;
private consumerCount: number;
private consumerIntervalMs: number;
private visibilityTimeoutMs: number;
private heartbeatIntervalMs: number;
private reclaimIntervalMs: number;
private workerQueueResolver: (message: StoredMessage<z.infer<TPayloadSchema>>) => string;
private batchClaimSize: number;
// Cooloff state
private cooloffEnabled: boolean;
private cooloffThreshold: number;
private cooloffPeriodMs: number;
private maxCooloffStatesSize: number;
private queueCooloffStates = new Map<string, QueueCooloffState>();
// Global rate limiter
private globalRateLimiter?: GlobalRateLimiter;
// Consumer tracing
private consumerTraceMaxIterations: number;
private consumerTraceTimeoutSeconds: number;
private batchedSpanManager: BatchedSpanManager;
// Runtime state
private isRunning = false;
private abortController: AbortController;
private masterQueueConsumerLoops: Promise<void>[] = [];
private reclaimLoop?: Promise<void>;
// Queue descriptor cache for message processing
private queueDescriptorCache = new Map<string, QueueDescriptor>();
// Two-level tenant dispatch
private tenantDispatch: TenantDispatch;
constructor(private options: FairQueueOptions<TPayloadSchema>) {
this.redis = createRedisClient(options.redis);
this.keys = options.keys;
this.scheduler = options.scheduler;
this.logger = options.logger ?? new Logger("FairQueue", "info");
this.abortController = new AbortController();
// Payload validation
this.payloadSchema = options.payloadSchema;
this.validateOnEnqueue = options.validateOnEnqueue ?? false;
// Retry and DLQ
this.retryStrategy = options.retry?.strategy;
this.deadLetterQueueEnabled = options.retry?.deadLetterQueue ?? true;
// Configuration
this.shardCount = options.shardCount ?? 1;
this.consumerCount = options.consumerCount ?? 1;
this.consumerIntervalMs = options.consumerIntervalMs ?? 100;
this.visibilityTimeoutMs = options.visibilityTimeoutMs ?? 30_000;
this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? this.visibilityTimeoutMs / 3;
this.reclaimIntervalMs = options.reclaimIntervalMs ?? 5_000;
// Worker queue resolver (required)
this.workerQueueResolver = options.workerQueue.resolveWorkerQueue;
// Batch claiming
this.batchClaimSize = options.batchClaimSize ?? 10;
// Cooloff
this.cooloffEnabled = options.cooloff?.enabled ?? true;
this.cooloffThreshold = options.cooloff?.threshold ?? 10;
this.cooloffPeriodMs = options.cooloff?.periodMs ?? 10_000;
this.maxCooloffStatesSize = options.cooloff?.maxStatesSize ?? 1000;
// Global rate limiter
this.globalRateLimiter = options.globalRateLimiter;
// Consumer tracing
this.consumerTraceMaxIterations = options.consumerTraceMaxIterations ?? 500;
this.consumerTraceTimeoutSeconds = options.consumerTraceTimeoutSeconds ?? 60;
// Initialize telemetry
this.telemetry = new FairQueueTelemetry({
tracer: options.tracer,
meter: options.meter,
name: options.name ?? "fairqueue",
});
// Initialize batched span manager for consumer tracing
this.batchedSpanManager = new BatchedSpanManager({
tracer: options.tracer,
name: options.name ?? "fairqueue",
maxIterations: this.consumerTraceMaxIterations,
timeoutSeconds: this.consumerTraceTimeoutSeconds,
getDynamicAttributes: () => ({
"cache.descriptor_size": this.queueDescriptorCache.size,
"cache.cooloff_states_size": this.queueCooloffStates.size,
}),
});
// Initialize components
this.masterQueue = new MasterQueue({
redis: options.redis,
keys: options.keys,
shardCount: this.shardCount,
});
this.tenantDispatch = new TenantDispatch({
redis: options.redis,
keys: options.keys,
shardCount: this.shardCount,
});
if (options.concurrencyGroups && options.concurrencyGroups.length > 0) {
this.concurrencyManager = new ConcurrencyManager({
redis: options.redis,
keys: options.keys,
groups: options.concurrencyGroups,
});
}
this.visibilityManager = new VisibilityManager({
redis: options.redis,
keys: options.keys,
shardCount: this.shardCount,
defaultTimeoutMs: this.visibilityTimeoutMs,
logger: {
debug: (msg, ctx) => this.logger.debug(msg, ctx),
error: (msg, ctx) => this.logger.error(msg, ctx),
},
});
// Worker queue manager for pushing messages to worker queues
this.workerQueueManager = new WorkerQueueManager({
redis: options.redis,
keys: options.keys,
logger: {
debug: (msg, ctx) => this.logger.debug(msg, ctx),
error: (msg, ctx) => this.logger.error(msg, ctx),
},
});
this.#registerCommands();
// Auto-start consumers if not disabled
if (options.startConsumers !== false) {
this.start();
}
}
// ============================================================================
// Public API - Telemetry
// ============================================================================
/**
* Register observable gauge callbacks for telemetry.
* Call this after FairQueue is created to enable gauge metrics.
*
* @param options.observedTenants - List of tenant IDs to observe for DLQ metrics
*/
registerTelemetryGauges(options?: { observedTenants?: string[] }): void {
this.telemetry.registerGaugeCallbacks({
getMasterQueueLength: async (shardId: number) => {
return await this.masterQueue.getShardQueueCount(shardId);
},
getDispatchLength: async (shardId: number) => {
return await this.tenantDispatch.getShardTenantCount(shardId);
},
getInflightCount: async (shardId: number) => {
return await this.visibilityManager.getInflightCount(shardId);
},
getDLQLength: async (tenantId: string) => {
return await this.getDeadLetterQueueLength(tenantId);
},
shardCount: this.shardCount,
observedTenants: options?.observedTenants,
});
}
// ============================================================================
// Public API - Enqueueing
// ============================================================================
/**
* Enqueue a single message to a queue.
*/
async enqueue(options: EnqueueOptions<z.infer<TPayloadSchema>>): Promise<string> {
return this.telemetry.trace(
"enqueue",
async (span) => {
const messageId = options.messageId ?? nanoid();
const timestamp = options.timestamp ?? Date.now();
const queueKey = this.keys.queueKey(options.queueId);
const queueItemsKey = this.keys.queueItemsKey(options.queueId);
const shardId = this.masterQueue.getShardForQueue(options.queueId);
const tenantQueueIndexKey = this.keys.tenantQueueIndexKey(options.tenantId);
const dispatchKey = this.keys.dispatchKey(shardId);
// Validate payload if schema provided and validation enabled
if (this.validateOnEnqueue && this.payloadSchema) {
const result = this.payloadSchema.safeParse(options.payload);
if (!result.success) {
throw new Error(`Payload validation failed: ${result.error.message}`);
}
}
// Store queue descriptor for later use
const descriptor: QueueDescriptor = {
id: options.queueId,
tenantId: options.tenantId,
metadata: options.metadata ?? {},
};
this.queueDescriptorCache.set(options.queueId, descriptor);
// Build stored message
const storedMessage: StoredMessage<z.infer<TPayloadSchema>> = {
id: messageId,
queueId: options.queueId,
tenantId: options.tenantId,
payload: options.payload,
timestamp,
attempt: 1,
workerQueue: this.workerQueueResolver
? this.workerQueueResolver({
id: messageId,
queueId: options.queueId,
tenantId: options.tenantId,
payload: options.payload,
timestamp,
attempt: 1,
metadata: options.metadata,
})
: undefined,
metadata: options.metadata,
};
// Use atomic Lua script to enqueue and update tenant dispatch indexes
await this.redis.enqueueMessageAtomicV2(
queueKey,
queueItemsKey,
tenantQueueIndexKey,
dispatchKey,
options.queueId,
messageId,
timestamp.toString(),
JSON.stringify(storedMessage),
options.tenantId
);
span.setAttributes({
[FairQueueAttributes.QUEUE_ID]: options.queueId,
[FairQueueAttributes.TENANT_ID]: options.tenantId,
[FairQueueAttributes.MESSAGE_ID]: messageId,
[FairQueueAttributes.SHARD_ID]: shardId.toString(),
});
this.telemetry.recordEnqueue();
this.logger.debug("Message enqueued", {
queueId: options.queueId,
messageId,
timestamp,
});
return messageId;
},
{
kind: SpanKind.PRODUCER,
attributes: {
[MessagingAttributes.OPERATION]: "publish",
},
}
);
}
/**
* Enqueue multiple messages to a queue.
*/
async enqueueBatch(options: EnqueueBatchOptions<z.infer<TPayloadSchema>>): Promise<string[]> {
return this.telemetry.trace(
"enqueueBatch",
async (span) => {
const queueKey = this.keys.queueKey(options.queueId);
const queueItemsKey = this.keys.queueItemsKey(options.queueId);
const shardId = this.masterQueue.getShardForQueue(options.queueId);
const tenantQueueIndexKey = this.keys.tenantQueueIndexKey(options.tenantId);
const dispatchKey = this.keys.dispatchKey(shardId);
const now = Date.now();
// Store queue descriptor
const descriptor: QueueDescriptor = {
id: options.queueId,
tenantId: options.tenantId,
metadata: options.metadata ?? {},
};
this.queueDescriptorCache.set(options.queueId, descriptor);
const messageIds: string[] = [];
const args: string[] = [];
for (const message of options.messages) {
const messageId = message.messageId ?? nanoid();
const timestamp = message.timestamp ?? now;
// Validate if enabled
if (this.validateOnEnqueue && this.payloadSchema) {
const result = this.payloadSchema.safeParse(message.payload);
if (!result.success) {
throw new Error(
`Payload validation failed for message ${messageId}: ${result.error.message}`
);
}
}
const storedMessage: StoredMessage<z.infer<TPayloadSchema>> = {
id: messageId,
queueId: options.queueId,
tenantId: options.tenantId,
payload: message.payload,
timestamp,
attempt: 1,
workerQueue: this.workerQueueResolver
? this.workerQueueResolver({
id: messageId,
queueId: options.queueId,
tenantId: options.tenantId,
payload: message.payload,
timestamp,
attempt: 1,
metadata: options.metadata,
})
: undefined,
metadata: options.metadata,
};
messageIds.push(messageId);
args.push(messageId, timestamp.toString(), JSON.stringify(storedMessage));
}
// Use atomic Lua script for batch enqueue with tenant dispatch indexes
await this.redis.enqueueBatchAtomicV2(
queueKey,
queueItemsKey,
tenantQueueIndexKey,
dispatchKey,
options.queueId,
options.tenantId,
...args
);
span.setAttributes({
[FairQueueAttributes.QUEUE_ID]: options.queueId,
[FairQueueAttributes.TENANT_ID]: options.tenantId,
[FairQueueAttributes.MESSAGE_COUNT]: messageIds.length,
[FairQueueAttributes.SHARD_ID]: shardId.toString(),
});
this.telemetry.recordEnqueueBatch(messageIds.length);
this.logger.debug("Batch enqueued", {
queueId: options.queueId,
messageCount: messageIds.length,
});
return messageIds;
},
{
kind: SpanKind.PRODUCER,
attributes: {
[MessagingAttributes.OPERATION]: "publish",
},
}
);
}
// ============================================================================
// Public API - Dead Letter Queue
// ============================================================================
/**
* Get messages from the dead letter queue for a tenant.
*/
async getDeadLetterMessages(
tenantId: string,
limit: number = 100
): Promise<DeadLetterMessage<z.infer<TPayloadSchema>>[]> {
if (!this.deadLetterQueueEnabled) {
return [];
}
const dlqKey = this.keys.deadLetterQueueKey(tenantId);
const dlqDataKey = this.keys.deadLetterQueueDataKey(tenantId);
// Get message IDs with scores (deadLetteredAt timestamps)
const results = await this.redis.zrange(dlqKey, 0, limit - 1, "WITHSCORES");
const messages: DeadLetterMessage<z.infer<TPayloadSchema>>[] = [];
for (let i = 0; i < results.length; i += 2) {
const messageId = results[i];
const deadLetteredAtStr = results[i + 1];
if (!messageId || !deadLetteredAtStr) continue;
const dataJson = await this.redis.hget(dlqDataKey, messageId);
if (!dataJson) continue;
try {
const data = JSON.parse(dataJson) as DeadLetterMessage<z.infer<TPayloadSchema>>;
data.deadLetteredAt = parseFloat(deadLetteredAtStr);
messages.push(data);
} catch {
this.logger.error("Failed to parse DLQ message", { messageId, tenantId });
}
}
return messages;
}
/**
* Redrive a message from DLQ back to its original queue.
*/
async redriveMessage(tenantId: string, messageId: string): Promise<boolean> {
if (!this.deadLetterQueueEnabled) {
return false;
}
return this.telemetry.trace(
"redriveMessage",
async (span) => {
const dlqKey = this.keys.deadLetterQueueKey(tenantId);
const dlqDataKey = this.keys.deadLetterQueueDataKey(tenantId);
// Get the message data
const dataJson = await this.redis.hget(dlqDataKey, messageId);
if (!dataJson) {
return false;
}
const dlqMessage = JSON.parse(dataJson) as DeadLetterMessage<z.infer<TPayloadSchema>>;
// Re-enqueue with reset attempt count
await this.enqueue({
queueId: dlqMessage.queueId,
tenantId: dlqMessage.tenantId,
payload: dlqMessage.payload,
messageId: dlqMessage.id,
timestamp: Date.now(),
});
// Remove from DLQ
const pipeline = this.redis.pipeline();
pipeline.zrem(dlqKey, messageId);
pipeline.hdel(dlqDataKey, messageId);
await pipeline.exec();
span.setAttributes({
[FairQueueAttributes.TENANT_ID]: tenantId,
[FairQueueAttributes.MESSAGE_ID]: messageId,
});
this.logger.info("Redrived message from DLQ", { tenantId, messageId });
return true;
},
{
kind: SpanKind.PRODUCER,
attributes: {
[MessagingAttributes.OPERATION]: "redrive",
},
}
);
}
/**
* Redrive all messages from DLQ back to their original queues.
*/
async redriveAll(tenantId: string): Promise<number> {
const messages = await this.getDeadLetterMessages(tenantId, 1000);
let count = 0;
for (const message of messages) {
const success = await this.redriveMessage(tenantId, message.id);
if (success) count++;
}
return count;
}
/**
* Purge all messages from a tenant's DLQ.
*/
async purgeDeadLetterQueue(tenantId: string): Promise<number> {
if (!this.deadLetterQueueEnabled) {
return 0;
}
const dlqKey = this.keys.deadLetterQueueKey(tenantId);
const dlqDataKey = this.keys.deadLetterQueueDataKey(tenantId);
const count = await this.redis.zcard(dlqKey);
const pipeline = this.redis.pipeline();
pipeline.del(dlqKey);
pipeline.del(dlqDataKey);
await pipeline.exec();
this.logger.info("Purged DLQ", { tenantId, count });
return count;
}
/**
* Get the number of messages in a tenant's DLQ.
*/
async getDeadLetterQueueLength(tenantId: string): Promise<number> {
if (!this.deadLetterQueueEnabled) {
return 0;
}
const dlqKey = this.keys.deadLetterQueueKey(tenantId);
return await this.redis.zcard(dlqKey);
}
/**
* Get the size of the in-memory queue descriptor cache.
* This cache stores metadata for queues that have been enqueued.
* The cache is cleaned up when queues are fully processed.
*/
getQueueDescriptorCacheSize(): number {
return this.queueDescriptorCache.size;
}
/**
* Get the size of the in-memory cooloff states cache.
* This cache tracks queues that are in cooloff due to repeated failures.
* The cache is cleaned up when queues are fully processed or cooloff expires.
*/
getQueueCooloffStatesSize(): number {
return this.queueCooloffStates.size;
}
/**
* Get all in-memory cache sizes for monitoring.
* Useful for adding as span attributes.
*/
getCacheSizes(): { descriptorCacheSize: number; cooloffStatesSize: number } {
return {
descriptorCacheSize: this.queueDescriptorCache.size,
cooloffStatesSize: this.queueCooloffStates.size,
};
}
// ============================================================================
// Public API - Lifecycle
// ============================================================================
/**
* Start the master queue consumer loops and reclaim loop.
* FairQueue claims messages and pushes them to worker queues.
* External consumers are responsible for consuming from worker queues.
*/
start(): void {
if (this.isRunning) {
return;
}
this.isRunning = true;
this.abortController = new AbortController();
// Start master queue consumers (one per shard)
// These claim messages from queues and push to worker queues
for (let shardId = 0; shardId < this.shardCount; shardId++) {
const loop = this.#runMasterQueueConsumerLoop(shardId);
this.masterQueueConsumerLoops.push(loop);
}
// Start reclaim loop for handling timed-out messages
this.reclaimLoop = this.#runReclaimLoop();
this.logger.info("FairQueue started", {
consumerCount: this.consumerCount,
shardCount: this.shardCount,
consumerIntervalMs: this.consumerIntervalMs,
});
}
/**
* Stop the consumer loops gracefully.
*/
async stop(): Promise<void> {
if (!this.isRunning) {
return;
}
this.isRunning = false;
this.abortController.abort();
await Promise.allSettled([...this.masterQueueConsumerLoops, this.reclaimLoop]);
this.masterQueueConsumerLoops = [];
this.reclaimLoop = undefined;
this.logger.info("FairQueue stopped");
}
/**
* Close all resources.
*/
async close(): Promise<void> {
await this.stop();
// Clean up any remaining batched spans
this.batchedSpanManager.cleanupAll();
await Promise.all([
this.masterQueue.close(),
this.tenantDispatch.close(),
this.concurrencyManager?.close(),
this.visibilityManager.close(),
this.workerQueueManager.close(),
this.scheduler.close?.(),
this.redis.quit(),
]);
}
// ============================================================================
// Public API - Inspection
// ============================================================================
/**
* Get the number of messages in a queue.
*/
async getQueueLength(queueId: string): Promise<number> {
const queueKey = this.keys.queueKey(queueId);
return await this.redis.zcard(queueKey);
}
/**
* Get total queue count across all shards.
*/
async getTotalQueueCount(): Promise<number> {
// Count from new dispatch index (primary) + legacy master queue (drain)
const [dispatchCount, legacyCount] = await Promise.all([
this.tenantDispatch.getTotalTenantCount(),
this.masterQueue.getTotalQueueCount(),
]);
// During migration, dispatch has tenant count (not queue count).
// For a more accurate queue count, we'd need to sum per-tenant queue counts.
// For now, return the dispatch tenant count + any legacy queues still draining.
return dispatchCount + legacyCount;
}
/**
* Get total in-flight message count.
*/
async getTotalInflightCount(): Promise<number> {
return await this.visibilityManager.getTotalInflightCount();
}
/**
* Get the shard ID for a queue.
*/
getShardForQueue(queueId: string): number {
return this.masterQueue.getShardForQueue(queueId);
}
// ============================================================================
// Private - Master Queue Consumer Loop (Two-Stage)
// ============================================================================
async #runMasterQueueConsumerLoop(shardId: number): Promise<void> {
const loopId = `master-shard-${shardId}`;
// Initialize batched span tracking for this loop
this.batchedSpanManager.initializeLoop(loopId);
try {
while (this.isRunning) {
// Check abort signal
if (this.abortController.signal.aborted) {
break;
}
let hadWork = false;
try {
hadWork = await this.batchedSpanManager.withBatchedSpan(
loopId,
async (span) => {
span.setAttribute("shard_id", shardId);
return await this.#processShardIteration(loopId, shardId, span);
},
{
iterationSpanName: "processMasterQueueShard",
attributes: { shard_id: shardId },
}
);
} catch (error) {
this.logger.error("Master queue consumer error", {
loopId,
shardId,
error: error instanceof Error ? error.message : String(error),
});
this.batchedSpanManager.markForRotation(loopId);
}
// Wait between iterations to prevent CPU spin
// Short delay when there's work (yield to event loop), longer delay when idle
const waitMs = hadWork ? 1 : this.consumerIntervalMs;
await new Promise<void>((resolve, reject) => {
const abortHandler = () => {
clearTimeout(timeout);
reject(new Error("AbortError"));
};
const timeout = 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", abortHandler);
resolve();
}, waitMs);
this.abortController.signal.addEventListener("abort", abortHandler, { once: true });
});
}
} catch (error) {
if (isAbortError(error)) {
this.logger.debug("Master queue consumer aborted", { loopId });
this.batchedSpanManager.cleanup(loopId);
return;
}
throw error;
} finally {
this.batchedSpanManager.cleanup(loopId);
}
}
/**
* Process a shard iteration. Runs both the new tenant dispatch path
* and the legacy master queue drain path.
*/
async #processShardIteration(
loopId: string,
shardId: number,
parentSpan?: Span
): Promise<boolean> {
let hadWork = false;
// Main path: new two-level tenant dispatch (gets full DRR scheduling)
hadWork = await this.#processDispatchShard(loopId, shardId, parentSpan);
// Drain path: legacy master queue (simple scheduling, no DRR)
// Check ZCARD first (O(1)) to skip the drain path when empty
const legacyCount = await this.masterQueue.getShardQueueCount(shardId);
if (legacyCount > 0) {
const drainHadWork = await this.#drainLegacyMasterQueueShard(loopId, shardId, parentSpan);
hadWork = hadWork || drainHadWork;
}
return hadWork;
}
/**
* Main path: process queues using the two-level tenant dispatch index.
* Level 1: dispatch index → tenantIds. Level 2: per-tenant → queueIds.
*/
async #processDispatchShard(
loopId: string,
shardId: number,
parentSpan?: Span
): Promise<boolean> {
const dispatchKey = this.keys.dispatchKey(shardId);
// Get dispatch index size for observability
const dispatchSize = await this.tenantDispatch.getShardTenantCount(shardId);
parentSpan?.setAttribute("dispatch_size", dispatchSize);
this.batchedSpanManager.incrementStat(loopId, "dispatch_size_sum", dispatchSize);
// Create dispatch-aware scheduler context
const schedulerContext: DispatchSchedulerContext = {
...this.#createSchedulerContext(),
getQueuesForTenant: async (tenantId: string) => {
return this.tenantDispatch.getQueuesForTenant(tenantId);
},
};
// Get queues to process from scheduler
let tenantQueues: TenantQueues[];
if (this.scheduler.selectQueuesFromDispatch) {
// Use dispatch-aware scheduler method (DRR with two-level lookup)
tenantQueues = await this.telemetry.trace(
"selectQueuesFromDispatch",
async (span) => {
span.setAttribute(FairQueueAttributes.SHARD_ID, shardId.toString());
span.setAttribute(FairQueueAttributes.CONSUMER_ID, loopId);
span.setAttribute("dispatch_size", dispatchSize);
const result = await this.scheduler.selectQueuesFromDispatch!(
dispatchKey,
loopId,
schedulerContext
);
span.setAttribute("tenant_count", result.length);
span.setAttribute(
"queue_count",
result.reduce((acc, t) => acc + t.queues.length, 0)
);
return result;
},
{ kind: SpanKind.INTERNAL }
);
} else {
// Fallback: read dispatch index, build flat queue list, use legacy selectQueues
tenantQueues = await this.#fallbackDispatchToLegacyScheduler(
loopId,
shardId,
schedulerContext,
parentSpan
);
}
if (tenantQueues.length === 0) {
this.batchedSpanManager.incrementStat(loopId, "empty_iterations");
return false;
}
return this.#processSelectedQueues(loopId, shardId, tenantQueues);
}
/**
* Drain path: process remaining messages from the legacy master queue shard.
* Uses simple ZRANGEBYSCORE without DRR - just flushing pre-deploy messages.
*/
async #drainLegacyMasterQueueShard(
loopId: string,
shardId: number,
parentSpan?: Span
): Promise<boolean> {
const masterQueueKey = this.keys.masterQueueKey(shardId);
const now = Date.now();
// Simple fetch from old master queue - no DRR needed for drain
const results = await this.redis.zrangebyscore(
masterQueueKey,
"-inf",
now,
"WITHSCORES",
"LIMIT",
0,
100
);
if (results.length === 0) {
return false;
}
// Parse results into QueueWithScore, group by tenant
const byTenant = new Map<string, string[]>();
for (let i = 0; i < results.length; i += 2) {
const queueId = results[i];
const _score = results[i + 1];
if (queueId && _score) {
const tenantId = this.keys.extractTenantId(queueId);
const existing = byTenant.get(tenantId) ?? [];
existing.push(queueId);
byTenant.set(tenantId, existing);
}
}
// Build TenantQueues, filter at-capacity tenants
const tenantQueues: TenantQueues[] = [];
for (const [tenantId, queueIds] of byTenant) {
if (this.concurrencyManager) {
const atCapacity = await this.concurrencyManager.isAtCapacity("tenant", tenantId);
if (atCapacity) continue;
}
tenantQueues.push({ tenantId, queues: queueIds });
}
if (tenantQueues.length === 0) {
return false;
}
parentSpan?.setAttribute("drain_tenants", tenantQueues.length);
this.batchedSpanManager.incrementStat(loopId, "drain_tenants", tenantQueues.length);
return this.#processSelectedQueues(loopId, shardId, tenantQueues);
}
/**
* Fallback for schedulers that don't implement selectQueuesFromDispatch.
* Reads dispatch index, fetches per-tenant queues, groups by tenant,
* and filters at-capacity tenants. No DRR deficit tracking in this path.
*/
async #fallbackDispatchToLegacyScheduler(
loopId: string,
shardId: number,
context: DispatchSchedulerContext,
parentSpan?: Span
): Promise<TenantQueues[]> {
// Get tenants from dispatch
const tenants = await this.tenantDispatch.getTenantsFromShard(shardId);
if (tenants.length === 0) return [];
// For each tenant, get their queues and build grouped result
const tenantQueues: TenantQueues[] = [];
for (const { tenantId } of tenants) {
if (this.concurrencyManager) {
const atCapacity = await this.concurrencyManager.isAtCapacity("tenant", tenantId);
if (atCapacity) continue;
}
const queues = await this.tenantDispatch.getQueuesForTenant(tenantId);
if (queues.length > 0) {
tenantQueues.push({ tenantId, queues: queues.map((q) => q.queueId) });
}
}
return tenantQueues;
}
/**
* Shared claim loop: process selected queues from either dispatch or drain path.