@trigger.dev/redis-worker 4.3.0 → 4.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,9 +6,11 @@ import { Logger } from '@trigger.dev/core/logger';
6
6
  import { webcrypto } from 'node:crypto';
7
7
  import '@trigger.dev/core/v3/utils/flattenAttributes';
8
8
  import { calculateNextRetryDelay } from '@trigger.dev/core/v3';
9
- import { shutdownManager } from '@trigger.dev/core/v3/serverOnly';
9
+ import { shutdownManager, jumpHash } from '@trigger.dev/core/v3/serverOnly';
10
10
  import { z } from 'zod';
11
11
  import { parseExpression } from 'cron-parser';
12
+ import { setInterval as setInterval$1 } from 'node:timers/promises';
13
+ import seedrandom from 'seedrandom';
12
14
 
13
15
  const require = createRequire(import.meta.url || process.cwd() + '/index.js');
14
16
  var __create = Object.create;
@@ -11721,6 +11723,3399 @@ var Worker = class _Worker {
11721
11723
  }
11722
11724
  };
11723
11725
 
11724
- export { CronSchema, SimpleQueue, Worker };
11726
+ // src/fair-queue/concurrency.ts
11727
+ var ConcurrencyManager = class {
11728
+ constructor(options) {
11729
+ this.options = options;
11730
+ this.redis = createRedisClient(options.redis);
11731
+ this.keys = options.keys;
11732
+ this.groups = options.groups;
11733
+ this.groupsByName = new Map(options.groups.map((g) => [g.name, g]));
11734
+ this.#registerCommands();
11735
+ }
11736
+ redis;
11737
+ keys;
11738
+ groups;
11739
+ groupsByName;
11740
+ // ============================================================================
11741
+ // Public Methods
11742
+ // ============================================================================
11743
+ /**
11744
+ * Check if a message can be processed given all concurrency constraints.
11745
+ * Checks all configured groups and returns the first one at capacity.
11746
+ */
11747
+ async canProcess(queue) {
11748
+ for (const group of this.groups) {
11749
+ const groupId = group.extractGroupId(queue);
11750
+ const isAtCapacity = await this.isAtCapacity(group.name, groupId);
11751
+ if (isAtCapacity) {
11752
+ const state = await this.getState(group.name, groupId);
11753
+ return {
11754
+ allowed: false,
11755
+ blockedBy: state
11756
+ };
11757
+ }
11758
+ }
11759
+ return { allowed: true };
11760
+ }
11761
+ /**
11762
+ * Reserve concurrency slots for a message across all groups.
11763
+ * Atomic - either all groups are reserved or none.
11764
+ *
11765
+ * @returns true if reservation successful, false if any group is at capacity
11766
+ */
11767
+ async reserve(queue, messageId) {
11768
+ const groupData = await Promise.all(
11769
+ this.groups.map(async (group) => {
11770
+ const groupId = group.extractGroupId(queue);
11771
+ const limit = await group.getLimit(groupId);
11772
+ return {
11773
+ key: this.keys.concurrencyKey(group.name, groupId),
11774
+ limit: limit || group.defaultLimit
11775
+ };
11776
+ })
11777
+ );
11778
+ const keys = groupData.map((g) => g.key);
11779
+ const limits = groupData.map((g) => g.limit.toString());
11780
+ const result = await this.redis.reserveConcurrency(keys.length, keys, messageId, ...limits);
11781
+ return result === 1;
11782
+ }
11783
+ /**
11784
+ * Release concurrency slots for a message across all groups.
11785
+ */
11786
+ async release(queue, messageId) {
11787
+ const pipeline = this.redis.pipeline();
11788
+ for (const group of this.groups) {
11789
+ const groupId = group.extractGroupId(queue);
11790
+ const key = this.keys.concurrencyKey(group.name, groupId);
11791
+ pipeline.srem(key, messageId);
11792
+ }
11793
+ await pipeline.exec();
11794
+ }
11795
+ /**
11796
+ * Get current concurrency for a specific group.
11797
+ */
11798
+ async getCurrentConcurrency(groupName, groupId) {
11799
+ const key = this.keys.concurrencyKey(groupName, groupId);
11800
+ return await this.redis.scard(key);
11801
+ }
11802
+ /**
11803
+ * Get concurrency limit for a specific group.
11804
+ */
11805
+ async getConcurrencyLimit(groupName, groupId) {
11806
+ const group = this.groupsByName.get(groupName);
11807
+ if (!group) {
11808
+ throw new Error(`Unknown concurrency group: ${groupName}`);
11809
+ }
11810
+ return await group.getLimit(groupId) || group.defaultLimit;
11811
+ }
11812
+ /**
11813
+ * Check if a group is at capacity.
11814
+ */
11815
+ async isAtCapacity(groupName, groupId) {
11816
+ const [current, limit] = await Promise.all([
11817
+ this.getCurrentConcurrency(groupName, groupId),
11818
+ this.getConcurrencyLimit(groupName, groupId)
11819
+ ]);
11820
+ return current >= limit;
11821
+ }
11822
+ /**
11823
+ * Get full state for a group.
11824
+ */
11825
+ async getState(groupName, groupId) {
11826
+ const [current, limit] = await Promise.all([
11827
+ this.getCurrentConcurrency(groupName, groupId),
11828
+ this.getConcurrencyLimit(groupName, groupId)
11829
+ ]);
11830
+ return {
11831
+ groupName,
11832
+ groupId,
11833
+ current,
11834
+ limit
11835
+ };
11836
+ }
11837
+ /**
11838
+ * Get all active message IDs for a group.
11839
+ */
11840
+ async getActiveMessages(groupName, groupId) {
11841
+ const key = this.keys.concurrencyKey(groupName, groupId);
11842
+ return await this.redis.smembers(key);
11843
+ }
11844
+ /**
11845
+ * Force-clear concurrency for a group (use with caution).
11846
+ * Useful for cleanup after crashes.
11847
+ */
11848
+ async clearGroup(groupName, groupId) {
11849
+ const key = this.keys.concurrencyKey(groupName, groupId);
11850
+ await this.redis.del(key);
11851
+ }
11852
+ /**
11853
+ * Remove a specific message from concurrency tracking.
11854
+ * Useful for cleanup.
11855
+ */
11856
+ async removeMessage(messageId, queue) {
11857
+ await this.release(queue, messageId);
11858
+ }
11859
+ /**
11860
+ * Get configured group names.
11861
+ */
11862
+ getGroupNames() {
11863
+ return this.groups.map((g) => g.name);
11864
+ }
11865
+ /**
11866
+ * Close the Redis connection.
11867
+ */
11868
+ async close() {
11869
+ await this.redis.quit();
11870
+ }
11871
+ // ============================================================================
11872
+ // Private Methods
11873
+ // ============================================================================
11874
+ #registerCommands() {
11875
+ this.redis.defineCommand("reserveConcurrency", {
11876
+ lua: `
11877
+ local numGroups = #KEYS
11878
+ local messageId = ARGV[1]
11879
+
11880
+ -- Check all groups first
11881
+ for i = 1, numGroups do
11882
+ local key = KEYS[i]
11883
+ local limit = tonumber(ARGV[1 + i]) -- Limits start at ARGV[2]
11884
+ local current = redis.call('SCARD', key)
11885
+
11886
+ if current >= limit then
11887
+ return 0 -- At capacity
11888
+ end
11889
+ end
11890
+
11891
+ -- All groups have capacity, add message to all
11892
+ for i = 1, numGroups do
11893
+ local key = KEYS[i]
11894
+ redis.call('SADD', key, messageId)
11895
+ end
11896
+
11897
+ return 1
11898
+ `
11899
+ });
11900
+ }
11901
+ };
11902
+ var MasterQueue = class {
11903
+ constructor(options) {
11904
+ this.options = options;
11905
+ this.redis = createRedisClient(options.redis);
11906
+ this.keys = options.keys;
11907
+ this.shardCount = Math.max(1, options.shardCount);
11908
+ this.#registerCommands();
11909
+ }
11910
+ redis;
11911
+ keys;
11912
+ shardCount;
11913
+ // ============================================================================
11914
+ // Public Methods
11915
+ // ============================================================================
11916
+ /**
11917
+ * Get the shard ID for a queue.
11918
+ * Uses consistent hashing based on queue ID.
11919
+ */
11920
+ getShardForQueue(queueId) {
11921
+ return this.#hashToShard(queueId);
11922
+ }
11923
+ /**
11924
+ * Add a queue to its master queue shard.
11925
+ * Updates the score to the oldest message timestamp.
11926
+ *
11927
+ * @param queueId - The queue identifier
11928
+ * @param oldestMessageTimestamp - Timestamp of the oldest message in the queue
11929
+ */
11930
+ async addQueue(queueId, oldestMessageTimestamp) {
11931
+ const shardId = this.getShardForQueue(queueId);
11932
+ const masterKey = this.keys.masterQueueKey(shardId);
11933
+ await this.redis.zadd(masterKey, oldestMessageTimestamp, queueId);
11934
+ }
11935
+ /**
11936
+ * Update a queue's score in the master queue.
11937
+ * This is typically called after dequeuing to update to the new oldest message.
11938
+ *
11939
+ * @param queueId - The queue identifier
11940
+ * @param newOldestTimestamp - New timestamp of the oldest message
11941
+ */
11942
+ async updateQueueScore(queueId, newOldestTimestamp) {
11943
+ const shardId = this.getShardForQueue(queueId);
11944
+ const masterKey = this.keys.masterQueueKey(shardId);
11945
+ await this.redis.zadd(masterKey, newOldestTimestamp, queueId);
11946
+ }
11947
+ /**
11948
+ * Remove a queue from its master queue shard.
11949
+ * Called when a queue becomes empty.
11950
+ *
11951
+ * @param queueId - The queue identifier
11952
+ */
11953
+ async removeQueue(queueId) {
11954
+ const shardId = this.getShardForQueue(queueId);
11955
+ const masterKey = this.keys.masterQueueKey(shardId);
11956
+ await this.redis.zrem(masterKey, queueId);
11957
+ }
11958
+ /**
11959
+ * Get queues from a shard, ordered by oldest message (lowest score first).
11960
+ *
11961
+ * @param shardId - The shard to query
11962
+ * @param limit - Maximum number of queues to return (default: 1000)
11963
+ * @param maxScore - Maximum score (timestamp) to include (default: now)
11964
+ */
11965
+ async getQueuesFromShard(shardId, limit = 1e3, maxScore) {
11966
+ const masterKey = this.keys.masterQueueKey(shardId);
11967
+ const score = maxScore ?? Date.now();
11968
+ const results = await this.redis.zrangebyscore(
11969
+ masterKey,
11970
+ "-inf",
11971
+ score,
11972
+ "WITHSCORES",
11973
+ "LIMIT",
11974
+ 0,
11975
+ limit
11976
+ );
11977
+ const queues = [];
11978
+ for (let i = 0; i < results.length; i += 2) {
11979
+ const queueId = results[i];
11980
+ const scoreStr = results[i + 1];
11981
+ if (queueId && scoreStr) {
11982
+ queues.push({
11983
+ queueId,
11984
+ score: parseFloat(scoreStr),
11985
+ tenantId: this.keys.extractTenantId(queueId)
11986
+ });
11987
+ }
11988
+ }
11989
+ return queues;
11990
+ }
11991
+ /**
11992
+ * Get the number of queues in a shard.
11993
+ */
11994
+ async getShardQueueCount(shardId) {
11995
+ const masterKey = this.keys.masterQueueKey(shardId);
11996
+ return await this.redis.zcard(masterKey);
11997
+ }
11998
+ /**
11999
+ * Get total queue count across all shards.
12000
+ */
12001
+ async getTotalQueueCount() {
12002
+ const counts = await Promise.all(
12003
+ Array.from({ length: this.shardCount }, (_, i) => this.getShardQueueCount(i))
12004
+ );
12005
+ return counts.reduce((sum, count) => sum + count, 0);
12006
+ }
12007
+ /**
12008
+ * Atomically add a queue to master queue only if queue has messages.
12009
+ * Uses Lua script for atomicity.
12010
+ *
12011
+ * @param queueId - The queue identifier
12012
+ * @param queueKey - The actual queue sorted set key
12013
+ * @returns Whether the queue was added to the master queue
12014
+ */
12015
+ async addQueueIfNotEmpty(queueId, queueKey) {
12016
+ const shardId = this.getShardForQueue(queueId);
12017
+ const masterKey = this.keys.masterQueueKey(shardId);
12018
+ const result = await this.redis.addQueueIfNotEmpty(masterKey, queueKey, queueId);
12019
+ return result === 1;
12020
+ }
12021
+ /**
12022
+ * Atomically remove a queue from master queue only if queue is empty.
12023
+ * Uses Lua script for atomicity.
12024
+ *
12025
+ * @param queueId - The queue identifier
12026
+ * @param queueKey - The actual queue sorted set key
12027
+ * @returns Whether the queue was removed from the master queue
12028
+ */
12029
+ async removeQueueIfEmpty(queueId, queueKey) {
12030
+ const shardId = this.getShardForQueue(queueId);
12031
+ const masterKey = this.keys.masterQueueKey(shardId);
12032
+ const result = await this.redis.removeQueueIfEmpty(masterKey, queueKey, queueId);
12033
+ return result === 1;
12034
+ }
12035
+ /**
12036
+ * Close the Redis connection.
12037
+ */
12038
+ async close() {
12039
+ await this.redis.quit();
12040
+ }
12041
+ // ============================================================================
12042
+ // Private Methods
12043
+ // ============================================================================
12044
+ /**
12045
+ * Map queue ID to shard using Jump Consistent Hash.
12046
+ * Provides better distribution than djb2 and minimal reshuffling when shard count changes.
12047
+ */
12048
+ #hashToShard(queueId) {
12049
+ return jumpHash(queueId, this.shardCount);
12050
+ }
12051
+ #registerCommands() {
12052
+ this.redis.defineCommand("addQueueIfNotEmpty", {
12053
+ numberOfKeys: 2,
12054
+ lua: `
12055
+ local masterKey = KEYS[1]
12056
+ local queueKey = KEYS[2]
12057
+ local queueId = ARGV[1]
12058
+
12059
+ -- Check if queue has any messages
12060
+ local count = redis.call('ZCARD', queueKey)
12061
+ if count == 0 then
12062
+ return 0
12063
+ end
12064
+
12065
+ -- Get the oldest message timestamp (lowest score)
12066
+ local oldest = redis.call('ZRANGE', queueKey, 0, 0, 'WITHSCORES')
12067
+ if #oldest == 0 then
12068
+ return 0
12069
+ end
12070
+
12071
+ local score = oldest[2]
12072
+
12073
+ -- Add to master queue with the oldest message score
12074
+ redis.call('ZADD', masterKey, score, queueId)
12075
+ return 1
12076
+ `
12077
+ });
12078
+ this.redis.defineCommand("removeQueueIfEmpty", {
12079
+ numberOfKeys: 2,
12080
+ lua: `
12081
+ local masterKey = KEYS[1]
12082
+ local queueKey = KEYS[2]
12083
+ local queueId = ARGV[1]
12084
+
12085
+ -- Check if queue is empty
12086
+ local count = redis.call('ZCARD', queueKey)
12087
+ if count > 0 then
12088
+ return 0
12089
+ end
12090
+
12091
+ -- Remove from master queue
12092
+ redis.call('ZREM', masterKey, queueId)
12093
+ return 1
12094
+ `
12095
+ });
12096
+ }
12097
+ };
12098
+
12099
+ // src/fair-queue/telemetry.ts
12100
+ var FairQueueAttributes = {
12101
+ QUEUE_ID: "fairqueue.queue_id",
12102
+ TENANT_ID: "fairqueue.tenant_id",
12103
+ MESSAGE_ID: "fairqueue.message_id",
12104
+ SHARD_ID: "fairqueue.shard_id",
12105
+ WORKER_QUEUE: "fairqueue.worker_queue",
12106
+ CONSUMER_ID: "fairqueue.consumer_id",
12107
+ ATTEMPT: "fairqueue.attempt",
12108
+ CONCURRENCY_GROUP: "fairqueue.concurrency_group",
12109
+ MESSAGE_COUNT: "fairqueue.message_count",
12110
+ RESULT: "fairqueue.result"
12111
+ };
12112
+ var MessagingAttributes = {
12113
+ SYSTEM: "messaging.system",
12114
+ OPERATION: "messaging.operation",
12115
+ MESSAGE_ID: "messaging.message_id",
12116
+ DESTINATION_NAME: "messaging.destination.name"
12117
+ };
12118
+ var FairQueueTelemetry = class {
12119
+ tracer;
12120
+ meter;
12121
+ metrics;
12122
+ name;
12123
+ constructor(options) {
12124
+ this.tracer = options.tracer;
12125
+ this.meter = options.meter;
12126
+ this.name = options.name ?? "fairqueue";
12127
+ if (this.meter) {
12128
+ this.#initializeMetrics();
12129
+ }
12130
+ }
12131
+ // ============================================================================
12132
+ // Tracing
12133
+ // ============================================================================
12134
+ /**
12135
+ * Create a traced span for an operation.
12136
+ * Returns the result of the function, or throws any error after recording it.
12137
+ */
12138
+ async trace(name, fn, options) {
12139
+ if (!this.tracer) {
12140
+ return fn(noopSpan);
12141
+ }
12142
+ const spanOptions = {
12143
+ kind: options?.kind,
12144
+ attributes: {
12145
+ [MessagingAttributes.SYSTEM]: this.name,
12146
+ ...options?.attributes
12147
+ }
12148
+ };
12149
+ return this.tracer.startActiveSpan(`${this.name}.${name}`, spanOptions, async (span) => {
12150
+ try {
12151
+ const result = await fn(span);
12152
+ return result;
12153
+ } catch (error) {
12154
+ if (error instanceof Error) {
12155
+ span.recordException(error);
12156
+ } else {
12157
+ span.recordException(new Error(String(error)));
12158
+ }
12159
+ throw error;
12160
+ } finally {
12161
+ span.end();
12162
+ }
12163
+ });
12164
+ }
12165
+ /**
12166
+ * Synchronous version of trace.
12167
+ */
12168
+ traceSync(name, fn, options) {
12169
+ if (!this.tracer) {
12170
+ return fn(noopSpan);
12171
+ }
12172
+ const spanOptions = {
12173
+ kind: options?.kind,
12174
+ attributes: {
12175
+ [MessagingAttributes.SYSTEM]: this.name,
12176
+ ...options?.attributes
12177
+ }
12178
+ };
12179
+ return this.tracer.startActiveSpan(`${this.name}.${name}`, spanOptions, (span) => {
12180
+ try {
12181
+ return fn(span);
12182
+ } catch (error) {
12183
+ if (error instanceof Error) {
12184
+ span.recordException(error);
12185
+ } else {
12186
+ span.recordException(new Error(String(error)));
12187
+ }
12188
+ throw error;
12189
+ } finally {
12190
+ span.end();
12191
+ }
12192
+ });
12193
+ }
12194
+ // ============================================================================
12195
+ // Metrics
12196
+ // ============================================================================
12197
+ /**
12198
+ * Record a message enqueued.
12199
+ */
12200
+ recordEnqueue(attributes) {
12201
+ this.metrics?.messagesEnqueued.add(1, attributes);
12202
+ }
12203
+ /**
12204
+ * Record a batch of messages enqueued.
12205
+ */
12206
+ recordEnqueueBatch(count, attributes) {
12207
+ this.metrics?.messagesEnqueued.add(count, attributes);
12208
+ }
12209
+ /**
12210
+ * Record a message completed successfully.
12211
+ */
12212
+ recordComplete(attributes) {
12213
+ this.metrics?.messagesCompleted.add(1, attributes);
12214
+ }
12215
+ /**
12216
+ * Record a message processing failure.
12217
+ */
12218
+ recordFailure(attributes) {
12219
+ this.metrics?.messagesFailed.add(1, attributes);
12220
+ }
12221
+ /**
12222
+ * Record a message retry.
12223
+ */
12224
+ recordRetry(attributes) {
12225
+ this.metrics?.messagesRetried.add(1, attributes);
12226
+ }
12227
+ /**
12228
+ * Record a message sent to DLQ.
12229
+ */
12230
+ recordDLQ(attributes) {
12231
+ this.metrics?.messagesToDLQ.add(1, attributes);
12232
+ }
12233
+ /**
12234
+ * Record message processing time.
12235
+ *
12236
+ * @param durationMs - Processing duration in milliseconds
12237
+ */
12238
+ recordProcessingTime(durationMs, attributes) {
12239
+ this.metrics?.processingTime.record(durationMs, attributes);
12240
+ }
12241
+ /**
12242
+ * Record time a message spent waiting in queue.
12243
+ *
12244
+ * @param durationMs - Queue wait time in milliseconds
12245
+ */
12246
+ recordQueueTime(durationMs, attributes) {
12247
+ this.metrics?.queueTime.record(durationMs, attributes);
12248
+ }
12249
+ /**
12250
+ * Register observable gauge callbacks.
12251
+ * Call this after FairQueue is initialized to register the gauge callbacks.
12252
+ */
12253
+ registerGaugeCallbacks(callbacks) {
12254
+ if (!this.metrics) return;
12255
+ if (callbacks.getQueueLength && callbacks.observedQueues) {
12256
+ const getQueueLength = callbacks.getQueueLength;
12257
+ const queues = callbacks.observedQueues;
12258
+ this.metrics.queueLength.addCallback(async (observableResult) => {
12259
+ for (const queueId of queues) {
12260
+ const length = await getQueueLength(queueId);
12261
+ observableResult.observe(length, {
12262
+ [FairQueueAttributes.QUEUE_ID]: queueId
12263
+ });
12264
+ }
12265
+ });
12266
+ }
12267
+ if (callbacks.getMasterQueueLength && callbacks.shardCount) {
12268
+ const getMasterQueueLength = callbacks.getMasterQueueLength;
12269
+ const shardCount = callbacks.shardCount;
12270
+ this.metrics.masterQueueLength.addCallback(async (observableResult) => {
12271
+ for (let shardId = 0; shardId < shardCount; shardId++) {
12272
+ const length = await getMasterQueueLength(shardId);
12273
+ observableResult.observe(length, {
12274
+ [FairQueueAttributes.SHARD_ID]: shardId.toString()
12275
+ });
12276
+ }
12277
+ });
12278
+ }
12279
+ if (callbacks.getInflightCount && callbacks.shardCount) {
12280
+ const getInflightCount = callbacks.getInflightCount;
12281
+ const shardCount = callbacks.shardCount;
12282
+ this.metrics.inflightCount.addCallback(async (observableResult) => {
12283
+ for (let shardId = 0; shardId < shardCount; shardId++) {
12284
+ const count = await getInflightCount(shardId);
12285
+ observableResult.observe(count, {
12286
+ [FairQueueAttributes.SHARD_ID]: shardId.toString()
12287
+ });
12288
+ }
12289
+ });
12290
+ }
12291
+ if (callbacks.getDLQLength && callbacks.observedTenants) {
12292
+ const getDLQLength = callbacks.getDLQLength;
12293
+ const tenants = callbacks.observedTenants;
12294
+ this.metrics.dlqLength.addCallback(async (observableResult) => {
12295
+ for (const tenantId of tenants) {
12296
+ const length = await getDLQLength(tenantId);
12297
+ observableResult.observe(length, {
12298
+ [FairQueueAttributes.TENANT_ID]: tenantId
12299
+ });
12300
+ }
12301
+ });
12302
+ }
12303
+ }
12304
+ // ============================================================================
12305
+ // Helper Methods
12306
+ // ============================================================================
12307
+ /**
12308
+ * Create standard attributes for a message operation.
12309
+ */
12310
+ messageAttributes(params) {
12311
+ const attrs = {};
12312
+ if (params.queueId) attrs[FairQueueAttributes.QUEUE_ID] = params.queueId;
12313
+ if (params.tenantId) attrs[FairQueueAttributes.TENANT_ID] = params.tenantId;
12314
+ if (params.messageId) attrs[FairQueueAttributes.MESSAGE_ID] = params.messageId;
12315
+ if (params.attempt !== void 0) attrs[FairQueueAttributes.ATTEMPT] = params.attempt;
12316
+ if (params.workerQueue) attrs[FairQueueAttributes.WORKER_QUEUE] = params.workerQueue;
12317
+ if (params.consumerId) attrs[FairQueueAttributes.CONSUMER_ID] = params.consumerId;
12318
+ return attrs;
12319
+ }
12320
+ /**
12321
+ * Check if telemetry is enabled.
12322
+ */
12323
+ get isEnabled() {
12324
+ return !!this.tracer || !!this.meter;
12325
+ }
12326
+ /**
12327
+ * Check if tracing is enabled.
12328
+ */
12329
+ get hasTracer() {
12330
+ return !!this.tracer;
12331
+ }
12332
+ /**
12333
+ * Check if metrics are enabled.
12334
+ */
12335
+ get hasMetrics() {
12336
+ return !!this.meter;
12337
+ }
12338
+ // ============================================================================
12339
+ // Private Methods
12340
+ // ============================================================================
12341
+ #initializeMetrics() {
12342
+ if (!this.meter) return;
12343
+ this.metrics = {
12344
+ // Counters
12345
+ messagesEnqueued: this.meter.createCounter(`${this.name}.messages.enqueued`, {
12346
+ description: "Number of messages enqueued",
12347
+ unit: "messages"
12348
+ }),
12349
+ messagesCompleted: this.meter.createCounter(`${this.name}.messages.completed`, {
12350
+ description: "Number of messages completed successfully",
12351
+ unit: "messages"
12352
+ }),
12353
+ messagesFailed: this.meter.createCounter(`${this.name}.messages.failed`, {
12354
+ description: "Number of messages that failed processing",
12355
+ unit: "messages"
12356
+ }),
12357
+ messagesRetried: this.meter.createCounter(`${this.name}.messages.retried`, {
12358
+ description: "Number of message retries",
12359
+ unit: "messages"
12360
+ }),
12361
+ messagesToDLQ: this.meter.createCounter(`${this.name}.messages.dlq`, {
12362
+ description: "Number of messages sent to dead letter queue",
12363
+ unit: "messages"
12364
+ }),
12365
+ // Histograms
12366
+ processingTime: this.meter.createHistogram(`${this.name}.message.processing_time`, {
12367
+ description: "Message processing time",
12368
+ unit: "ms"
12369
+ }),
12370
+ queueTime: this.meter.createHistogram(`${this.name}.message.queue_time`, {
12371
+ description: "Time message spent waiting in queue",
12372
+ unit: "ms"
12373
+ }),
12374
+ // Observable gauges
12375
+ queueLength: this.meter.createObservableGauge(`${this.name}.queue.length`, {
12376
+ description: "Number of messages in a queue",
12377
+ unit: "messages"
12378
+ }),
12379
+ masterQueueLength: this.meter.createObservableGauge(`${this.name}.master_queue.length`, {
12380
+ description: "Number of queues in master queue shard",
12381
+ unit: "queues"
12382
+ }),
12383
+ inflightCount: this.meter.createObservableGauge(`${this.name}.inflight.count`, {
12384
+ description: "Number of messages currently being processed",
12385
+ unit: "messages"
12386
+ }),
12387
+ dlqLength: this.meter.createObservableGauge(`${this.name}.dlq.length`, {
12388
+ description: "Number of messages in dead letter queue",
12389
+ unit: "messages"
12390
+ })
12391
+ };
12392
+ }
12393
+ };
12394
+ var noopSpan = {
12395
+ spanContext: () => ({
12396
+ traceId: "",
12397
+ spanId: "",
12398
+ traceFlags: 0
12399
+ }),
12400
+ setAttribute: () => noopSpan,
12401
+ setAttributes: () => noopSpan,
12402
+ addEvent: () => noopSpan,
12403
+ addLink: () => noopSpan,
12404
+ addLinks: () => noopSpan,
12405
+ setStatus: () => noopSpan,
12406
+ updateName: () => noopSpan,
12407
+ end: () => {
12408
+ },
12409
+ isRecording: () => false,
12410
+ recordException: () => {
12411
+ }
12412
+ };
12413
+ var noopTelemetry = new FairQueueTelemetry({});
12414
+ var VisibilityManager = class {
12415
+ constructor(options) {
12416
+ this.options = options;
12417
+ this.redis = createRedisClient(options.redis);
12418
+ this.keys = options.keys;
12419
+ this.shardCount = options.shardCount;
12420
+ this.defaultTimeoutMs = options.defaultTimeoutMs;
12421
+ this.logger = options.logger ?? {
12422
+ debug: () => {
12423
+ },
12424
+ error: () => {
12425
+ }
12426
+ };
12427
+ this.#registerCommands();
12428
+ }
12429
+ redis;
12430
+ keys;
12431
+ shardCount;
12432
+ defaultTimeoutMs;
12433
+ logger;
12434
+ // ============================================================================
12435
+ // Public Methods
12436
+ // ============================================================================
12437
+ /**
12438
+ * Claim a message for processing.
12439
+ * Moves the message from its queue to the in-flight set with a visibility timeout.
12440
+ *
12441
+ * @param queueId - The queue to claim from
12442
+ * @param queueKey - The Redis key for the queue sorted set
12443
+ * @param queueItemsKey - The Redis key for the queue items hash
12444
+ * @param consumerId - ID of the consumer claiming the message
12445
+ * @param timeoutMs - Visibility timeout in milliseconds
12446
+ * @returns Claim result with the message if successful
12447
+ */
12448
+ async claim(queueId, queueKey, queueItemsKey, consumerId, timeoutMs) {
12449
+ const timeout = timeoutMs ?? this.defaultTimeoutMs;
12450
+ const deadline = Date.now() + timeout;
12451
+ const shardId = this.#getShardForQueue(queueId);
12452
+ const inflightKey = this.keys.inflightKey(shardId);
12453
+ const inflightDataKey = this.keys.inflightDataKey(shardId);
12454
+ const result = await this.redis.claimMessage(
12455
+ queueKey,
12456
+ queueItemsKey,
12457
+ inflightKey,
12458
+ inflightDataKey,
12459
+ queueId,
12460
+ consumerId,
12461
+ deadline.toString()
12462
+ );
12463
+ if (!result) {
12464
+ return { claimed: false };
12465
+ }
12466
+ const [messageId, payloadJson] = result;
12467
+ try {
12468
+ const payload = JSON.parse(payloadJson);
12469
+ const message = {
12470
+ messageId,
12471
+ queueId,
12472
+ payload,
12473
+ deadline,
12474
+ consumerId
12475
+ };
12476
+ this.logger.debug("Message claimed", {
12477
+ messageId,
12478
+ queueId,
12479
+ consumerId,
12480
+ deadline
12481
+ });
12482
+ return { claimed: true, message };
12483
+ } catch (error) {
12484
+ this.logger.error("Failed to parse claimed message", {
12485
+ messageId,
12486
+ queueId,
12487
+ error: error instanceof Error ? error.message : String(error)
12488
+ });
12489
+ await this.#removeFromInflight(shardId, messageId, queueId);
12490
+ return { claimed: false };
12491
+ }
12492
+ }
12493
+ /**
12494
+ * Extend the visibility timeout for a message (heartbeat).
12495
+ *
12496
+ * @param messageId - The message ID
12497
+ * @param queueId - The queue ID
12498
+ * @param extendMs - Additional milliseconds to add to the deadline
12499
+ * @returns true if the heartbeat was successful
12500
+ */
12501
+ async heartbeat(messageId, queueId, extendMs) {
12502
+ const shardId = this.#getShardForQueue(queueId);
12503
+ const inflightKey = this.keys.inflightKey(shardId);
12504
+ const member = this.#makeMember(messageId, queueId);
12505
+ const newDeadline = Date.now() + extendMs;
12506
+ const result = await this.redis.heartbeatMessage(
12507
+ inflightKey,
12508
+ member,
12509
+ newDeadline.toString()
12510
+ );
12511
+ const success = result === 1;
12512
+ if (success) {
12513
+ this.logger.debug("Heartbeat successful", {
12514
+ messageId,
12515
+ queueId,
12516
+ newDeadline
12517
+ });
12518
+ }
12519
+ return success;
12520
+ }
12521
+ /**
12522
+ * Mark a message as successfully processed.
12523
+ * Removes the message from in-flight tracking.
12524
+ *
12525
+ * @param messageId - The message ID
12526
+ * @param queueId - The queue ID
12527
+ */
12528
+ async complete(messageId, queueId) {
12529
+ const shardId = this.#getShardForQueue(queueId);
12530
+ await this.#removeFromInflight(shardId, messageId, queueId);
12531
+ this.logger.debug("Message completed", {
12532
+ messageId,
12533
+ queueId
12534
+ });
12535
+ }
12536
+ /**
12537
+ * Release a message back to its queue.
12538
+ * Used when processing fails or consumer wants to retry later.
12539
+ *
12540
+ * @param messageId - The message ID
12541
+ * @param queueId - The queue ID
12542
+ * @param queueKey - The Redis key for the queue
12543
+ * @param queueItemsKey - The Redis key for the queue items hash
12544
+ * @param score - Optional score for the message (defaults to now)
12545
+ */
12546
+ async release(messageId, queueId, queueKey, queueItemsKey, score) {
12547
+ const shardId = this.#getShardForQueue(queueId);
12548
+ const inflightKey = this.keys.inflightKey(shardId);
12549
+ const inflightDataKey = this.keys.inflightDataKey(shardId);
12550
+ const member = this.#makeMember(messageId, queueId);
12551
+ const messageScore = score ?? Date.now();
12552
+ await this.redis.releaseMessage(
12553
+ inflightKey,
12554
+ inflightDataKey,
12555
+ queueKey,
12556
+ queueItemsKey,
12557
+ member,
12558
+ messageId,
12559
+ messageScore.toString()
12560
+ );
12561
+ this.logger.debug("Message released", {
12562
+ messageId,
12563
+ queueId,
12564
+ score: messageScore
12565
+ });
12566
+ }
12567
+ /**
12568
+ * Reclaim timed-out messages from a shard.
12569
+ * Returns messages to their original queues.
12570
+ *
12571
+ * @param shardId - The shard to check
12572
+ * @param getQueueKeys - Function to get queue keys for a queue ID
12573
+ * @returns Number of messages reclaimed
12574
+ */
12575
+ async reclaimTimedOut(shardId, getQueueKeys) {
12576
+ const inflightKey = this.keys.inflightKey(shardId);
12577
+ const inflightDataKey = this.keys.inflightDataKey(shardId);
12578
+ const now = Date.now();
12579
+ const timedOut = await this.redis.zrangebyscore(
12580
+ inflightKey,
12581
+ "-inf",
12582
+ now,
12583
+ "WITHSCORES",
12584
+ "LIMIT",
12585
+ 0,
12586
+ 100
12587
+ // Process in batches
12588
+ );
12589
+ let reclaimed = 0;
12590
+ for (let i = 0; i < timedOut.length; i += 2) {
12591
+ const member = timedOut[i];
12592
+ const originalScore = timedOut[i + 1];
12593
+ if (!member || !originalScore) {
12594
+ continue;
12595
+ }
12596
+ const { messageId, queueId } = this.#parseMember(member);
12597
+ const { queueKey, queueItemsKey } = getQueueKeys(queueId);
12598
+ try {
12599
+ const score = parseFloat(originalScore) || now;
12600
+ await this.redis.releaseMessage(
12601
+ inflightKey,
12602
+ inflightDataKey,
12603
+ queueKey,
12604
+ queueItemsKey,
12605
+ member,
12606
+ messageId,
12607
+ score.toString()
12608
+ );
12609
+ reclaimed++;
12610
+ this.logger.debug("Reclaimed timed-out message", {
12611
+ messageId,
12612
+ queueId,
12613
+ originalScore
12614
+ });
12615
+ } catch (error) {
12616
+ this.logger.error("Failed to reclaim message", {
12617
+ messageId,
12618
+ queueId,
12619
+ error: error instanceof Error ? error.message : String(error)
12620
+ });
12621
+ }
12622
+ }
12623
+ return reclaimed;
12624
+ }
12625
+ /**
12626
+ * Get all in-flight messages for a shard.
12627
+ */
12628
+ async getInflightMessages(shardId) {
12629
+ const inflightKey = this.keys.inflightKey(shardId);
12630
+ const results = await this.redis.zrange(inflightKey, 0, -1, "WITHSCORES");
12631
+ const messages = [];
12632
+ for (let i = 0; i < results.length; i += 2) {
12633
+ const member = results[i];
12634
+ const deadlineStr = results[i + 1];
12635
+ if (!member || !deadlineStr) {
12636
+ continue;
12637
+ }
12638
+ const deadline = parseFloat(deadlineStr);
12639
+ const { messageId, queueId } = this.#parseMember(member);
12640
+ messages.push({ messageId, queueId, deadline });
12641
+ }
12642
+ return messages;
12643
+ }
12644
+ /**
12645
+ * Get count of in-flight messages for a shard.
12646
+ */
12647
+ async getInflightCount(shardId) {
12648
+ const inflightKey = this.keys.inflightKey(shardId);
12649
+ return await this.redis.zcard(inflightKey);
12650
+ }
12651
+ /**
12652
+ * Get total in-flight count across all shards.
12653
+ */
12654
+ async getTotalInflightCount() {
12655
+ const counts = await Promise.all(
12656
+ Array.from({ length: this.shardCount }, (_, i) => this.getInflightCount(i))
12657
+ );
12658
+ return counts.reduce((sum, count) => sum + count, 0);
12659
+ }
12660
+ /**
12661
+ * Close the Redis connection.
12662
+ */
12663
+ async close() {
12664
+ await this.redis.quit();
12665
+ }
12666
+ // ============================================================================
12667
+ // Private Methods
12668
+ // ============================================================================
12669
+ /**
12670
+ * Map queue ID to shard using Jump Consistent Hash.
12671
+ * Must use same algorithm as MasterQueue for consistency.
12672
+ */
12673
+ #getShardForQueue(queueId) {
12674
+ return jumpHash(queueId, this.shardCount);
12675
+ }
12676
+ #makeMember(messageId, queueId) {
12677
+ return `${messageId}:${queueId}`;
12678
+ }
12679
+ #parseMember(member) {
12680
+ const colonIndex = member.indexOf(":");
12681
+ if (colonIndex === -1) {
12682
+ return { messageId: member, queueId: "" };
12683
+ }
12684
+ return {
12685
+ messageId: member.substring(0, colonIndex),
12686
+ queueId: member.substring(colonIndex + 1)
12687
+ };
12688
+ }
12689
+ async #removeFromInflight(shardId, messageId, queueId) {
12690
+ const inflightKey = this.keys.inflightKey(shardId);
12691
+ const inflightDataKey = this.keys.inflightDataKey(shardId);
12692
+ const member = this.#makeMember(messageId, queueId);
12693
+ const pipeline = this.redis.pipeline();
12694
+ pipeline.zrem(inflightKey, member);
12695
+ pipeline.hdel(inflightDataKey, messageId);
12696
+ await pipeline.exec();
12697
+ }
12698
+ #registerCommands() {
12699
+ this.redis.defineCommand("claimMessage", {
12700
+ numberOfKeys: 4,
12701
+ lua: `
12702
+ local queueKey = KEYS[1]
12703
+ local queueItemsKey = KEYS[2]
12704
+ local inflightKey = KEYS[3]
12705
+ local inflightDataKey = KEYS[4]
12706
+
12707
+ local queueId = ARGV[1]
12708
+ local consumerId = ARGV[2]
12709
+ local deadline = tonumber(ARGV[3])
12710
+
12711
+ -- Get oldest message from queue
12712
+ local items = redis.call('ZRANGE', queueKey, 0, 0)
12713
+ if #items == 0 then
12714
+ return nil
12715
+ end
12716
+
12717
+ local messageId = items[1]
12718
+
12719
+ -- Get message data
12720
+ local payload = redis.call('HGET', queueItemsKey, messageId)
12721
+ if not payload then
12722
+ -- Message data missing, remove from queue and return nil
12723
+ redis.call('ZREM', queueKey, messageId)
12724
+ return nil
12725
+ end
12726
+
12727
+ -- Remove from queue
12728
+ redis.call('ZREM', queueKey, messageId)
12729
+ redis.call('HDEL', queueItemsKey, messageId)
12730
+
12731
+ -- Add to in-flight set with deadline
12732
+ local member = messageId .. ':' .. queueId
12733
+ redis.call('ZADD', inflightKey, deadline, member)
12734
+
12735
+ -- Store message data for potential release
12736
+ redis.call('HSET', inflightDataKey, messageId, payload)
12737
+
12738
+ return {messageId, payload}
12739
+ `
12740
+ });
12741
+ this.redis.defineCommand("releaseMessage", {
12742
+ numberOfKeys: 4,
12743
+ lua: `
12744
+ local inflightKey = KEYS[1]
12745
+ local inflightDataKey = KEYS[2]
12746
+ local queueKey = KEYS[3]
12747
+ local queueItemsKey = KEYS[4]
12748
+
12749
+ local member = ARGV[1]
12750
+ local messageId = ARGV[2]
12751
+ local score = tonumber(ARGV[3])
12752
+
12753
+ -- Get message data from in-flight
12754
+ local payload = redis.call('HGET', inflightDataKey, messageId)
12755
+ if not payload then
12756
+ -- Message not in in-flight or already released
12757
+ return 0
12758
+ end
12759
+
12760
+ -- Remove from in-flight
12761
+ redis.call('ZREM', inflightKey, member)
12762
+ redis.call('HDEL', inflightDataKey, messageId)
12763
+
12764
+ -- Add back to queue
12765
+ redis.call('ZADD', queueKey, score, messageId)
12766
+ redis.call('HSET', queueItemsKey, messageId, payload)
12767
+
12768
+ return 1
12769
+ `
12770
+ });
12771
+ this.redis.defineCommand("heartbeatMessage", {
12772
+ numberOfKeys: 1,
12773
+ lua: `
12774
+ local inflightKey = KEYS[1]
12775
+ local member = ARGV[1]
12776
+ local newDeadline = tonumber(ARGV[2])
12777
+
12778
+ -- Check if member exists in the in-flight set
12779
+ local score = redis.call('ZSCORE', inflightKey, member)
12780
+ if not score then
12781
+ return 0
12782
+ end
12783
+
12784
+ -- Update the deadline
12785
+ redis.call('ZADD', inflightKey, 'XX', newDeadline, member)
12786
+ return 1
12787
+ `
12788
+ });
12789
+ }
12790
+ };
12791
+
12792
+ // src/fair-queue/workerQueue.ts
12793
+ var WorkerQueueManager = class {
12794
+ constructor(options) {
12795
+ this.options = options;
12796
+ this.redis = createRedisClient(options.redis);
12797
+ this.keys = options.keys;
12798
+ this.logger = options.logger ?? {
12799
+ debug: () => {
12800
+ },
12801
+ error: () => {
12802
+ }
12803
+ };
12804
+ this.#registerCommands();
12805
+ }
12806
+ redis;
12807
+ keys;
12808
+ logger;
12809
+ // ============================================================================
12810
+ // Public Methods
12811
+ // ============================================================================
12812
+ /**
12813
+ * Push a message key to a worker queue.
12814
+ * Called after claiming a message from the message queue.
12815
+ *
12816
+ * @param workerQueueId - The worker queue identifier
12817
+ * @param messageKey - The message key to push (typically "messageId:queueId")
12818
+ */
12819
+ async push(workerQueueId, messageKey) {
12820
+ const workerQueueKey = this.keys.workerQueueKey(workerQueueId);
12821
+ await this.redis.rpush(workerQueueKey, messageKey);
12822
+ this.logger.debug("Pushed to worker queue", {
12823
+ workerQueueId,
12824
+ workerQueueKey,
12825
+ messageKey
12826
+ });
12827
+ }
12828
+ /**
12829
+ * Push multiple message keys to a worker queue.
12830
+ *
12831
+ * @param workerQueueId - The worker queue identifier
12832
+ * @param messageKeys - The message keys to push
12833
+ */
12834
+ async pushBatch(workerQueueId, messageKeys) {
12835
+ if (messageKeys.length === 0) {
12836
+ return;
12837
+ }
12838
+ const workerQueueKey = this.keys.workerQueueKey(workerQueueId);
12839
+ await this.redis.rpush(workerQueueKey, ...messageKeys);
12840
+ this.logger.debug("Pushed batch to worker queue", {
12841
+ workerQueueId,
12842
+ workerQueueKey,
12843
+ count: messageKeys.length
12844
+ });
12845
+ }
12846
+ /**
12847
+ * Blocking pop from a worker queue.
12848
+ * Waits until a message is available or timeout expires.
12849
+ *
12850
+ * @param workerQueueId - The worker queue identifier
12851
+ * @param timeoutSeconds - Maximum time to wait (0 = wait forever)
12852
+ * @param signal - Optional abort signal to cancel waiting
12853
+ * @returns The message key, or null if timeout
12854
+ */
12855
+ async blockingPop(workerQueueId, timeoutSeconds, signal) {
12856
+ const workerQueueKey = this.keys.workerQueueKey(workerQueueId);
12857
+ const blockingClient = this.redis.duplicate();
12858
+ try {
12859
+ if (signal) {
12860
+ const cleanup = () => {
12861
+ blockingClient.disconnect();
12862
+ };
12863
+ signal.addEventListener("abort", cleanup, { once: true });
12864
+ if (signal.aborted) {
12865
+ return null;
12866
+ }
12867
+ }
12868
+ const result = await blockingClient.blpop(workerQueueKey, timeoutSeconds);
12869
+ if (!result) {
12870
+ return null;
12871
+ }
12872
+ const [, messageKey] = result;
12873
+ this.logger.debug("Blocking pop received message", {
12874
+ workerQueueId,
12875
+ workerQueueKey,
12876
+ messageKey
12877
+ });
12878
+ return messageKey;
12879
+ } catch (error) {
12880
+ if (signal?.aborted) {
12881
+ return null;
12882
+ }
12883
+ this.logger.error("Blocking pop error", {
12884
+ workerQueueId,
12885
+ error: error instanceof Error ? error.message : String(error)
12886
+ });
12887
+ throw error;
12888
+ } finally {
12889
+ await blockingClient.quit().catch(() => {
12890
+ });
12891
+ }
12892
+ }
12893
+ /**
12894
+ * Non-blocking pop from a worker queue.
12895
+ *
12896
+ * @param workerQueueId - The worker queue identifier
12897
+ * @returns The message key and queue length, or null if empty
12898
+ */
12899
+ async pop(workerQueueId) {
12900
+ const workerQueueKey = this.keys.workerQueueKey(workerQueueId);
12901
+ const result = await this.redis.popWithLength(workerQueueKey);
12902
+ if (!result) {
12903
+ return null;
12904
+ }
12905
+ const [messageKey, queueLength] = result;
12906
+ this.logger.debug("Non-blocking pop received message", {
12907
+ workerQueueId,
12908
+ workerQueueKey,
12909
+ messageKey,
12910
+ queueLength
12911
+ });
12912
+ return { messageKey, queueLength: Number(queueLength) };
12913
+ }
12914
+ /**
12915
+ * Get the current length of a worker queue.
12916
+ */
12917
+ async getLength(workerQueueId) {
12918
+ const workerQueueKey = this.keys.workerQueueKey(workerQueueId);
12919
+ return await this.redis.llen(workerQueueKey);
12920
+ }
12921
+ /**
12922
+ * Peek at all messages in a worker queue without removing them.
12923
+ * Useful for debugging and tests.
12924
+ */
12925
+ async peek(workerQueueId) {
12926
+ const workerQueueKey = this.keys.workerQueueKey(workerQueueId);
12927
+ return await this.redis.lrange(workerQueueKey, 0, -1);
12928
+ }
12929
+ /**
12930
+ * Remove a specific message from the worker queue.
12931
+ * Used when a message needs to be removed without processing.
12932
+ *
12933
+ * @param workerQueueId - The worker queue identifier
12934
+ * @param messageKey - The message key to remove
12935
+ * @returns Number of removed items
12936
+ */
12937
+ async remove(workerQueueId, messageKey) {
12938
+ const workerQueueKey = this.keys.workerQueueKey(workerQueueId);
12939
+ return await this.redis.lrem(workerQueueKey, 0, messageKey);
12940
+ }
12941
+ /**
12942
+ * Clear all messages from a worker queue.
12943
+ */
12944
+ async clear(workerQueueId) {
12945
+ const workerQueueKey = this.keys.workerQueueKey(workerQueueId);
12946
+ await this.redis.del(workerQueueKey);
12947
+ }
12948
+ /**
12949
+ * Close the Redis connection.
12950
+ */
12951
+ async close() {
12952
+ await this.redis.quit();
12953
+ }
12954
+ // ============================================================================
12955
+ // Private - Register Commands
12956
+ // ============================================================================
12957
+ /**
12958
+ * Initialize custom Redis commands.
12959
+ */
12960
+ #registerCommands() {
12961
+ this.redis.defineCommand("popWithLength", {
12962
+ numberOfKeys: 1,
12963
+ lua: `
12964
+ local workerQueueKey = KEYS[1]
12965
+
12966
+ -- Pop the first message
12967
+ local messageKey = redis.call('LPOP', workerQueueKey)
12968
+ if not messageKey then
12969
+ return nil
12970
+ end
12971
+
12972
+ -- Get remaining queue length
12973
+ local queueLength = redis.call('LLEN', workerQueueKey)
12974
+
12975
+ return {messageKey, queueLength}
12976
+ `
12977
+ });
12978
+ }
12979
+ /**
12980
+ * Register custom commands on an external Redis client.
12981
+ * Use this when initializing FairQueue with worker queues.
12982
+ */
12983
+ registerCommands(redis) {
12984
+ redis.defineCommand("popWithLength", {
12985
+ numberOfKeys: 1,
12986
+ lua: `
12987
+ local workerQueueKey = KEYS[1]
12988
+
12989
+ -- Pop the first message
12990
+ local messageKey = redis.call('LPOP', workerQueueKey)
12991
+ if not messageKey then
12992
+ return nil
12993
+ end
12994
+
12995
+ -- Get remaining queue length
12996
+ local queueLength = redis.call('LLEN', workerQueueKey)
12997
+
12998
+ return {messageKey, queueLength}
12999
+ `
13000
+ });
13001
+ }
13002
+ };
13003
+
13004
+ // src/fair-queue/keyProducer.ts
13005
+ var DefaultFairQueueKeyProducer = class {
13006
+ prefix;
13007
+ separator;
13008
+ constructor(options = {}) {
13009
+ this.prefix = options.prefix ?? "fq";
13010
+ this.separator = options.separator ?? ":";
13011
+ }
13012
+ // ============================================================================
13013
+ // Master Queue Keys
13014
+ // ============================================================================
13015
+ masterQueueKey(shardId) {
13016
+ return this.#buildKey("master", shardId.toString());
13017
+ }
13018
+ // ============================================================================
13019
+ // Queue Keys
13020
+ // ============================================================================
13021
+ queueKey(queueId) {
13022
+ return this.#buildKey("queue", queueId);
13023
+ }
13024
+ queueItemsKey(queueId) {
13025
+ return this.#buildKey("queue", queueId, "items");
13026
+ }
13027
+ // ============================================================================
13028
+ // Concurrency Keys
13029
+ // ============================================================================
13030
+ concurrencyKey(groupName, groupId) {
13031
+ return this.#buildKey("concurrency", groupName, groupId);
13032
+ }
13033
+ // ============================================================================
13034
+ // In-Flight Keys
13035
+ // ============================================================================
13036
+ inflightKey(shardId) {
13037
+ return this.#buildKey("inflight", shardId.toString());
13038
+ }
13039
+ inflightDataKey(shardId) {
13040
+ return this.#buildKey("inflight", shardId.toString(), "data");
13041
+ }
13042
+ // ============================================================================
13043
+ // Worker Queue Keys
13044
+ // ============================================================================
13045
+ workerQueueKey(consumerId) {
13046
+ return this.#buildKey("worker", consumerId);
13047
+ }
13048
+ // ============================================================================
13049
+ // Dead Letter Queue Keys
13050
+ // ============================================================================
13051
+ deadLetterQueueKey(tenantId) {
13052
+ return this.#buildKey("dlq", tenantId);
13053
+ }
13054
+ deadLetterQueueDataKey(tenantId) {
13055
+ return this.#buildKey("dlq", tenantId, "data");
13056
+ }
13057
+ // ============================================================================
13058
+ // Extraction Methods
13059
+ // ============================================================================
13060
+ /**
13061
+ * Extract tenant ID from a queue ID.
13062
+ * Default implementation assumes queue IDs are formatted as: tenant:{tenantId}:...
13063
+ * Override this method for custom queue ID formats.
13064
+ */
13065
+ extractTenantId(queueId) {
13066
+ const parts = queueId.split(this.separator);
13067
+ if (parts.length >= 2 && parts[0] === "tenant" && parts[1]) {
13068
+ return parts[1];
13069
+ }
13070
+ return parts[0] ?? "";
13071
+ }
13072
+ /**
13073
+ * Extract a group ID from a queue ID.
13074
+ * Default implementation looks for pattern: {groupName}:{groupId}:...
13075
+ * Override this method for custom queue ID formats.
13076
+ */
13077
+ extractGroupId(groupName, queueId) {
13078
+ const parts = queueId.split(this.separator);
13079
+ for (let i = 0; i < parts.length - 1; i++) {
13080
+ if (parts[i] === groupName) {
13081
+ const nextPart = parts[i + 1];
13082
+ if (nextPart) {
13083
+ return nextPart;
13084
+ }
13085
+ }
13086
+ }
13087
+ return "";
13088
+ }
13089
+ // ============================================================================
13090
+ // Helper Methods
13091
+ // ============================================================================
13092
+ #buildKey(...parts) {
13093
+ return [this.prefix, ...parts].join(this.separator);
13094
+ }
13095
+ };
13096
+ var CallbackFairQueueKeyProducer = class extends DefaultFairQueueKeyProducer {
13097
+ tenantExtractor;
13098
+ groupExtractor;
13099
+ constructor(options) {
13100
+ super({ prefix: options.prefix, separator: options.separator });
13101
+ this.tenantExtractor = options.extractTenantId;
13102
+ this.groupExtractor = options.extractGroupId;
13103
+ }
13104
+ extractTenantId(queueId) {
13105
+ return this.tenantExtractor(queueId);
13106
+ }
13107
+ extractGroupId(groupName, queueId) {
13108
+ return this.groupExtractor(groupName, queueId);
13109
+ }
13110
+ };
13111
+
13112
+ // src/fair-queue/scheduler.ts
13113
+ var BaseScheduler = class {
13114
+ /**
13115
+ * Called after processing a message to update scheduler state.
13116
+ * Default implementation does nothing.
13117
+ */
13118
+ async recordProcessed(_tenantId, _queueId) {
13119
+ }
13120
+ /**
13121
+ * Initialize the scheduler.
13122
+ * Default implementation does nothing.
13123
+ */
13124
+ async initialize() {
13125
+ }
13126
+ /**
13127
+ * Cleanup scheduler resources.
13128
+ * Default implementation does nothing.
13129
+ */
13130
+ async close() {
13131
+ }
13132
+ /**
13133
+ * Helper to group queues by tenant.
13134
+ */
13135
+ groupQueuesByTenant(queues) {
13136
+ const grouped = /* @__PURE__ */ new Map();
13137
+ for (const { queueId, tenantId } of queues) {
13138
+ const existing = grouped.get(tenantId) ?? [];
13139
+ existing.push(queueId);
13140
+ grouped.set(tenantId, existing);
13141
+ }
13142
+ return grouped;
13143
+ }
13144
+ /**
13145
+ * Helper to convert grouped queues to TenantQueues array.
13146
+ */
13147
+ toTenantQueuesArray(grouped) {
13148
+ return Array.from(grouped.entries()).map(([tenantId, queues]) => ({
13149
+ tenantId,
13150
+ queues
13151
+ }));
13152
+ }
13153
+ /**
13154
+ * Helper to filter out tenants at capacity.
13155
+ */
13156
+ async filterAtCapacity(tenants, context2, groupName = "tenant") {
13157
+ const filtered = [];
13158
+ for (const tenant of tenants) {
13159
+ const isAtCapacity = await context2.isAtCapacity(groupName, tenant.tenantId);
13160
+ if (!isAtCapacity) {
13161
+ filtered.push(tenant);
13162
+ }
13163
+ }
13164
+ return filtered;
13165
+ }
13166
+ };
13167
+ var NoopScheduler = class extends BaseScheduler {
13168
+ async selectQueues(_masterQueueShard, _consumerId, _context) {
13169
+ return [];
13170
+ }
13171
+ };
13172
+
13173
+ // src/fair-queue/schedulers/drr.ts
13174
+ var DRRScheduler = class extends BaseScheduler {
13175
+ constructor(config) {
13176
+ super();
13177
+ this.config = config;
13178
+ this.redis = createRedisClient(config.redis);
13179
+ this.keys = config.keys;
13180
+ this.quantum = config.quantum;
13181
+ this.maxDeficit = config.maxDeficit;
13182
+ this.logger = config.logger ?? {
13183
+ debug: () => {
13184
+ },
13185
+ error: () => {
13186
+ }
13187
+ };
13188
+ this.#registerCommands();
13189
+ }
13190
+ redis;
13191
+ keys;
13192
+ quantum;
13193
+ maxDeficit;
13194
+ logger;
13195
+ // ============================================================================
13196
+ // FairScheduler Implementation
13197
+ // ============================================================================
13198
+ /**
13199
+ * Select queues for processing using DRR algorithm.
13200
+ *
13201
+ * Algorithm:
13202
+ * 1. Get all queues from the master shard
13203
+ * 2. Group by tenant
13204
+ * 3. Filter out tenants at concurrency capacity
13205
+ * 4. Add quantum to each tenant's deficit (atomically)
13206
+ * 5. Select queues from tenants with deficit >= 1
13207
+ * 6. Order tenants by deficit (highest first for fairness)
13208
+ */
13209
+ async selectQueues(masterQueueShard, consumerId, context2) {
13210
+ const queues = await this.#getQueuesFromShard(masterQueueShard);
13211
+ if (queues.length === 0) {
13212
+ return [];
13213
+ }
13214
+ const queuesByTenant = this.groupQueuesByTenant(
13215
+ queues.map((q) => ({ queueId: q.queueId, tenantId: q.tenantId }))
13216
+ );
13217
+ const tenantIds = Array.from(queuesByTenant.keys());
13218
+ const deficits = await this.#addQuantumToTenants(tenantIds);
13219
+ const tenantData = await Promise.all(
13220
+ tenantIds.map(async (tenantId, index) => {
13221
+ const isAtCapacity = await context2.isAtCapacity("tenant", tenantId);
13222
+ return {
13223
+ tenantId,
13224
+ deficit: deficits[index] ?? 0,
13225
+ queues: queuesByTenant.get(tenantId) ?? [],
13226
+ isAtCapacity
13227
+ };
13228
+ })
13229
+ );
13230
+ const eligibleTenants = tenantData.filter(
13231
+ (t) => !t.isAtCapacity && t.deficit >= 1
13232
+ );
13233
+ const blockedTenants = tenantData.filter((t) => t.isAtCapacity);
13234
+ if (blockedTenants.length > 0) {
13235
+ this.logger.debug("DRR: tenants blocked by concurrency", {
13236
+ blockedCount: blockedTenants.length,
13237
+ blockedTenants: blockedTenants.map((t) => t.tenantId)
13238
+ });
13239
+ }
13240
+ eligibleTenants.sort((a, b) => b.deficit - a.deficit);
13241
+ this.logger.debug("DRR: queue selection complete", {
13242
+ totalQueues: queues.length,
13243
+ totalTenants: tenantIds.length,
13244
+ eligibleTenants: eligibleTenants.length,
13245
+ topTenantDeficit: eligibleTenants[0]?.deficit
13246
+ });
13247
+ return eligibleTenants.map((t) => ({
13248
+ tenantId: t.tenantId,
13249
+ queues: t.queues
13250
+ }));
13251
+ }
13252
+ /**
13253
+ * Record that a message was processed from a tenant.
13254
+ * Decrements the tenant's deficit.
13255
+ */
13256
+ async recordProcessed(tenantId, _queueId) {
13257
+ await this.#decrementDeficit(tenantId);
13258
+ }
13259
+ async close() {
13260
+ await this.redis.quit();
13261
+ }
13262
+ // ============================================================================
13263
+ // Public Methods for Deficit Management
13264
+ // ============================================================================
13265
+ /**
13266
+ * Get the current deficit for a tenant.
13267
+ */
13268
+ async getDeficit(tenantId) {
13269
+ const key = this.#deficitKey();
13270
+ const value = await this.redis.hget(key, tenantId);
13271
+ return value ? parseFloat(value) : 0;
13272
+ }
13273
+ /**
13274
+ * Reset deficit for a tenant.
13275
+ * Used when a tenant has no more active queues.
13276
+ */
13277
+ async resetDeficit(tenantId) {
13278
+ const key = this.#deficitKey();
13279
+ await this.redis.hdel(key, tenantId);
13280
+ }
13281
+ /**
13282
+ * Get all tenant deficits.
13283
+ */
13284
+ async getAllDeficits() {
13285
+ const key = this.#deficitKey();
13286
+ const data = await this.redis.hgetall(key);
13287
+ const result = /* @__PURE__ */ new Map();
13288
+ for (const [tenantId, value] of Object.entries(data)) {
13289
+ result.set(tenantId, parseFloat(value));
13290
+ }
13291
+ return result;
13292
+ }
13293
+ // ============================================================================
13294
+ // Private Methods
13295
+ // ============================================================================
13296
+ #deficitKey() {
13297
+ return `${this.keys.masterQueueKey(0).split(":")[0]}:drr:deficit`;
13298
+ }
13299
+ async #getQueuesFromShard(shardKey) {
13300
+ const now = Date.now();
13301
+ const results = await this.redis.zrangebyscore(
13302
+ shardKey,
13303
+ "-inf",
13304
+ now,
13305
+ "WITHSCORES",
13306
+ "LIMIT",
13307
+ 0,
13308
+ 1e3
13309
+ // Limit for performance
13310
+ );
13311
+ const queues = [];
13312
+ for (let i = 0; i < results.length; i += 2) {
13313
+ const queueId = results[i];
13314
+ const scoreStr = results[i + 1];
13315
+ if (queueId && scoreStr) {
13316
+ queues.push({
13317
+ queueId,
13318
+ score: parseFloat(scoreStr),
13319
+ tenantId: this.keys.extractTenantId(queueId)
13320
+ });
13321
+ }
13322
+ }
13323
+ return queues;
13324
+ }
13325
+ /**
13326
+ * Add quantum to multiple tenants atomically.
13327
+ * Returns the new deficit values.
13328
+ */
13329
+ async #addQuantumToTenants(tenantIds) {
13330
+ if (tenantIds.length === 0) {
13331
+ return [];
13332
+ }
13333
+ const key = this.#deficitKey();
13334
+ const results = await this.redis.drrAddQuantum(
13335
+ key,
13336
+ this.quantum.toString(),
13337
+ this.maxDeficit.toString(),
13338
+ ...tenantIds
13339
+ );
13340
+ return results.map((r) => parseFloat(r));
13341
+ }
13342
+ /**
13343
+ * Decrement deficit for a tenant atomically.
13344
+ */
13345
+ async #decrementDeficit(tenantId) {
13346
+ const key = this.#deficitKey();
13347
+ const result = await this.redis.drrDecrementDeficit(key, tenantId);
13348
+ return parseFloat(result);
13349
+ }
13350
+ #registerCommands() {
13351
+ this.redis.defineCommand("drrAddQuantum", {
13352
+ numberOfKeys: 1,
13353
+ lua: `
13354
+ local deficitKey = KEYS[1]
13355
+ local quantum = tonumber(ARGV[1])
13356
+ local maxDeficit = tonumber(ARGV[2])
13357
+ local results = {}
13358
+
13359
+ for i = 3, #ARGV do
13360
+ local tenantId = ARGV[i]
13361
+
13362
+ -- Add quantum to deficit
13363
+ local newDeficit = redis.call('HINCRBYFLOAT', deficitKey, tenantId, quantum)
13364
+ newDeficit = tonumber(newDeficit)
13365
+
13366
+ -- Cap at maxDeficit
13367
+ if newDeficit > maxDeficit then
13368
+ redis.call('HSET', deficitKey, tenantId, maxDeficit)
13369
+ newDeficit = maxDeficit
13370
+ end
13371
+
13372
+ table.insert(results, tostring(newDeficit))
13373
+ end
13374
+
13375
+ return results
13376
+ `
13377
+ });
13378
+ this.redis.defineCommand("drrDecrementDeficit", {
13379
+ numberOfKeys: 1,
13380
+ lua: `
13381
+ local deficitKey = KEYS[1]
13382
+ local tenantId = ARGV[1]
13383
+
13384
+ local newDeficit = redis.call('HINCRBYFLOAT', deficitKey, tenantId, -1)
13385
+ newDeficit = tonumber(newDeficit)
13386
+
13387
+ -- Floor at 0
13388
+ if newDeficit < 0 then
13389
+ redis.call('HSET', deficitKey, tenantId, 0)
13390
+ newDeficit = 0
13391
+ end
13392
+
13393
+ return tostring(newDeficit)
13394
+ `
13395
+ });
13396
+ }
13397
+ };
13398
+ var defaultBiases = {
13399
+ concurrencyLimitBias: 0,
13400
+ availableCapacityBias: 0,
13401
+ queueAgeRandomization: 0
13402
+ };
13403
+ var WeightedScheduler = class extends BaseScheduler {
13404
+ constructor(config) {
13405
+ super();
13406
+ this.config = config;
13407
+ this.redis = createRedisClient(config.redis);
13408
+ this.keys = config.keys;
13409
+ this.rng = seedrandom(config.seed);
13410
+ this.biases = config.biases ?? defaultBiases;
13411
+ this.defaultTenantLimit = config.defaultTenantConcurrencyLimit ?? 100;
13412
+ this.masterQueueLimit = config.masterQueueLimit ?? 100;
13413
+ this.reuseSnapshotCount = config.reuseSnapshotCount ?? 0;
13414
+ this.maximumTenantCount = config.maximumTenantCount ?? 0;
13415
+ }
13416
+ redis;
13417
+ keys;
13418
+ rng;
13419
+ biases;
13420
+ defaultTenantLimit;
13421
+ masterQueueLimit;
13422
+ reuseSnapshotCount;
13423
+ maximumTenantCount;
13424
+ // Snapshot cache
13425
+ snapshotCache = /* @__PURE__ */ new Map();
13426
+ // ============================================================================
13427
+ // FairScheduler Implementation
13428
+ // ============================================================================
13429
+ async selectQueues(masterQueueShard, consumerId, context2) {
13430
+ const snapshot = await this.#getOrCreateSnapshot(
13431
+ masterQueueShard,
13432
+ consumerId,
13433
+ context2
13434
+ );
13435
+ if (snapshot.queues.length === 0) {
13436
+ return [];
13437
+ }
13438
+ const shuffledTenants = this.#shuffleTenantsByWeight(snapshot);
13439
+ return shuffledTenants.map((tenantId) => ({
13440
+ tenantId,
13441
+ queues: this.#orderQueuesForTenant(snapshot, tenantId)
13442
+ }));
13443
+ }
13444
+ async close() {
13445
+ this.snapshotCache.clear();
13446
+ await this.redis.quit();
13447
+ }
13448
+ // ============================================================================
13449
+ // Private Methods
13450
+ // ============================================================================
13451
+ async #getOrCreateSnapshot(masterQueueShard, consumerId, context2) {
13452
+ const cacheKey = `${masterQueueShard}:${consumerId}`;
13453
+ if (this.reuseSnapshotCount > 0) {
13454
+ const cached = this.snapshotCache.get(cacheKey);
13455
+ if (cached && cached.reuseCount < this.reuseSnapshotCount) {
13456
+ this.snapshotCache.set(cacheKey, {
13457
+ snapshot: cached.snapshot,
13458
+ reuseCount: cached.reuseCount + 1
13459
+ });
13460
+ return cached.snapshot;
13461
+ }
13462
+ }
13463
+ const snapshot = await this.#createSnapshot(masterQueueShard, context2);
13464
+ if (this.reuseSnapshotCount > 0) {
13465
+ this.snapshotCache.set(cacheKey, { snapshot, reuseCount: 0 });
13466
+ }
13467
+ return snapshot;
13468
+ }
13469
+ async #createSnapshot(masterQueueShard, context2) {
13470
+ const now = Date.now();
13471
+ let rawQueues = await this.#getQueuesFromShard(masterQueueShard, now);
13472
+ if (rawQueues.length === 0) {
13473
+ return { id: crypto.randomUUID(), tenants: /* @__PURE__ */ new Map(), queues: [] };
13474
+ }
13475
+ if (this.maximumTenantCount > 0) {
13476
+ rawQueues = this.#selectTopTenantQueues(rawQueues);
13477
+ }
13478
+ const tenantIds = /* @__PURE__ */ new Set();
13479
+ const queuesByTenant = /* @__PURE__ */ new Map();
13480
+ for (const queue of rawQueues) {
13481
+ tenantIds.add(queue.tenantId);
13482
+ const tenantQueues = queuesByTenant.get(queue.tenantId) ?? [];
13483
+ tenantQueues.push({
13484
+ queueId: queue.queueId,
13485
+ age: now - queue.score
13486
+ });
13487
+ queuesByTenant.set(queue.tenantId, tenantQueues);
13488
+ }
13489
+ const tenants = /* @__PURE__ */ new Map();
13490
+ for (const tenantId of tenantIds) {
13491
+ const [current, limit] = await Promise.all([
13492
+ context2.getCurrentConcurrency("tenant", tenantId),
13493
+ context2.getConcurrencyLimit("tenant", tenantId)
13494
+ ]);
13495
+ if (current >= limit) {
13496
+ continue;
13497
+ }
13498
+ tenants.set(tenantId, {
13499
+ tenantId,
13500
+ concurrency: { current, limit },
13501
+ queues: queuesByTenant.get(tenantId) ?? []
13502
+ });
13503
+ }
13504
+ const queues = rawQueues.filter((q) => tenants.has(q.tenantId)).map((q) => ({
13505
+ queueId: q.queueId,
13506
+ tenantId: q.tenantId,
13507
+ age: now - q.score
13508
+ }));
13509
+ return {
13510
+ id: crypto.randomUUID(),
13511
+ tenants,
13512
+ queues
13513
+ };
13514
+ }
13515
+ async #getQueuesFromShard(shardKey, maxScore) {
13516
+ const results = await this.redis.zrangebyscore(
13517
+ shardKey,
13518
+ "-inf",
13519
+ maxScore,
13520
+ "WITHSCORES",
13521
+ "LIMIT",
13522
+ 0,
13523
+ this.masterQueueLimit
13524
+ );
13525
+ const queues = [];
13526
+ for (let i = 0; i < results.length; i += 2) {
13527
+ const queueId = results[i];
13528
+ const scoreStr = results[i + 1];
13529
+ if (queueId && scoreStr) {
13530
+ queues.push({
13531
+ queueId,
13532
+ score: parseFloat(scoreStr),
13533
+ tenantId: this.keys.extractTenantId(queueId)
13534
+ });
13535
+ }
13536
+ }
13537
+ return queues;
13538
+ }
13539
+ #selectTopTenantQueues(queues) {
13540
+ const queuesByTenant = /* @__PURE__ */ new Map();
13541
+ for (const queue of queues) {
13542
+ const tenantQueues = queuesByTenant.get(queue.tenantId) ?? [];
13543
+ tenantQueues.push(queue);
13544
+ queuesByTenant.set(queue.tenantId, tenantQueues);
13545
+ }
13546
+ const tenantAges = Array.from(queuesByTenant.entries()).map(([tenantId, tQueues]) => {
13547
+ const avgAge = tQueues.reduce((sum, q) => sum + q.score, 0) / tQueues.length;
13548
+ return { tenantId, avgAge };
13549
+ });
13550
+ const maxAge = Math.max(...tenantAges.map((t) => t.avgAge));
13551
+ const weightedTenants = maxAge === 0 ? tenantAges.map((t) => ({
13552
+ tenantId: t.tenantId,
13553
+ weight: 1 / tenantAges.length
13554
+ })) : tenantAges.map((t) => ({
13555
+ tenantId: t.tenantId,
13556
+ weight: t.avgAge / maxAge
13557
+ }));
13558
+ const selectedTenants = /* @__PURE__ */ new Set();
13559
+ let remaining = [...weightedTenants];
13560
+ let totalWeight = remaining.reduce((sum, t) => sum + t.weight, 0);
13561
+ while (selectedTenants.size < this.maximumTenantCount && remaining.length > 0) {
13562
+ let random = this.rng() * totalWeight;
13563
+ let index = 0;
13564
+ while (random > 0 && index < remaining.length) {
13565
+ const item = remaining[index];
13566
+ if (item) {
13567
+ random -= item.weight;
13568
+ }
13569
+ index++;
13570
+ }
13571
+ index = Math.max(0, index - 1);
13572
+ const selected = remaining[index];
13573
+ if (selected) {
13574
+ selectedTenants.add(selected.tenantId);
13575
+ totalWeight -= selected.weight;
13576
+ remaining.splice(index, 1);
13577
+ }
13578
+ }
13579
+ return queues.filter((q) => selectedTenants.has(q.tenantId));
13580
+ }
13581
+ #shuffleTenantsByWeight(snapshot) {
13582
+ const tenantIds = Array.from(snapshot.tenants.keys());
13583
+ if (tenantIds.length === 0) {
13584
+ return [];
13585
+ }
13586
+ const { concurrencyLimitBias, availableCapacityBias } = this.biases;
13587
+ if (concurrencyLimitBias === 0 && availableCapacityBias === 0) {
13588
+ return this.#shuffle(tenantIds);
13589
+ }
13590
+ const maxLimit = Math.max(
13591
+ ...tenantIds.map((id) => snapshot.tenants.get(id).concurrency.limit)
13592
+ );
13593
+ const weightedTenants = tenantIds.map((tenantId) => {
13594
+ const tenant = snapshot.tenants.get(tenantId);
13595
+ let weight = 1;
13596
+ if (concurrencyLimitBias > 0) {
13597
+ const normalizedLimit = maxLimit > 0 ? tenant.concurrency.limit / maxLimit : 0;
13598
+ weight *= 1 + Math.pow(normalizedLimit * concurrencyLimitBias, 2);
13599
+ }
13600
+ if (availableCapacityBias > 0) {
13601
+ const usedPercentage = tenant.concurrency.limit > 0 ? tenant.concurrency.current / tenant.concurrency.limit : 1;
13602
+ const availableBonus = 1 - usedPercentage;
13603
+ weight *= 1 + Math.pow(availableBonus * availableCapacityBias, 2);
13604
+ }
13605
+ return { tenantId, weight };
13606
+ });
13607
+ return this.#weightedShuffle(weightedTenants);
13608
+ }
13609
+ #orderQueuesForTenant(snapshot, tenantId) {
13610
+ const tenant = snapshot.tenants.get(tenantId);
13611
+ if (!tenant || tenant.queues.length === 0) {
13612
+ return [];
13613
+ }
13614
+ const queues = [...tenant.queues];
13615
+ const { queueAgeRandomization } = this.biases;
13616
+ if (queueAgeRandomization === 0) {
13617
+ return queues.sort((a, b) => b.age - a.age).map((q) => q.queueId);
13618
+ }
13619
+ const maxAge = Math.max(...queues.map((q) => q.age));
13620
+ const ageDenom = maxAge === 0 ? 1 : maxAge;
13621
+ const weightedQueues = queues.map((q) => ({
13622
+ queue: q,
13623
+ weight: 1 + q.age / ageDenom * queueAgeRandomization
13624
+ }));
13625
+ const result = [];
13626
+ let remaining = [...weightedQueues];
13627
+ let totalWeight = remaining.reduce((sum, q) => sum + q.weight, 0);
13628
+ while (remaining.length > 0) {
13629
+ let random = this.rng() * totalWeight;
13630
+ let index = 0;
13631
+ while (random > 0 && index < remaining.length) {
13632
+ const item = remaining[index];
13633
+ if (item) {
13634
+ random -= item.weight;
13635
+ }
13636
+ index++;
13637
+ }
13638
+ index = Math.max(0, index - 1);
13639
+ const selected = remaining[index];
13640
+ if (selected) {
13641
+ result.push(selected.queue.queueId);
13642
+ totalWeight -= selected.weight;
13643
+ remaining.splice(index, 1);
13644
+ }
13645
+ }
13646
+ return result;
13647
+ }
13648
+ #shuffle(array) {
13649
+ const result = [...array];
13650
+ for (let i = result.length - 1; i > 0; i--) {
13651
+ const j = Math.floor(this.rng() * (i + 1));
13652
+ const temp = result[i];
13653
+ const swapValue = result[j];
13654
+ if (temp !== void 0 && swapValue !== void 0) {
13655
+ result[i] = swapValue;
13656
+ result[j] = temp;
13657
+ }
13658
+ }
13659
+ return result;
13660
+ }
13661
+ #weightedShuffle(items) {
13662
+ const result = [];
13663
+ let remaining = [...items];
13664
+ let totalWeight = remaining.reduce((sum, item) => sum + item.weight, 0);
13665
+ while (remaining.length > 0) {
13666
+ let random = this.rng() * totalWeight;
13667
+ let index = 0;
13668
+ while (random > 0 && index < remaining.length) {
13669
+ const item = remaining[index];
13670
+ if (item) {
13671
+ random -= item.weight;
13672
+ }
13673
+ index++;
13674
+ }
13675
+ index = Math.max(0, index - 1);
13676
+ const selected = remaining[index];
13677
+ if (selected) {
13678
+ result.push(selected.tenantId);
13679
+ totalWeight -= selected.weight;
13680
+ remaining.splice(index, 1);
13681
+ }
13682
+ }
13683
+ return result;
13684
+ }
13685
+ };
13686
+
13687
+ // src/fair-queue/schedulers/roundRobin.ts
13688
+ var RoundRobinScheduler = class extends BaseScheduler {
13689
+ constructor(config) {
13690
+ super();
13691
+ this.config = config;
13692
+ this.redis = createRedisClient(config.redis);
13693
+ this.keys = config.keys;
13694
+ this.masterQueueLimit = config.masterQueueLimit ?? 1e3;
13695
+ }
13696
+ redis;
13697
+ keys;
13698
+ masterQueueLimit;
13699
+ // ============================================================================
13700
+ // FairScheduler Implementation
13701
+ // ============================================================================
13702
+ async selectQueues(masterQueueShard, consumerId, context2) {
13703
+ const now = Date.now();
13704
+ const queues = await this.#getQueuesFromShard(masterQueueShard, now);
13705
+ if (queues.length === 0) {
13706
+ return [];
13707
+ }
13708
+ const queuesByTenant = /* @__PURE__ */ new Map();
13709
+ const tenantOrder = [];
13710
+ for (const queue of queues) {
13711
+ if (!queuesByTenant.has(queue.tenantId)) {
13712
+ queuesByTenant.set(queue.tenantId, []);
13713
+ tenantOrder.push(queue.tenantId);
13714
+ }
13715
+ queuesByTenant.get(queue.tenantId).push(queue.queueId);
13716
+ }
13717
+ const lastServedIndex = await this.#getLastServedIndex(masterQueueShard);
13718
+ const rotatedTenants = this.#rotateArray(tenantOrder, lastServedIndex);
13719
+ const eligibleTenants = [];
13720
+ for (const tenantId of rotatedTenants) {
13721
+ const isAtCapacity = await context2.isAtCapacity("tenant", tenantId);
13722
+ if (!isAtCapacity) {
13723
+ const tenantQueues = queuesByTenant.get(tenantId) ?? [];
13724
+ eligibleTenants.push({
13725
+ tenantId,
13726
+ queues: tenantQueues
13727
+ });
13728
+ }
13729
+ }
13730
+ const firstEligible = eligibleTenants[0];
13731
+ if (firstEligible) {
13732
+ const firstTenantIndex = tenantOrder.indexOf(firstEligible.tenantId);
13733
+ await this.#setLastServedIndex(masterQueueShard, firstTenantIndex + 1);
13734
+ }
13735
+ return eligibleTenants;
13736
+ }
13737
+ async close() {
13738
+ await this.redis.quit();
13739
+ }
13740
+ // ============================================================================
13741
+ // Private Methods
13742
+ // ============================================================================
13743
+ async #getQueuesFromShard(shardKey, maxScore) {
13744
+ const results = await this.redis.zrangebyscore(
13745
+ shardKey,
13746
+ "-inf",
13747
+ maxScore,
13748
+ "WITHSCORES",
13749
+ "LIMIT",
13750
+ 0,
13751
+ this.masterQueueLimit
13752
+ );
13753
+ const queues = [];
13754
+ for (let i = 0; i < results.length; i += 2) {
13755
+ const queueId = results[i];
13756
+ const scoreStr = results[i + 1];
13757
+ if (queueId && scoreStr) {
13758
+ queues.push({
13759
+ queueId,
13760
+ score: parseFloat(scoreStr),
13761
+ tenantId: this.keys.extractTenantId(queueId)
13762
+ });
13763
+ }
13764
+ }
13765
+ return queues;
13766
+ }
13767
+ #lastServedKey(shardKey) {
13768
+ return `${shardKey}:rr:lastServed`;
13769
+ }
13770
+ async #getLastServedIndex(shardKey) {
13771
+ const key = this.#lastServedKey(shardKey);
13772
+ const value = await this.redis.get(key);
13773
+ return value ? parseInt(value, 10) : 0;
13774
+ }
13775
+ async #setLastServedIndex(shardKey, index) {
13776
+ const key = this.#lastServedKey(shardKey);
13777
+ await this.redis.set(key, index.toString());
13778
+ }
13779
+ #rotateArray(array, startIndex) {
13780
+ if (array.length === 0) return [];
13781
+ const normalizedIndex = startIndex % array.length;
13782
+ return [...array.slice(normalizedIndex), ...array.slice(0, normalizedIndex)];
13783
+ }
13784
+ };
13785
+ var ExponentialBackoffRetry = class {
13786
+ maxAttempts;
13787
+ options;
13788
+ constructor(options) {
13789
+ this.options = {
13790
+ maxAttempts: options?.maxAttempts ?? 12,
13791
+ factor: options?.factor ?? 2,
13792
+ minTimeoutInMs: options?.minTimeoutInMs ?? 1e3,
13793
+ maxTimeoutInMs: options?.maxTimeoutInMs ?? 36e5,
13794
+ // 1 hour
13795
+ randomize: options?.randomize ?? true
13796
+ };
13797
+ this.maxAttempts = this.options.maxAttempts ?? 12;
13798
+ }
13799
+ getNextDelay(attempt, _error) {
13800
+ if (attempt >= this.maxAttempts) {
13801
+ return null;
13802
+ }
13803
+ const delay = calculateNextRetryDelay(this.options, attempt);
13804
+ return delay ?? null;
13805
+ }
13806
+ };
13807
+ var FixedDelayRetry = class {
13808
+ maxAttempts;
13809
+ delayMs;
13810
+ constructor(options) {
13811
+ this.maxAttempts = options.maxAttempts;
13812
+ this.delayMs = options.delayMs;
13813
+ }
13814
+ getNextDelay(attempt, _error) {
13815
+ if (attempt >= this.maxAttempts) {
13816
+ return null;
13817
+ }
13818
+ return this.delayMs;
13819
+ }
13820
+ };
13821
+ var LinearBackoffRetry = class {
13822
+ maxAttempts;
13823
+ baseDelayMs;
13824
+ maxDelayMs;
13825
+ constructor(options) {
13826
+ this.maxAttempts = options.maxAttempts;
13827
+ this.baseDelayMs = options.baseDelayMs;
13828
+ this.maxDelayMs = options.maxDelayMs ?? options.baseDelayMs * options.maxAttempts;
13829
+ }
13830
+ getNextDelay(attempt, _error) {
13831
+ if (attempt >= this.maxAttempts) {
13832
+ return null;
13833
+ }
13834
+ const delay = this.baseDelayMs * attempt;
13835
+ return Math.min(delay, this.maxDelayMs);
13836
+ }
13837
+ };
13838
+ var NoRetry = class {
13839
+ maxAttempts = 1;
13840
+ getNextDelay(_attempt, _error) {
13841
+ return null;
13842
+ }
13843
+ };
13844
+ var ImmediateRetry = class {
13845
+ maxAttempts;
13846
+ constructor(maxAttempts) {
13847
+ this.maxAttempts = maxAttempts;
13848
+ }
13849
+ getNextDelay(attempt, _error) {
13850
+ if (attempt >= this.maxAttempts) {
13851
+ return null;
13852
+ }
13853
+ return 0;
13854
+ }
13855
+ };
13856
+ var CustomRetry = class {
13857
+ maxAttempts;
13858
+ calculateDelay;
13859
+ constructor(options) {
13860
+ this.maxAttempts = options.maxAttempts;
13861
+ this.calculateDelay = options.calculateDelay;
13862
+ }
13863
+ getNextDelay(attempt, error) {
13864
+ if (attempt >= this.maxAttempts) {
13865
+ return null;
13866
+ }
13867
+ return this.calculateDelay(attempt, error);
13868
+ }
13869
+ };
13870
+ var defaultRetryOptions = {
13871
+ maxAttempts: 12,
13872
+ factor: 2,
13873
+ minTimeoutInMs: 1e3,
13874
+ maxTimeoutInMs: 36e5,
13875
+ randomize: true
13876
+ };
13877
+ function createDefaultRetryStrategy() {
13878
+ return new ExponentialBackoffRetry(defaultRetryOptions);
13879
+ }
13880
+
13881
+ // src/fair-queue/index.ts
13882
+ var FairQueue = class {
13883
+ constructor(options) {
13884
+ this.options = options;
13885
+ this.redis = createRedisClient(options.redis);
13886
+ this.keys = options.keys;
13887
+ this.scheduler = options.scheduler;
13888
+ this.logger = options.logger ?? new Logger("FairQueue", "info");
13889
+ this.abortController = new AbortController();
13890
+ this.payloadSchema = options.payloadSchema;
13891
+ this.validateOnEnqueue = options.validateOnEnqueue ?? false;
13892
+ this.retryStrategy = options.retry?.strategy;
13893
+ this.deadLetterQueueEnabled = options.retry?.deadLetterQueue ?? true;
13894
+ this.shardCount = options.shardCount ?? 1;
13895
+ this.consumerCount = options.consumerCount ?? 1;
13896
+ this.consumerIntervalMs = options.consumerIntervalMs ?? 100;
13897
+ this.visibilityTimeoutMs = options.visibilityTimeoutMs ?? 3e4;
13898
+ this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? this.visibilityTimeoutMs / 3;
13899
+ this.reclaimIntervalMs = options.reclaimIntervalMs ?? 5e3;
13900
+ this.workerQueueEnabled = options.workerQueue?.enabled ?? false;
13901
+ this.workerQueueBlockingTimeoutSeconds = options.workerQueue?.blockingTimeoutSeconds ?? 10;
13902
+ this.workerQueueResolver = options.workerQueue?.resolveWorkerQueue;
13903
+ this.cooloffEnabled = options.cooloff?.enabled ?? true;
13904
+ this.cooloffThreshold = options.cooloff?.threshold ?? 10;
13905
+ this.cooloffPeriodMs = options.cooloff?.periodMs ?? 1e4;
13906
+ this.globalRateLimiter = options.globalRateLimiter;
13907
+ this.telemetry = new FairQueueTelemetry({
13908
+ tracer: options.tracer,
13909
+ meter: options.meter,
13910
+ name: options.name ?? "fairqueue"
13911
+ });
13912
+ this.masterQueue = new MasterQueue({
13913
+ redis: options.redis,
13914
+ keys: options.keys,
13915
+ shardCount: this.shardCount
13916
+ });
13917
+ if (options.concurrencyGroups && options.concurrencyGroups.length > 0) {
13918
+ this.concurrencyManager = new ConcurrencyManager({
13919
+ redis: options.redis,
13920
+ keys: options.keys,
13921
+ groups: options.concurrencyGroups
13922
+ });
13923
+ }
13924
+ this.visibilityManager = new VisibilityManager({
13925
+ redis: options.redis,
13926
+ keys: options.keys,
13927
+ shardCount: this.shardCount,
13928
+ defaultTimeoutMs: this.visibilityTimeoutMs,
13929
+ logger: {
13930
+ debug: (msg, ctx) => this.logger.debug(msg, ctx),
13931
+ error: (msg, ctx) => this.logger.error(msg, ctx)
13932
+ }
13933
+ });
13934
+ if (this.workerQueueEnabled) {
13935
+ this.workerQueueManager = new WorkerQueueManager({
13936
+ redis: options.redis,
13937
+ keys: options.keys,
13938
+ logger: {
13939
+ debug: (msg, ctx) => this.logger.debug(msg, ctx),
13940
+ error: (msg, ctx) => this.logger.error(msg, ctx)
13941
+ }
13942
+ });
13943
+ }
13944
+ this.#registerCommands();
13945
+ if (options.startConsumers !== false) {
13946
+ this.start();
13947
+ }
13948
+ }
13949
+ redis;
13950
+ keys;
13951
+ scheduler;
13952
+ masterQueue;
13953
+ concurrencyManager;
13954
+ visibilityManager;
13955
+ workerQueueManager;
13956
+ telemetry;
13957
+ logger;
13958
+ // Configuration
13959
+ payloadSchema;
13960
+ validateOnEnqueue;
13961
+ retryStrategy;
13962
+ deadLetterQueueEnabled;
13963
+ shardCount;
13964
+ consumerCount;
13965
+ consumerIntervalMs;
13966
+ visibilityTimeoutMs;
13967
+ heartbeatIntervalMs;
13968
+ reclaimIntervalMs;
13969
+ workerQueueEnabled;
13970
+ workerQueueBlockingTimeoutSeconds;
13971
+ workerQueueResolver;
13972
+ // Cooloff state
13973
+ cooloffEnabled;
13974
+ cooloffThreshold;
13975
+ cooloffPeriodMs;
13976
+ queueCooloffStates = /* @__PURE__ */ new Map();
13977
+ // Global rate limiter
13978
+ globalRateLimiter;
13979
+ // Runtime state
13980
+ messageHandler;
13981
+ isRunning = false;
13982
+ abortController;
13983
+ masterQueueConsumerLoops = [];
13984
+ workerQueueConsumerLoops = [];
13985
+ reclaimLoop;
13986
+ // Queue descriptor cache for message processing
13987
+ queueDescriptorCache = /* @__PURE__ */ new Map();
13988
+ // ============================================================================
13989
+ // Public API - Telemetry
13990
+ // ============================================================================
13991
+ /**
13992
+ * Register observable gauge callbacks for telemetry.
13993
+ * Call this after FairQueue is created to enable gauge metrics.
13994
+ *
13995
+ * @param options.observedTenants - List of tenant IDs to observe for DLQ metrics
13996
+ */
13997
+ registerTelemetryGauges(options) {
13998
+ this.telemetry.registerGaugeCallbacks({
13999
+ getMasterQueueLength: async (shardId) => {
14000
+ return await this.masterQueue.getShardQueueCount(shardId);
14001
+ },
14002
+ getInflightCount: async (shardId) => {
14003
+ return await this.visibilityManager.getInflightCount(shardId);
14004
+ },
14005
+ getDLQLength: async (tenantId) => {
14006
+ return await this.getDeadLetterQueueLength(tenantId);
14007
+ },
14008
+ shardCount: this.shardCount,
14009
+ observedTenants: options?.observedTenants
14010
+ });
14011
+ }
14012
+ // ============================================================================
14013
+ // Public API - Message Handler
14014
+ // ============================================================================
14015
+ /**
14016
+ * Set the message handler for processing dequeued messages.
14017
+ */
14018
+ onMessage(handler) {
14019
+ this.messageHandler = handler;
14020
+ }
14021
+ // ============================================================================
14022
+ // Public API - Enqueueing
14023
+ // ============================================================================
14024
+ /**
14025
+ * Enqueue a single message to a queue.
14026
+ */
14027
+ async enqueue(options) {
14028
+ return this.telemetry.trace(
14029
+ "enqueue",
14030
+ async (span) => {
14031
+ const messageId = options.messageId ?? nanoid();
14032
+ const timestamp = options.timestamp ?? Date.now();
14033
+ const queueKey = this.keys.queueKey(options.queueId);
14034
+ const queueItemsKey = this.keys.queueItemsKey(options.queueId);
14035
+ const shardId = this.masterQueue.getShardForQueue(options.queueId);
14036
+ const masterQueueKey = this.keys.masterQueueKey(shardId);
14037
+ if (this.validateOnEnqueue && this.payloadSchema) {
14038
+ const result = this.payloadSchema.safeParse(options.payload);
14039
+ if (!result.success) {
14040
+ throw new Error(`Payload validation failed: ${result.error.message}`);
14041
+ }
14042
+ }
14043
+ const descriptor = {
14044
+ id: options.queueId,
14045
+ tenantId: options.tenantId,
14046
+ metadata: options.metadata ?? {}
14047
+ };
14048
+ this.queueDescriptorCache.set(options.queueId, descriptor);
14049
+ const storedMessage = {
14050
+ id: messageId,
14051
+ queueId: options.queueId,
14052
+ tenantId: options.tenantId,
14053
+ payload: options.payload,
14054
+ timestamp,
14055
+ attempt: 1,
14056
+ workerQueue: this.workerQueueResolver ? this.workerQueueResolver({
14057
+ id: messageId,
14058
+ queueId: options.queueId,
14059
+ tenantId: options.tenantId,
14060
+ payload: options.payload,
14061
+ timestamp,
14062
+ attempt: 1,
14063
+ metadata: options.metadata
14064
+ }) : options.queueId,
14065
+ metadata: options.metadata
14066
+ };
14067
+ await this.redis.enqueueMessageAtomic(
14068
+ queueKey,
14069
+ queueItemsKey,
14070
+ masterQueueKey,
14071
+ options.queueId,
14072
+ messageId,
14073
+ timestamp.toString(),
14074
+ JSON.stringify(storedMessage)
14075
+ );
14076
+ span.setAttributes({
14077
+ [FairQueueAttributes.QUEUE_ID]: options.queueId,
14078
+ [FairQueueAttributes.TENANT_ID]: options.tenantId,
14079
+ [FairQueueAttributes.MESSAGE_ID]: messageId,
14080
+ [FairQueueAttributes.SHARD_ID]: shardId.toString()
14081
+ });
14082
+ this.telemetry.recordEnqueue(
14083
+ this.telemetry.messageAttributes({
14084
+ queueId: options.queueId,
14085
+ tenantId: options.tenantId,
14086
+ messageId
14087
+ })
14088
+ );
14089
+ this.logger.debug("Message enqueued", {
14090
+ queueId: options.queueId,
14091
+ messageId,
14092
+ timestamp
14093
+ });
14094
+ return messageId;
14095
+ },
14096
+ {
14097
+ kind: SpanKind.PRODUCER,
14098
+ attributes: {
14099
+ [MessagingAttributes.OPERATION]: "publish"
14100
+ }
14101
+ }
14102
+ );
14103
+ }
14104
+ /**
14105
+ * Enqueue multiple messages to a queue.
14106
+ */
14107
+ async enqueueBatch(options) {
14108
+ return this.telemetry.trace(
14109
+ "enqueueBatch",
14110
+ async (span) => {
14111
+ const queueKey = this.keys.queueKey(options.queueId);
14112
+ const queueItemsKey = this.keys.queueItemsKey(options.queueId);
14113
+ const shardId = this.masterQueue.getShardForQueue(options.queueId);
14114
+ const masterQueueKey = this.keys.masterQueueKey(shardId);
14115
+ const now = Date.now();
14116
+ const descriptor = {
14117
+ id: options.queueId,
14118
+ tenantId: options.tenantId,
14119
+ metadata: options.metadata ?? {}
14120
+ };
14121
+ this.queueDescriptorCache.set(options.queueId, descriptor);
14122
+ const messageIds = [];
14123
+ const args = [];
14124
+ for (const message of options.messages) {
14125
+ const messageId = message.messageId ?? nanoid();
14126
+ const timestamp = message.timestamp ?? now;
14127
+ if (this.validateOnEnqueue && this.payloadSchema) {
14128
+ const result = this.payloadSchema.safeParse(message.payload);
14129
+ if (!result.success) {
14130
+ throw new Error(
14131
+ `Payload validation failed for message ${messageId}: ${result.error.message}`
14132
+ );
14133
+ }
14134
+ }
14135
+ const storedMessage = {
14136
+ id: messageId,
14137
+ queueId: options.queueId,
14138
+ tenantId: options.tenantId,
14139
+ payload: message.payload,
14140
+ timestamp,
14141
+ attempt: 1,
14142
+ workerQueue: this.workerQueueResolver ? this.workerQueueResolver({
14143
+ id: messageId,
14144
+ queueId: options.queueId,
14145
+ tenantId: options.tenantId,
14146
+ payload: message.payload,
14147
+ timestamp,
14148
+ attempt: 1,
14149
+ metadata: options.metadata
14150
+ }) : options.queueId,
14151
+ metadata: options.metadata
14152
+ };
14153
+ messageIds.push(messageId);
14154
+ args.push(messageId, timestamp.toString(), JSON.stringify(storedMessage));
14155
+ }
14156
+ await this.redis.enqueueBatchAtomic(
14157
+ queueKey,
14158
+ queueItemsKey,
14159
+ masterQueueKey,
14160
+ options.queueId,
14161
+ ...args
14162
+ );
14163
+ span.setAttributes({
14164
+ [FairQueueAttributes.QUEUE_ID]: options.queueId,
14165
+ [FairQueueAttributes.TENANT_ID]: options.tenantId,
14166
+ [FairQueueAttributes.MESSAGE_COUNT]: messageIds.length,
14167
+ [FairQueueAttributes.SHARD_ID]: shardId.toString()
14168
+ });
14169
+ this.telemetry.recordEnqueueBatch(
14170
+ messageIds.length,
14171
+ this.telemetry.messageAttributes({
14172
+ queueId: options.queueId,
14173
+ tenantId: options.tenantId
14174
+ })
14175
+ );
14176
+ this.logger.debug("Batch enqueued", {
14177
+ queueId: options.queueId,
14178
+ messageCount: messageIds.length
14179
+ });
14180
+ return messageIds;
14181
+ },
14182
+ {
14183
+ kind: SpanKind.PRODUCER,
14184
+ attributes: {
14185
+ [MessagingAttributes.OPERATION]: "publish"
14186
+ }
14187
+ }
14188
+ );
14189
+ }
14190
+ // ============================================================================
14191
+ // Public API - Dead Letter Queue
14192
+ // ============================================================================
14193
+ /**
14194
+ * Get messages from the dead letter queue for a tenant.
14195
+ */
14196
+ async getDeadLetterMessages(tenantId, limit = 100) {
14197
+ if (!this.deadLetterQueueEnabled) {
14198
+ return [];
14199
+ }
14200
+ const dlqKey = this.keys.deadLetterQueueKey(tenantId);
14201
+ const dlqDataKey = this.keys.deadLetterQueueDataKey(tenantId);
14202
+ const results = await this.redis.zrange(dlqKey, 0, limit - 1, "WITHSCORES");
14203
+ const messages = [];
14204
+ for (let i = 0; i < results.length; i += 2) {
14205
+ const messageId = results[i];
14206
+ const deadLetteredAtStr = results[i + 1];
14207
+ if (!messageId || !deadLetteredAtStr) continue;
14208
+ const dataJson = await this.redis.hget(dlqDataKey, messageId);
14209
+ if (!dataJson) continue;
14210
+ try {
14211
+ const data = JSON.parse(dataJson);
14212
+ data.deadLetteredAt = parseFloat(deadLetteredAtStr);
14213
+ messages.push(data);
14214
+ } catch {
14215
+ this.logger.error("Failed to parse DLQ message", { messageId, tenantId });
14216
+ }
14217
+ }
14218
+ return messages;
14219
+ }
14220
+ /**
14221
+ * Redrive a message from DLQ back to its original queue.
14222
+ */
14223
+ async redriveMessage(tenantId, messageId) {
14224
+ if (!this.deadLetterQueueEnabled) {
14225
+ return false;
14226
+ }
14227
+ return this.telemetry.trace(
14228
+ "redriveMessage",
14229
+ async (span) => {
14230
+ const dlqKey = this.keys.deadLetterQueueKey(tenantId);
14231
+ const dlqDataKey = this.keys.deadLetterQueueDataKey(tenantId);
14232
+ const dataJson = await this.redis.hget(dlqDataKey, messageId);
14233
+ if (!dataJson) {
14234
+ return false;
14235
+ }
14236
+ const dlqMessage = JSON.parse(dataJson);
14237
+ await this.enqueue({
14238
+ queueId: dlqMessage.queueId,
14239
+ tenantId: dlqMessage.tenantId,
14240
+ payload: dlqMessage.payload,
14241
+ messageId: dlqMessage.id,
14242
+ timestamp: Date.now()
14243
+ });
14244
+ const pipeline = this.redis.pipeline();
14245
+ pipeline.zrem(dlqKey, messageId);
14246
+ pipeline.hdel(dlqDataKey, messageId);
14247
+ await pipeline.exec();
14248
+ span.setAttributes({
14249
+ [FairQueueAttributes.TENANT_ID]: tenantId,
14250
+ [FairQueueAttributes.MESSAGE_ID]: messageId
14251
+ });
14252
+ this.logger.info("Redrived message from DLQ", { tenantId, messageId });
14253
+ return true;
14254
+ },
14255
+ {
14256
+ kind: SpanKind.PRODUCER,
14257
+ attributes: {
14258
+ [MessagingAttributes.OPERATION]: "redrive"
14259
+ }
14260
+ }
14261
+ );
14262
+ }
14263
+ /**
14264
+ * Redrive all messages from DLQ back to their original queues.
14265
+ */
14266
+ async redriveAll(tenantId) {
14267
+ const messages = await this.getDeadLetterMessages(tenantId, 1e3);
14268
+ let count = 0;
14269
+ for (const message of messages) {
14270
+ const success = await this.redriveMessage(tenantId, message.id);
14271
+ if (success) count++;
14272
+ }
14273
+ return count;
14274
+ }
14275
+ /**
14276
+ * Purge all messages from a tenant's DLQ.
14277
+ */
14278
+ async purgeDeadLetterQueue(tenantId) {
14279
+ if (!this.deadLetterQueueEnabled) {
14280
+ return 0;
14281
+ }
14282
+ const dlqKey = this.keys.deadLetterQueueKey(tenantId);
14283
+ const dlqDataKey = this.keys.deadLetterQueueDataKey(tenantId);
14284
+ const count = await this.redis.zcard(dlqKey);
14285
+ const pipeline = this.redis.pipeline();
14286
+ pipeline.del(dlqKey);
14287
+ pipeline.del(dlqDataKey);
14288
+ await pipeline.exec();
14289
+ this.logger.info("Purged DLQ", { tenantId, count });
14290
+ return count;
14291
+ }
14292
+ /**
14293
+ * Get the number of messages in a tenant's DLQ.
14294
+ */
14295
+ async getDeadLetterQueueLength(tenantId) {
14296
+ if (!this.deadLetterQueueEnabled) {
14297
+ return 0;
14298
+ }
14299
+ const dlqKey = this.keys.deadLetterQueueKey(tenantId);
14300
+ return await this.redis.zcard(dlqKey);
14301
+ }
14302
+ // ============================================================================
14303
+ // Public API - Lifecycle
14304
+ // ============================================================================
14305
+ /**
14306
+ * Start the consumer loops and reclaim loop.
14307
+ */
14308
+ start() {
14309
+ if (this.isRunning) {
14310
+ return;
14311
+ }
14312
+ this.isRunning = true;
14313
+ this.abortController = new AbortController();
14314
+ if (this.workerQueueEnabled && this.workerQueueManager) {
14315
+ for (let shardId = 0; shardId < this.shardCount; shardId++) {
14316
+ const loop = this.#runMasterQueueConsumerLoop(shardId);
14317
+ this.masterQueueConsumerLoops.push(loop);
14318
+ }
14319
+ for (let consumerId = 0; consumerId < this.consumerCount; consumerId++) {
14320
+ const loop = this.#runWorkerQueueConsumerLoop(consumerId);
14321
+ this.workerQueueConsumerLoops.push(loop);
14322
+ }
14323
+ } else {
14324
+ for (let consumerId = 0; consumerId < this.consumerCount; consumerId++) {
14325
+ for (let shardId = 0; shardId < this.shardCount; shardId++) {
14326
+ const loop = this.#runDirectConsumerLoop(consumerId, shardId);
14327
+ this.masterQueueConsumerLoops.push(loop);
14328
+ }
14329
+ }
14330
+ }
14331
+ this.reclaimLoop = this.#runReclaimLoop();
14332
+ this.logger.info("FairQueue started", {
14333
+ consumerCount: this.consumerCount,
14334
+ shardCount: this.shardCount,
14335
+ workerQueueEnabled: this.workerQueueEnabled,
14336
+ consumerIntervalMs: this.consumerIntervalMs
14337
+ });
14338
+ }
14339
+ /**
14340
+ * Stop the consumer loops gracefully.
14341
+ */
14342
+ async stop() {
14343
+ if (!this.isRunning) {
14344
+ return;
14345
+ }
14346
+ this.isRunning = false;
14347
+ this.abortController.abort();
14348
+ await Promise.allSettled([
14349
+ ...this.masterQueueConsumerLoops,
14350
+ ...this.workerQueueConsumerLoops,
14351
+ this.reclaimLoop
14352
+ ]);
14353
+ this.masterQueueConsumerLoops = [];
14354
+ this.workerQueueConsumerLoops = [];
14355
+ this.reclaimLoop = void 0;
14356
+ this.logger.info("FairQueue stopped");
14357
+ }
14358
+ /**
14359
+ * Close all resources.
14360
+ */
14361
+ async close() {
14362
+ await this.stop();
14363
+ await Promise.all([
14364
+ this.masterQueue.close(),
14365
+ this.concurrencyManager?.close(),
14366
+ this.visibilityManager.close(),
14367
+ this.workerQueueManager?.close(),
14368
+ this.scheduler.close?.(),
14369
+ this.redis.quit()
14370
+ ]);
14371
+ }
14372
+ // ============================================================================
14373
+ // Public API - Inspection
14374
+ // ============================================================================
14375
+ /**
14376
+ * Get the number of messages in a queue.
14377
+ */
14378
+ async getQueueLength(queueId) {
14379
+ const queueKey = this.keys.queueKey(queueId);
14380
+ return await this.redis.zcard(queueKey);
14381
+ }
14382
+ /**
14383
+ * Get total queue count across all shards.
14384
+ */
14385
+ async getTotalQueueCount() {
14386
+ return await this.masterQueue.getTotalQueueCount();
14387
+ }
14388
+ /**
14389
+ * Get total in-flight message count.
14390
+ */
14391
+ async getTotalInflightCount() {
14392
+ return await this.visibilityManager.getTotalInflightCount();
14393
+ }
14394
+ /**
14395
+ * Get the shard ID for a queue.
14396
+ */
14397
+ getShardForQueue(queueId) {
14398
+ return this.masterQueue.getShardForQueue(queueId);
14399
+ }
14400
+ // ============================================================================
14401
+ // Private - Master Queue Consumer Loop (Two-Stage)
14402
+ // ============================================================================
14403
+ async #runMasterQueueConsumerLoop(shardId) {
14404
+ const loopId = `master-shard-${shardId}`;
14405
+ try {
14406
+ for await (const _ of setInterval$1(this.consumerIntervalMs, null, {
14407
+ signal: this.abortController.signal
14408
+ })) {
14409
+ try {
14410
+ await this.#processMasterQueueShard(loopId, shardId);
14411
+ } catch (error) {
14412
+ this.logger.error("Master queue consumer error", {
14413
+ loopId,
14414
+ shardId,
14415
+ error: error instanceof Error ? error.message : String(error)
14416
+ });
14417
+ }
14418
+ }
14419
+ } catch (error) {
14420
+ if (error instanceof Error && error.name === "AbortError") {
14421
+ this.logger.debug("Master queue consumer aborted", { loopId });
14422
+ return;
14423
+ }
14424
+ throw error;
14425
+ }
14426
+ }
14427
+ async #processMasterQueueShard(loopId, shardId) {
14428
+ const masterQueueKey = this.keys.masterQueueKey(shardId);
14429
+ const context2 = this.#createSchedulerContext();
14430
+ const tenantQueues = await this.scheduler.selectQueues(masterQueueKey, loopId, context2);
14431
+ if (tenantQueues.length === 0) {
14432
+ return;
14433
+ }
14434
+ for (const { tenantId, queues } of tenantQueues) {
14435
+ for (const queueId of queues) {
14436
+ if (this.cooloffEnabled && this.#isInCooloff(queueId)) {
14437
+ continue;
14438
+ }
14439
+ const processed = await this.#claimAndPushToWorkerQueue(loopId, queueId, tenantId, shardId);
14440
+ if (processed) {
14441
+ await this.scheduler.recordProcessed?.(tenantId, queueId);
14442
+ this.#resetCooloff(queueId);
14443
+ } else {
14444
+ this.#incrementCooloff(queueId);
14445
+ }
14446
+ }
14447
+ }
14448
+ }
14449
+ async #claimAndPushToWorkerQueue(loopId, queueId, tenantId, shardId) {
14450
+ const queueKey = this.keys.queueKey(queueId);
14451
+ const queueItemsKey = this.keys.queueItemsKey(queueId);
14452
+ const masterQueueKey = this.keys.masterQueueKey(shardId);
14453
+ const descriptor = this.queueDescriptorCache.get(queueId) ?? {
14454
+ id: queueId,
14455
+ tenantId,
14456
+ metadata: {}
14457
+ };
14458
+ if (this.concurrencyManager) {
14459
+ const check = await this.concurrencyManager.canProcess(descriptor);
14460
+ if (!check.allowed) {
14461
+ return false;
14462
+ }
14463
+ }
14464
+ if (this.globalRateLimiter) {
14465
+ const result = await this.globalRateLimiter.limit();
14466
+ if (!result.allowed && result.resetAt) {
14467
+ const waitMs = Math.max(0, result.resetAt - Date.now());
14468
+ if (waitMs > 0) {
14469
+ this.logger.debug("Global rate limit reached, waiting", { waitMs, loopId });
14470
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
14471
+ }
14472
+ }
14473
+ }
14474
+ const claimResult = await this.visibilityManager.claim(
14475
+ queueId,
14476
+ queueKey,
14477
+ queueItemsKey,
14478
+ loopId,
14479
+ this.visibilityTimeoutMs
14480
+ );
14481
+ if (!claimResult.claimed || !claimResult.message) {
14482
+ await this.redis.updateMasterQueueIfEmpty(masterQueueKey, queueKey, queueId);
14483
+ return false;
14484
+ }
14485
+ const { message } = claimResult;
14486
+ if (this.concurrencyManager) {
14487
+ const reserved = await this.concurrencyManager.reserve(descriptor, message.messageId);
14488
+ if (!reserved) {
14489
+ await this.visibilityManager.release(message.messageId, queueId, queueKey, queueItemsKey);
14490
+ return false;
14491
+ }
14492
+ }
14493
+ const workerQueueId = message.payload.workerQueue ?? queueId;
14494
+ const messageKey = `${message.messageId}:${queueId}`;
14495
+ await this.workerQueueManager.push(workerQueueId, messageKey);
14496
+ return true;
14497
+ }
14498
+ // ============================================================================
14499
+ // Private - Worker Queue Consumer Loop (Two-Stage)
14500
+ // ============================================================================
14501
+ async #runWorkerQueueConsumerLoop(consumerId) {
14502
+ const loopId = `worker-${consumerId}`;
14503
+ const workerQueueId = loopId;
14504
+ try {
14505
+ while (this.isRunning) {
14506
+ if (!this.messageHandler) {
14507
+ await new Promise((resolve) => setTimeout(resolve, this.consumerIntervalMs));
14508
+ continue;
14509
+ }
14510
+ try {
14511
+ const messageKey = await this.workerQueueManager.blockingPop(
14512
+ workerQueueId,
14513
+ this.workerQueueBlockingTimeoutSeconds,
14514
+ this.abortController.signal
14515
+ );
14516
+ if (!messageKey) {
14517
+ continue;
14518
+ }
14519
+ const colonIndex = messageKey.indexOf(":");
14520
+ if (colonIndex === -1) {
14521
+ this.logger.error("Invalid message key format", { messageKey });
14522
+ continue;
14523
+ }
14524
+ const messageId = messageKey.substring(0, colonIndex);
14525
+ const queueId = messageKey.substring(colonIndex + 1);
14526
+ await this.#processMessageFromWorkerQueue(loopId, messageId, queueId);
14527
+ } catch (error) {
14528
+ if (this.abortController.signal.aborted) {
14529
+ break;
14530
+ }
14531
+ this.logger.error("Worker queue consumer error", {
14532
+ loopId,
14533
+ error: error instanceof Error ? error.message : String(error)
14534
+ });
14535
+ }
14536
+ }
14537
+ } catch (error) {
14538
+ if (error instanceof Error && error.name === "AbortError") {
14539
+ this.logger.debug("Worker queue consumer aborted", { loopId });
14540
+ return;
14541
+ }
14542
+ throw error;
14543
+ }
14544
+ }
14545
+ async #processMessageFromWorkerQueue(loopId, messageId, queueId) {
14546
+ const shardId = this.masterQueue.getShardForQueue(queueId);
14547
+ const inflightDataKey = this.keys.inflightDataKey(shardId);
14548
+ const dataJson = await this.redis.hget(inflightDataKey, messageId);
14549
+ if (!dataJson) {
14550
+ this.logger.error("Message not found in in-flight data", { messageId, queueId });
14551
+ return;
14552
+ }
14553
+ let storedMessage;
14554
+ try {
14555
+ storedMessage = JSON.parse(dataJson);
14556
+ } catch {
14557
+ this.logger.error("Failed to parse message data", { messageId, queueId });
14558
+ return;
14559
+ }
14560
+ await this.#processMessage(loopId, storedMessage, queueId);
14561
+ }
14562
+ // ============================================================================
14563
+ // Private - Direct Consumer Loop (No Worker Queue)
14564
+ // ============================================================================
14565
+ async #runDirectConsumerLoop(consumerId, shardId) {
14566
+ const loopId = `consumer-${consumerId}-shard-${shardId}`;
14567
+ try {
14568
+ for await (const _ of setInterval$1(this.consumerIntervalMs, null, {
14569
+ signal: this.abortController.signal
14570
+ })) {
14571
+ if (!this.messageHandler) {
14572
+ continue;
14573
+ }
14574
+ try {
14575
+ await this.#processDirectIteration(loopId, shardId);
14576
+ } catch (error) {
14577
+ this.logger.error("Direct consumer iteration error", {
14578
+ loopId,
14579
+ error: error instanceof Error ? error.message : String(error)
14580
+ });
14581
+ }
14582
+ }
14583
+ } catch (error) {
14584
+ if (error instanceof Error && error.name === "AbortError") {
14585
+ this.logger.debug("Direct consumer loop aborted", { loopId });
14586
+ return;
14587
+ }
14588
+ throw error;
14589
+ }
14590
+ }
14591
+ async #processDirectIteration(loopId, shardId) {
14592
+ const masterQueueKey = this.keys.masterQueueKey(shardId);
14593
+ const context2 = this.#createSchedulerContext();
14594
+ const tenantQueues = await this.scheduler.selectQueues(masterQueueKey, loopId, context2);
14595
+ if (tenantQueues.length === 0) {
14596
+ return;
14597
+ }
14598
+ for (const { tenantId, queues } of tenantQueues) {
14599
+ let availableSlots = 1;
14600
+ if (this.concurrencyManager) {
14601
+ const [current, limit] = await Promise.all([
14602
+ this.concurrencyManager.getCurrentConcurrency("tenant", tenantId),
14603
+ this.concurrencyManager.getConcurrencyLimit("tenant", tenantId)
14604
+ ]);
14605
+ availableSlots = Math.max(1, limit - current);
14606
+ }
14607
+ let slotsUsed = 0;
14608
+ queueLoop: for (const queueId of queues) {
14609
+ while (slotsUsed < availableSlots) {
14610
+ if (this.cooloffEnabled && this.#isInCooloff(queueId)) {
14611
+ break;
14612
+ }
14613
+ const processed = await this.#processOneMessage(loopId, queueId, tenantId, shardId);
14614
+ if (processed) {
14615
+ await this.scheduler.recordProcessed?.(tenantId, queueId);
14616
+ this.#resetCooloff(queueId);
14617
+ slotsUsed++;
14618
+ } else {
14619
+ this.#incrementCooloff(queueId);
14620
+ break;
14621
+ }
14622
+ }
14623
+ if (slotsUsed >= availableSlots) {
14624
+ break queueLoop;
14625
+ }
14626
+ }
14627
+ }
14628
+ }
14629
+ async #processOneMessage(loopId, queueId, tenantId, shardId) {
14630
+ const queueKey = this.keys.queueKey(queueId);
14631
+ const queueItemsKey = this.keys.queueItemsKey(queueId);
14632
+ const masterQueueKey = this.keys.masterQueueKey(shardId);
14633
+ const descriptor = this.queueDescriptorCache.get(queueId) ?? {
14634
+ id: queueId,
14635
+ tenantId,
14636
+ metadata: {}
14637
+ };
14638
+ if (this.concurrencyManager) {
14639
+ const check = await this.concurrencyManager.canProcess(descriptor);
14640
+ if (!check.allowed) {
14641
+ return false;
14642
+ }
14643
+ }
14644
+ if (this.globalRateLimiter) {
14645
+ const result = await this.globalRateLimiter.limit();
14646
+ if (!result.allowed && result.resetAt) {
14647
+ const waitMs = Math.max(0, result.resetAt - Date.now());
14648
+ if (waitMs > 0) {
14649
+ this.logger.debug("Global rate limit reached, waiting", { waitMs, loopId });
14650
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
14651
+ }
14652
+ }
14653
+ }
14654
+ const claimResult = await this.visibilityManager.claim(
14655
+ queueId,
14656
+ queueKey,
14657
+ queueItemsKey,
14658
+ loopId,
14659
+ this.visibilityTimeoutMs
14660
+ );
14661
+ if (!claimResult.claimed || !claimResult.message) {
14662
+ await this.redis.updateMasterQueueIfEmpty(masterQueueKey, queueKey, queueId);
14663
+ return false;
14664
+ }
14665
+ const { message } = claimResult;
14666
+ if (this.concurrencyManager) {
14667
+ const reserved = await this.concurrencyManager.reserve(descriptor, message.messageId);
14668
+ if (!reserved) {
14669
+ await this.visibilityManager.release(message.messageId, queueId, queueKey, queueItemsKey);
14670
+ return false;
14671
+ }
14672
+ }
14673
+ await this.#processMessage(loopId, message.payload, queueId);
14674
+ return true;
14675
+ }
14676
+ // ============================================================================
14677
+ // Private - Message Processing
14678
+ // ============================================================================
14679
+ async #processMessage(loopId, storedMessage, queueId) {
14680
+ const startTime = Date.now();
14681
+ const queueKey = this.keys.queueKey(queueId);
14682
+ const queueItemsKey = this.keys.queueItemsKey(queueId);
14683
+ const shardId = this.masterQueue.getShardForQueue(queueId);
14684
+ const masterQueueKey = this.keys.masterQueueKey(shardId);
14685
+ const descriptor = this.queueDescriptorCache.get(queueId) ?? {
14686
+ id: queueId,
14687
+ tenantId: storedMessage.tenantId,
14688
+ metadata: storedMessage.metadata ?? {}
14689
+ };
14690
+ let payload;
14691
+ if (this.payloadSchema) {
14692
+ const result = this.payloadSchema.safeParse(storedMessage.payload);
14693
+ if (!result.success) {
14694
+ this.logger.error("Payload validation failed on dequeue", {
14695
+ messageId: storedMessage.id,
14696
+ queueId,
14697
+ error: result.error.message
14698
+ });
14699
+ await this.#moveToDeadLetterQueue(storedMessage, "Payload validation failed");
14700
+ if (this.concurrencyManager) {
14701
+ try {
14702
+ await this.concurrencyManager.release(descriptor, storedMessage.id);
14703
+ } catch (releaseError) {
14704
+ this.logger.error("Failed to release concurrency slot after payload validation failure", {
14705
+ messageId: storedMessage.id,
14706
+ queueId,
14707
+ error: releaseError instanceof Error ? releaseError.message : String(releaseError)
14708
+ });
14709
+ }
14710
+ }
14711
+ return;
14712
+ }
14713
+ payload = result.data;
14714
+ } else {
14715
+ payload = storedMessage.payload;
14716
+ }
14717
+ const queueMessage = {
14718
+ id: storedMessage.id,
14719
+ queueId,
14720
+ payload,
14721
+ timestamp: storedMessage.timestamp,
14722
+ attempt: storedMessage.attempt,
14723
+ metadata: storedMessage.metadata
14724
+ };
14725
+ const queueTime = startTime - storedMessage.timestamp;
14726
+ this.telemetry.recordQueueTime(
14727
+ queueTime,
14728
+ this.telemetry.messageAttributes({
14729
+ queueId,
14730
+ tenantId: storedMessage.tenantId,
14731
+ messageId: storedMessage.id
14732
+ })
14733
+ );
14734
+ const handlerContext = {
14735
+ message: queueMessage,
14736
+ queue: descriptor,
14737
+ consumerId: loopId,
14738
+ heartbeat: async () => {
14739
+ return this.visibilityManager.heartbeat(
14740
+ storedMessage.id,
14741
+ queueId,
14742
+ this.heartbeatIntervalMs
14743
+ );
14744
+ },
14745
+ complete: async () => {
14746
+ await this.#completeMessage(storedMessage, queueId, queueKey, masterQueueKey, descriptor);
14747
+ this.telemetry.recordComplete(
14748
+ this.telemetry.messageAttributes({
14749
+ queueId,
14750
+ tenantId: storedMessage.tenantId,
14751
+ messageId: storedMessage.id
14752
+ })
14753
+ );
14754
+ this.telemetry.recordProcessingTime(
14755
+ Date.now() - startTime,
14756
+ this.telemetry.messageAttributes({
14757
+ queueId,
14758
+ tenantId: storedMessage.tenantId,
14759
+ messageId: storedMessage.id
14760
+ })
14761
+ );
14762
+ },
14763
+ release: async () => {
14764
+ await this.#releaseMessage(storedMessage, queueId, queueKey, queueItemsKey, descriptor);
14765
+ },
14766
+ fail: async (error) => {
14767
+ await this.#handleMessageFailure(
14768
+ storedMessage,
14769
+ queueId,
14770
+ queueKey,
14771
+ queueItemsKey,
14772
+ masterQueueKey,
14773
+ descriptor,
14774
+ error
14775
+ );
14776
+ }
14777
+ };
14778
+ try {
14779
+ await this.telemetry.trace(
14780
+ "processMessage",
14781
+ async (span) => {
14782
+ span.setAttributes({
14783
+ [FairQueueAttributes.QUEUE_ID]: queueId,
14784
+ [FairQueueAttributes.TENANT_ID]: storedMessage.tenantId,
14785
+ [FairQueueAttributes.MESSAGE_ID]: storedMessage.id,
14786
+ [FairQueueAttributes.ATTEMPT]: storedMessage.attempt,
14787
+ [FairQueueAttributes.CONSUMER_ID]: loopId
14788
+ });
14789
+ await this.messageHandler(handlerContext);
14790
+ },
14791
+ {
14792
+ kind: SpanKind.CONSUMER,
14793
+ attributes: {
14794
+ [MessagingAttributes.OPERATION]: "process"
14795
+ }
14796
+ }
14797
+ );
14798
+ } catch (error) {
14799
+ this.logger.error("Message handler error", {
14800
+ messageId: storedMessage.id,
14801
+ queueId,
14802
+ error: error instanceof Error ? error.message : String(error)
14803
+ });
14804
+ await handlerContext.fail(error instanceof Error ? error : new Error(String(error)));
14805
+ }
14806
+ }
14807
+ async #completeMessage(storedMessage, queueId, queueKey, masterQueueKey, descriptor) {
14808
+ this.masterQueue.getShardForQueue(queueId);
14809
+ await this.visibilityManager.complete(storedMessage.id, queueId);
14810
+ if (this.concurrencyManager) {
14811
+ await this.concurrencyManager.release(descriptor, storedMessage.id);
14812
+ }
14813
+ await this.redis.updateMasterQueueIfEmpty(masterQueueKey, queueKey, queueId);
14814
+ this.logger.debug("Message completed", {
14815
+ messageId: storedMessage.id,
14816
+ queueId
14817
+ });
14818
+ }
14819
+ async #releaseMessage(storedMessage, queueId, queueKey, queueItemsKey, descriptor) {
14820
+ await this.visibilityManager.release(
14821
+ storedMessage.id,
14822
+ queueId,
14823
+ queueKey,
14824
+ queueItemsKey,
14825
+ Date.now()
14826
+ // Put at back of queue
14827
+ );
14828
+ if (this.concurrencyManager) {
14829
+ await this.concurrencyManager.release(descriptor, storedMessage.id);
14830
+ }
14831
+ this.logger.debug("Message released", {
14832
+ messageId: storedMessage.id,
14833
+ queueId
14834
+ });
14835
+ }
14836
+ async #handleMessageFailure(storedMessage, queueId, queueKey, queueItemsKey, masterQueueKey, descriptor, error) {
14837
+ this.telemetry.recordFailure(
14838
+ this.telemetry.messageAttributes({
14839
+ queueId,
14840
+ tenantId: storedMessage.tenantId,
14841
+ messageId: storedMessage.id,
14842
+ attempt: storedMessage.attempt
14843
+ })
14844
+ );
14845
+ if (this.retryStrategy) {
14846
+ const nextDelay = this.retryStrategy.getNextDelay(storedMessage.attempt, error);
14847
+ if (nextDelay !== null) {
14848
+ const updatedMessage = {
14849
+ ...storedMessage,
14850
+ attempt: storedMessage.attempt + 1
14851
+ };
14852
+ await this.visibilityManager.release(
14853
+ storedMessage.id,
14854
+ queueId,
14855
+ queueKey,
14856
+ queueItemsKey,
14857
+ Date.now() + nextDelay
14858
+ );
14859
+ await this.redis.hset(queueItemsKey, storedMessage.id, JSON.stringify(updatedMessage));
14860
+ if (this.concurrencyManager) {
14861
+ await this.concurrencyManager.release(descriptor, storedMessage.id);
14862
+ }
14863
+ this.telemetry.recordRetry(
14864
+ this.telemetry.messageAttributes({
14865
+ queueId,
14866
+ tenantId: storedMessage.tenantId,
14867
+ messageId: storedMessage.id,
14868
+ attempt: storedMessage.attempt + 1
14869
+ })
14870
+ );
14871
+ this.logger.debug("Message scheduled for retry", {
14872
+ messageId: storedMessage.id,
14873
+ queueId,
14874
+ attempt: storedMessage.attempt + 1,
14875
+ delayMs: nextDelay
14876
+ });
14877
+ return;
14878
+ }
14879
+ }
14880
+ await this.#moveToDeadLetterQueue(storedMessage, error?.message);
14881
+ if (this.concurrencyManager) {
14882
+ await this.concurrencyManager.release(descriptor, storedMessage.id);
14883
+ }
14884
+ }
14885
+ async #moveToDeadLetterQueue(storedMessage, errorMessage) {
14886
+ if (!this.deadLetterQueueEnabled) {
14887
+ await this.visibilityManager.complete(storedMessage.id, storedMessage.queueId);
14888
+ return;
14889
+ }
14890
+ const dlqKey = this.keys.deadLetterQueueKey(storedMessage.tenantId);
14891
+ const dlqDataKey = this.keys.deadLetterQueueDataKey(storedMessage.tenantId);
14892
+ this.masterQueue.getShardForQueue(storedMessage.queueId);
14893
+ const dlqMessage = {
14894
+ id: storedMessage.id,
14895
+ queueId: storedMessage.queueId,
14896
+ tenantId: storedMessage.tenantId,
14897
+ payload: storedMessage.payload,
14898
+ deadLetteredAt: Date.now(),
14899
+ attempts: storedMessage.attempt,
14900
+ lastError: errorMessage,
14901
+ originalTimestamp: storedMessage.timestamp
14902
+ };
14903
+ await this.visibilityManager.complete(storedMessage.id, storedMessage.queueId);
14904
+ const pipeline = this.redis.pipeline();
14905
+ pipeline.zadd(dlqKey, dlqMessage.deadLetteredAt, storedMessage.id);
14906
+ pipeline.hset(dlqDataKey, storedMessage.id, JSON.stringify(dlqMessage));
14907
+ await pipeline.exec();
14908
+ this.telemetry.recordDLQ(
14909
+ this.telemetry.messageAttributes({
14910
+ queueId: storedMessage.queueId,
14911
+ tenantId: storedMessage.tenantId,
14912
+ messageId: storedMessage.id,
14913
+ attempt: storedMessage.attempt
14914
+ })
14915
+ );
14916
+ this.logger.info("Message moved to DLQ", {
14917
+ messageId: storedMessage.id,
14918
+ queueId: storedMessage.queueId,
14919
+ tenantId: storedMessage.tenantId,
14920
+ attempts: storedMessage.attempt,
14921
+ error: errorMessage
14922
+ });
14923
+ }
14924
+ // ============================================================================
14925
+ // Private - Reclaim Loop
14926
+ // ============================================================================
14927
+ async #runReclaimLoop() {
14928
+ try {
14929
+ for await (const _ of setInterval$1(this.reclaimIntervalMs, null, {
14930
+ signal: this.abortController.signal
14931
+ })) {
14932
+ try {
14933
+ await this.#reclaimTimedOutMessages();
14934
+ } catch (error) {
14935
+ this.logger.error("Reclaim loop error", {
14936
+ error: error instanceof Error ? error.message : String(error)
14937
+ });
14938
+ }
14939
+ }
14940
+ } catch (error) {
14941
+ if (error instanceof Error && error.name === "AbortError") {
14942
+ this.logger.debug("Reclaim loop aborted");
14943
+ return;
14944
+ }
14945
+ throw error;
14946
+ }
14947
+ }
14948
+ async #reclaimTimedOutMessages() {
14949
+ let totalReclaimed = 0;
14950
+ for (let shardId = 0; shardId < this.shardCount; shardId++) {
14951
+ const reclaimed = await this.visibilityManager.reclaimTimedOut(shardId, (queueId) => ({
14952
+ queueKey: this.keys.queueKey(queueId),
14953
+ queueItemsKey: this.keys.queueItemsKey(queueId)
14954
+ }));
14955
+ totalReclaimed += reclaimed;
14956
+ }
14957
+ if (totalReclaimed > 0) {
14958
+ this.logger.info("Reclaimed timed-out messages", { count: totalReclaimed });
14959
+ }
14960
+ }
14961
+ // ============================================================================
14962
+ // Private - Cooloff State
14963
+ // ============================================================================
14964
+ #isInCooloff(queueId) {
14965
+ const state = this.queueCooloffStates.get(queueId);
14966
+ if (!state) return false;
14967
+ if (state.tag === "cooloff") {
14968
+ if (Date.now() >= state.expiresAt) {
14969
+ this.queueCooloffStates.delete(queueId);
14970
+ return false;
14971
+ }
14972
+ return true;
14973
+ }
14974
+ return false;
14975
+ }
14976
+ #incrementCooloff(queueId) {
14977
+ const state = this.queueCooloffStates.get(queueId) ?? {
14978
+ tag: "normal",
14979
+ consecutiveFailures: 0
14980
+ };
14981
+ if (state.tag === "normal") {
14982
+ const newFailures = state.consecutiveFailures + 1;
14983
+ if (newFailures >= this.cooloffThreshold) {
14984
+ this.queueCooloffStates.set(queueId, {
14985
+ tag: "cooloff",
14986
+ expiresAt: Date.now() + this.cooloffPeriodMs
14987
+ });
14988
+ this.logger.debug("Queue entered cooloff", {
14989
+ queueId,
14990
+ cooloffPeriodMs: this.cooloffPeriodMs,
14991
+ consecutiveFailures: newFailures
14992
+ });
14993
+ } else {
14994
+ this.queueCooloffStates.set(queueId, {
14995
+ tag: "normal",
14996
+ consecutiveFailures: newFailures
14997
+ });
14998
+ }
14999
+ }
15000
+ }
15001
+ #resetCooloff(queueId) {
15002
+ this.queueCooloffStates.delete(queueId);
15003
+ }
15004
+ // ============================================================================
15005
+ // Private - Helpers
15006
+ // ============================================================================
15007
+ #createSchedulerContext() {
15008
+ return {
15009
+ getCurrentConcurrency: async (groupName, groupId) => {
15010
+ if (!this.concurrencyManager) return 0;
15011
+ return this.concurrencyManager.getCurrentConcurrency(groupName, groupId);
15012
+ },
15013
+ getConcurrencyLimit: async (groupName, groupId) => {
15014
+ if (!this.concurrencyManager) return Infinity;
15015
+ return this.concurrencyManager.getConcurrencyLimit(groupName, groupId);
15016
+ },
15017
+ isAtCapacity: async (groupName, groupId) => {
15018
+ if (!this.concurrencyManager) return false;
15019
+ return this.concurrencyManager.isAtCapacity(groupName, groupId);
15020
+ },
15021
+ getQueueDescriptor: (queueId) => {
15022
+ return this.queueDescriptorCache.get(queueId) ?? {
15023
+ id: queueId,
15024
+ tenantId: this.keys.extractTenantId(queueId),
15025
+ metadata: {}
15026
+ };
15027
+ }
15028
+ };
15029
+ }
15030
+ // ============================================================================
15031
+ // Private - Redis Commands
15032
+ // ============================================================================
15033
+ #registerCommands() {
15034
+ this.redis.defineCommand("enqueueMessageAtomic", {
15035
+ numberOfKeys: 3,
15036
+ lua: `
15037
+ local queueKey = KEYS[1]
15038
+ local queueItemsKey = KEYS[2]
15039
+ local masterQueueKey = KEYS[3]
15040
+
15041
+ local queueId = ARGV[1]
15042
+ local messageId = ARGV[2]
15043
+ local timestamp = tonumber(ARGV[3])
15044
+ local payload = ARGV[4]
15045
+
15046
+ -- Add to sorted set (score = timestamp)
15047
+ redis.call('ZADD', queueKey, timestamp, messageId)
15048
+
15049
+ -- Store payload in hash
15050
+ redis.call('HSET', queueItemsKey, messageId, payload)
15051
+
15052
+ -- Update master queue with oldest message timestamp
15053
+ local oldest = redis.call('ZRANGE', queueKey, 0, 0, 'WITHSCORES')
15054
+ if #oldest >= 2 then
15055
+ redis.call('ZADD', masterQueueKey, oldest[2], queueId)
15056
+ end
15057
+
15058
+ return 1
15059
+ `
15060
+ });
15061
+ this.redis.defineCommand("enqueueBatchAtomic", {
15062
+ numberOfKeys: 3,
15063
+ lua: `
15064
+ local queueKey = KEYS[1]
15065
+ local queueItemsKey = KEYS[2]
15066
+ local masterQueueKey = KEYS[3]
15067
+
15068
+ local queueId = ARGV[1]
15069
+
15070
+ -- Args after queueId are triples: [messageId, timestamp, payload, ...]
15071
+ for i = 2, #ARGV, 3 do
15072
+ local messageId = ARGV[i]
15073
+ local timestamp = tonumber(ARGV[i + 1])
15074
+ local payload = ARGV[i + 2]
15075
+
15076
+ -- Add to sorted set
15077
+ redis.call('ZADD', queueKey, timestamp, messageId)
15078
+
15079
+ -- Store payload in hash
15080
+ redis.call('HSET', queueItemsKey, messageId, payload)
15081
+ end
15082
+
15083
+ -- Update master queue with oldest message timestamp
15084
+ local oldest = redis.call('ZRANGE', queueKey, 0, 0, 'WITHSCORES')
15085
+ if #oldest >= 2 then
15086
+ redis.call('ZADD', masterQueueKey, oldest[2], queueId)
15087
+ end
15088
+
15089
+ return (#ARGV - 1) / 3
15090
+ `
15091
+ });
15092
+ this.redis.defineCommand("updateMasterQueueIfEmpty", {
15093
+ numberOfKeys: 2,
15094
+ lua: `
15095
+ local masterQueueKey = KEYS[1]
15096
+ local queueKey = KEYS[2]
15097
+ local queueId = ARGV[1]
15098
+
15099
+ local count = redis.call('ZCARD', queueKey)
15100
+ if count == 0 then
15101
+ redis.call('ZREM', masterQueueKey, queueId)
15102
+ return 1
15103
+ else
15104
+ -- Update with oldest message timestamp
15105
+ local oldest = redis.call('ZRANGE', queueKey, 0, 0, 'WITHSCORES')
15106
+ if #oldest >= 2 then
15107
+ redis.call('ZADD', masterQueueKey, oldest[2], queueId)
15108
+ end
15109
+ return 0
15110
+ end
15111
+ `
15112
+ });
15113
+ if (this.workerQueueManager) {
15114
+ this.workerQueueManager.registerCommands(this.redis);
15115
+ }
15116
+ }
15117
+ };
15118
+
15119
+ export { BaseScheduler, CallbackFairQueueKeyProducer, ConcurrencyManager, CronSchema, CustomRetry, DRRScheduler, DefaultFairQueueKeyProducer, ExponentialBackoffRetry, FairQueue, FairQueueAttributes, FairQueueTelemetry, FixedDelayRetry, ImmediateRetry, LinearBackoffRetry, MasterQueue, MessagingAttributes, NoRetry, NoopScheduler, RoundRobinScheduler, SimpleQueue, VisibilityManager, WeightedScheduler, Worker, WorkerQueueManager, createDefaultRetryStrategy, defaultRetryOptions, noopTelemetry };
11725
15120
  //# sourceMappingURL=index.js.map
11726
15121
  //# sourceMappingURL=index.js.map