@omnitron-dev/titan-notifications 0.1.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.
Files changed (150) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -0
  3. package/dist/channel/channel-registry.d.ts +40 -0
  4. package/dist/channel/channel-registry.d.ts.map +1 -0
  5. package/dist/channel/channel-registry.js +157 -0
  6. package/dist/channel/channel-registry.js.map +1 -0
  7. package/dist/channel/channel.interface.d.ts +77 -0
  8. package/dist/channel/channel.interface.d.ts.map +1 -0
  9. package/dist/channel/channel.interface.js +9 -0
  10. package/dist/channel/channel.interface.js.map +1 -0
  11. package/dist/channel/channels/email.channel.d.ts +43 -0
  12. package/dist/channel/channels/email.channel.d.ts.map +1 -0
  13. package/dist/channel/channels/email.channel.js +211 -0
  14. package/dist/channel/channels/email.channel.js.map +1 -0
  15. package/dist/channel/channels/inapp.channel.d.ts +41 -0
  16. package/dist/channel/channels/inapp.channel.d.ts.map +1 -0
  17. package/dist/channel/channels/inapp.channel.js +308 -0
  18. package/dist/channel/channels/inapp.channel.js.map +1 -0
  19. package/dist/channel/channels/index.d.ts +11 -0
  20. package/dist/channel/channels/index.d.ts.map +1 -0
  21. package/dist/channel/channels/index.js +6 -0
  22. package/dist/channel/channels/index.js.map +1 -0
  23. package/dist/channel/channels/push.channel.d.ts +51 -0
  24. package/dist/channel/channels/push.channel.d.ts.map +1 -0
  25. package/dist/channel/channels/push.channel.js +179 -0
  26. package/dist/channel/channels/push.channel.js.map +1 -0
  27. package/dist/channel/channels/sms.channel.d.ts +45 -0
  28. package/dist/channel/channels/sms.channel.d.ts.map +1 -0
  29. package/dist/channel/channels/sms.channel.js +170 -0
  30. package/dist/channel/channels/sms.channel.js.map +1 -0
  31. package/dist/channel/channels/webhook.channel.d.ts +39 -0
  32. package/dist/channel/channels/webhook.channel.d.ts.map +1 -0
  33. package/dist/channel/channels/webhook.channel.js +217 -0
  34. package/dist/channel/channels/webhook.channel.js.map +1 -0
  35. package/dist/channel/index.d.ts +5 -0
  36. package/dist/channel/index.d.ts.map +1 -0
  37. package/dist/channel/index.js +4 -0
  38. package/dist/channel/index.js.map +1 -0
  39. package/dist/index.d.ts +35 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +17 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/notifications.decorators.d.ts +14 -0
  44. package/dist/notifications.decorators.d.ts.map +1 -0
  45. package/dist/notifications.decorators.js +24 -0
  46. package/dist/notifications.decorators.js.map +1 -0
  47. package/dist/notifications.events.d.ts +83 -0
  48. package/dist/notifications.events.d.ts.map +1 -0
  49. package/dist/notifications.events.js +118 -0
  50. package/dist/notifications.events.js.map +1 -0
  51. package/dist/notifications.health.d.ts +16 -0
  52. package/dist/notifications.health.d.ts.map +1 -0
  53. package/dist/notifications.health.js +63 -0
  54. package/dist/notifications.health.js.map +1 -0
  55. package/dist/notifications.module.d.ts +27 -0
  56. package/dist/notifications.module.d.ts.map +1 -0
  57. package/dist/notifications.module.js +533 -0
  58. package/dist/notifications.module.js.map +1 -0
  59. package/dist/notifications.service.d.ts +43 -0
  60. package/dist/notifications.service.d.ts.map +1 -0
  61. package/dist/notifications.service.js +394 -0
  62. package/dist/notifications.service.js.map +1 -0
  63. package/dist/notifications.tokens.d.ts +31 -0
  64. package/dist/notifications.tokens.d.ts.map +1 -0
  65. package/dist/notifications.tokens.js +14 -0
  66. package/dist/notifications.tokens.js.map +1 -0
  67. package/dist/notifications.types.d.ts +234 -0
  68. package/dist/notifications.types.d.ts.map +1 -0
  69. package/dist/notifications.types.js +2 -0
  70. package/dist/notifications.types.js.map +1 -0
  71. package/dist/publisher.d.ts +35 -0
  72. package/dist/publisher.d.ts.map +1 -0
  73. package/dist/publisher.js +18 -0
  74. package/dist/publisher.js.map +1 -0
  75. package/dist/redis-preference-store.d.ts +68 -0
  76. package/dist/redis-preference-store.d.ts.map +1 -0
  77. package/dist/redis-preference-store.js +291 -0
  78. package/dist/redis-preference-store.js.map +1 -0
  79. package/dist/redis-rate-limiter.d.ts +67 -0
  80. package/dist/redis-rate-limiter.d.ts.map +1 -0
  81. package/dist/redis-rate-limiter.js +270 -0
  82. package/dist/redis-rate-limiter.js.map +1 -0
  83. package/dist/rotif/dlq-manager.d.ts +53 -0
  84. package/dist/rotif/dlq-manager.d.ts.map +1 -0
  85. package/dist/rotif/dlq-manager.js +249 -0
  86. package/dist/rotif/dlq-manager.js.map +1 -0
  87. package/dist/rotif/index.d.ts +7 -0
  88. package/dist/rotif/index.d.ts.map +1 -0
  89. package/dist/rotif/index.js +7 -0
  90. package/dist/rotif/index.js.map +1 -0
  91. package/dist/rotif/middleware.d.ts +22 -0
  92. package/dist/rotif/middleware.d.ts.map +1 -0
  93. package/dist/rotif/middleware.js +39 -0
  94. package/dist/rotif/middleware.js.map +1 -0
  95. package/dist/rotif/rotif.d.ts +88 -0
  96. package/dist/rotif/rotif.d.ts.map +1 -0
  97. package/dist/rotif/rotif.js +948 -0
  98. package/dist/rotif/rotif.js.map +1 -0
  99. package/dist/rotif/stats.d.ts +12 -0
  100. package/dist/rotif/stats.d.ts.map +1 -0
  101. package/dist/rotif/stats.js +27 -0
  102. package/dist/rotif/stats.js.map +1 -0
  103. package/dist/rotif/types.d.ts +92 -0
  104. package/dist/rotif/types.d.ts.map +1 -0
  105. package/dist/rotif/types.js +2 -0
  106. package/dist/rotif/types.js.map +1 -0
  107. package/dist/rotif/utils.d.ts +40 -0
  108. package/dist/rotif/utils.d.ts.map +1 -0
  109. package/dist/rotif/utils.js +156 -0
  110. package/dist/rotif/utils.js.map +1 -0
  111. package/dist/template-engine.d.ts +97 -0
  112. package/dist/template-engine.d.ts.map +1 -0
  113. package/dist/template-engine.js +290 -0
  114. package/dist/template-engine.js.map +1 -0
  115. package/dist/transport/index.d.ts +4 -0
  116. package/dist/transport/index.d.ts.map +1 -0
  117. package/dist/transport/index.js +3 -0
  118. package/dist/transport/index.js.map +1 -0
  119. package/dist/transport/rotif.transport.d.ts +29 -0
  120. package/dist/transport/rotif.transport.d.ts.map +1 -0
  121. package/dist/transport/rotif.transport.js +301 -0
  122. package/dist/transport/rotif.transport.js.map +1 -0
  123. package/dist/transport/transport.interface.d.ts +130 -0
  124. package/dist/transport/transport.interface.d.ts.map +1 -0
  125. package/dist/transport/transport.interface.js +8 -0
  126. package/dist/transport/transport.interface.js.map +1 -0
  127. package/dist/worker/index.d.ts +4 -0
  128. package/dist/worker/index.d.ts.map +1 -0
  129. package/dist/worker/index.js +3 -0
  130. package/dist/worker/index.js.map +1 -0
  131. package/dist/worker/notification-worker.d.ts +41 -0
  132. package/dist/worker/notification-worker.d.ts.map +1 -0
  133. package/dist/worker/notification-worker.js +229 -0
  134. package/dist/worker/notification-worker.js.map +1 -0
  135. package/dist/worker/worker.interfaces.d.ts +41 -0
  136. package/dist/worker/worker.interfaces.d.ts.map +1 -0
  137. package/dist/worker/worker.interfaces.js +2 -0
  138. package/dist/worker/worker.interfaces.js.map +1 -0
  139. package/dist/worker/worker.tokens.d.ts +6 -0
  140. package/dist/worker/worker.tokens.d.ts.map +1 -0
  141. package/dist/worker/worker.tokens.js +5 -0
  142. package/dist/worker/worker.tokens.js.map +1 -0
  143. package/lua/rotif/ack-message.lua +19 -0
  144. package/lua/rotif/move-scheduled-messages.lua +38 -0
  145. package/lua/rotif/move-to-dlq.lua +41 -0
  146. package/lua/rotif/publish-message.lua +89 -0
  147. package/lua/rotif/requeue-from-dlq.lua +40 -0
  148. package/lua/rotif/retry-message.lua +49 -0
  149. package/lua/rotif/safe-unsubscribe.lua +8 -0
  150. package/package.json +67 -0
@@ -0,0 +1,948 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { minimatch } from 'minimatch';
5
+ import { Redis } from 'ioredis';
6
+ import { createHash } from 'node:crypto';
7
+ import { generateUuidV7 } from '@omnitron-dev/titan/utils';
8
+ import { defer, delay as delayMs } from '@omnitron-dev/common';
9
+ import { Errors } from '@omnitron-dev/titan/errors';
10
+ import { StatsTracker } from './stats.js';
11
+ import { createNullLogger } from '@omnitron-dev/titan/types';
12
+ import { MiddlewareManager } from './middleware.js';
13
+ import { getLoopKey, parseFields, parseFieldsFast, releaseFields, getStreamKey, getGroupName, generateDedupKey, defaultConsumerName, getCachedMatcher, chunkArray, processWithConcurrency, } from './utils.js';
14
+ import { createRetryDelayFn, RetryStrategies } from '@omnitron-dev/titan/utils';
15
+ import { DLQManager } from './dlq-manager.js';
16
+ const ROTIF_CONSTANTS = {
17
+ BASE_RETRY_DELAY_MS: 100,
18
+ MAX_RETRY_DELAY_MS: 5000,
19
+ DEFAULT_MAX_WAIT_MS: 5000,
20
+ DEFAULT_READ_COUNT: 5000,
21
+ DEFAULT_MESSAGE_CONCURRENCY: 1,
22
+ DEFAULT_PIPELINE_BATCH_SIZE: 100,
23
+ DEFAULT_HEALTH_CHECK_INTERVAL: 30000,
24
+ DEFAULT_BACKPRESSURE_THRESHOLD: 1000,
25
+ };
26
+ export class NotificationManager {
27
+ constructor(config) {
28
+ this.middleware = new MiddlewareManager();
29
+ this.subscriptions = new Map();
30
+ this.active = true;
31
+ this.activePatterns = new Set();
32
+ this.consumerLoops = new Map();
33
+ this.luaScripts = new Map();
34
+ this.roundRobinIndices = new Map();
35
+ this.healthStatus = {
36
+ connected: false,
37
+ lastPingMs: 0,
38
+ lastCheckTime: 0,
39
+ consecutiveFailures: 0,
40
+ };
41
+ this.backpressureStates = new Map();
42
+ this.patternMatcherCache = new Map();
43
+ this.config = config;
44
+ this.logger = config.logger || createNullLogger();
45
+ this.redis = new Redis(config.redis);
46
+ this.dlqKey = config.dlqKey || 'rotif:dlq';
47
+ this.enableFieldPooling = config.enableFieldPooling !== false;
48
+ this.dlqManager = new DLQManager(this.redis, this.logger, config.dlqCleanup, this.dlqKey);
49
+ this.redis.options.retryStrategy = (times) => {
50
+ const jitter = Math.random() * ROTIF_CONSTANTS.BASE_RETRY_DELAY_MS;
51
+ const delay = Math.min(ROTIF_CONSTANTS.BASE_RETRY_DELAY_MS * Math.pow(2, times - 1) + jitter, ROTIF_CONSTANTS.MAX_RETRY_DELAY_MS);
52
+ return delay;
53
+ };
54
+ this.redis.on('error', (err) => {
55
+ this.logger.error({ err }, 'Redis connection error');
56
+ this.healthStatus.connected = false;
57
+ this.healthStatus.consecutiveFailures++;
58
+ });
59
+ this.redis.on('reconnecting', (time) => {
60
+ this.logger.info(`Redis reconnecting in ${time}ms...`);
61
+ this.healthStatus.connected = false;
62
+ });
63
+ this.redis.on('connect', () => {
64
+ this.syncPatterns();
65
+ this.healthStatus.connected = true;
66
+ this.healthStatus.consecutiveFailures = 0;
67
+ this.logger.info('Redis successfully connected');
68
+ });
69
+ this.initializationDefer = defer();
70
+ this.loadLuaScripts().then(() => {
71
+ if (!this.active)
72
+ return;
73
+ if (!this.config.disableDelayed) {
74
+ setImmediate(() => {
75
+ this.startDelayScheduler();
76
+ });
77
+ }
78
+ if (this.config.dlqCleanup?.enabled) {
79
+ this.dlqManager.startAutoCleanup();
80
+ }
81
+ this.subscribeToPatternUpdates();
82
+ if (this.config.enableHealthCheck !== false) {
83
+ this.startHealthCheck();
84
+ }
85
+ this.initializationDefer.resolve?.(true);
86
+ });
87
+ }
88
+ startHealthCheck() {
89
+ const interval = this.config.healthCheckInterval ?? ROTIF_CONSTANTS.DEFAULT_HEALTH_CHECK_INTERVAL;
90
+ const performHealthCheck = async () => {
91
+ if (!this.active)
92
+ return;
93
+ try {
94
+ const startTime = Date.now();
95
+ await this.redis.ping();
96
+ const latency = Date.now() - startTime;
97
+ this.healthStatus = {
98
+ connected: true,
99
+ lastPingMs: latency,
100
+ lastCheckTime: Date.now(),
101
+ consecutiveFailures: 0,
102
+ };
103
+ if (latency > 100) {
104
+ this.logger.warn({ latency }, 'Redis connection latency is high');
105
+ }
106
+ }
107
+ catch (err) {
108
+ this.healthStatus.consecutiveFailures++;
109
+ this.healthStatus.connected = false;
110
+ this.healthStatus.lastCheckTime = Date.now();
111
+ this.logger.error({ err, consecutiveFailures: this.healthStatus.consecutiveFailures }, 'Redis health check failed');
112
+ if (this.healthStatus.consecutiveFailures >= 3) {
113
+ this.logger.warn('Multiple health check failures, attempting reconnection');
114
+ try {
115
+ await this.redis.disconnect();
116
+ await this.redis.connect();
117
+ }
118
+ catch (reconnectErr) {
119
+ this.logger.error({ err: reconnectErr }, 'Failed to reconnect Redis');
120
+ }
121
+ }
122
+ }
123
+ };
124
+ performHealthCheck();
125
+ this.healthCheckTimer = setInterval(performHealthCheck, interval);
126
+ }
127
+ getHealthStatus() {
128
+ return { ...this.healthStatus };
129
+ }
130
+ shouldApplyBackpressure(loopKey) {
131
+ if (this.config.enableBackpressure === false)
132
+ return false;
133
+ const state = this.backpressureStates.get(loopKey);
134
+ if (!state)
135
+ return false;
136
+ const threshold = this.config.backpressureThreshold ?? ROTIF_CONSTANTS.DEFAULT_BACKPRESSURE_THRESHOLD;
137
+ return state.pendingCount >= threshold;
138
+ }
139
+ updateBackpressure(loopKey, delta) {
140
+ if (this.config.enableBackpressure === false)
141
+ return;
142
+ let state = this.backpressureStates.get(loopKey);
143
+ if (!state) {
144
+ state = { active: false, pendingCount: 0 };
145
+ this.backpressureStates.set(loopKey, state);
146
+ }
147
+ state.pendingCount = Math.max(0, state.pendingCount + delta);
148
+ const threshold = this.config.backpressureThreshold ?? ROTIF_CONSTANTS.DEFAULT_BACKPRESSURE_THRESHOLD;
149
+ const wasActive = state.active;
150
+ state.active = state.pendingCount >= threshold;
151
+ if (state.active && !wasActive) {
152
+ state.activatedAt = Date.now();
153
+ this.logger.warn({ loopKey, pendingCount: state.pendingCount }, 'Backpressure activated');
154
+ }
155
+ else if (!state.active && wasActive) {
156
+ const duration = Date.now() - (state.activatedAt ?? Date.now());
157
+ this.logger.info({ loopKey, durationMs: duration }, 'Backpressure deactivated');
158
+ state.activatedAt = undefined;
159
+ }
160
+ }
161
+ async loadLuaScripts() {
162
+ try {
163
+ let luaDir;
164
+ try {
165
+ const __filename = fileURLToPath(import.meta.url);
166
+ const __dirname = path.dirname(__filename);
167
+ luaDir = path.resolve(__dirname, '..', '..', 'lua', 'rotif');
168
+ }
169
+ catch (_e) {
170
+ this.logger.debug('Cannot determine lua directory, skipping script loading');
171
+ return;
172
+ }
173
+ if (!fs.existsSync(luaDir)) {
174
+ this.logger.debug('Lua scripts directory not found, skipping loading');
175
+ return;
176
+ }
177
+ const luaFiles = fs.readdirSync(luaDir).filter((file) => file.endsWith('.lua'));
178
+ for (const file of luaFiles) {
179
+ const scriptContent = fs.readFileSync(path.join(luaDir, file), 'utf-8');
180
+ const scriptName = path.basename(file, '.lua');
181
+ const _localSha = createHash('sha1').update(scriptContent).digest('hex');
182
+ const sha = (await this.redis.script('LOAD', scriptContent));
183
+ this.luaScripts.set(scriptName, sha);
184
+ }
185
+ this.logger.info('Lua scripts loaded or reused');
186
+ }
187
+ catch (error) {
188
+ this.logger.debug({ err: error }, 'Could not load Lua scripts');
189
+ }
190
+ }
191
+ async runLuaScript(scriptName, keys, args) {
192
+ const sha = this.luaScripts.get(scriptName);
193
+ if (!sha) {
194
+ throw Errors.notFound('Lua script', scriptName);
195
+ }
196
+ return this.redis.evalsha(sha, keys.length, ...keys, ...args);
197
+ }
198
+ use(mw) {
199
+ this.middleware.use(mw);
200
+ }
201
+ async waitUntilReady() {
202
+ await this.initializationDefer.promise;
203
+ }
204
+ async destroy() {
205
+ this.active = false;
206
+ if (this.delayTimeoutId) {
207
+ clearInterval(this.delayTimeoutId);
208
+ this.delayTimeoutId = undefined;
209
+ }
210
+ if (this.healthCheckTimer) {
211
+ clearInterval(this.healthCheckTimer);
212
+ this.healthCheckTimer = undefined;
213
+ }
214
+ this.activePatterns.clear();
215
+ this.luaScripts.clear();
216
+ this.subscriptions.clear();
217
+ this.patternMatcherCache.clear();
218
+ this.backpressureStates.clear();
219
+ await Promise.all([this.redis?.quit(), this.subClient?.quit(), this.dlqClient?.quit()].filter(Boolean));
220
+ }
221
+ async publish(channel, payload, options) {
222
+ if (!this.active) {
223
+ throw new Error('Cannot publish: Rotif instance is stopped');
224
+ }
225
+ await this.initializationDefer.promise;
226
+ await this.middleware.runBeforePublish(channel, payload, options);
227
+ const matchingPatterns = [];
228
+ for (const pattern of this.activePatterns) {
229
+ let matcher = this.patternMatcherCache.get(pattern);
230
+ if (!matcher) {
231
+ matcher = getCachedMatcher(pattern, minimatch);
232
+ this.patternMatcherCache.set(pattern, matcher);
233
+ }
234
+ if (matcher(channel)) {
235
+ matchingPatterns.push(pattern);
236
+ }
237
+ }
238
+ if (matchingPatterns.length === 0) {
239
+ this.logger.debug(`No active patterns match channel ${channel}, skipping publish.`);
240
+ return null;
241
+ }
242
+ const timestamp = Date.now().toString();
243
+ const attempt = String(options?.attempt ?? 1);
244
+ const deliveryType = options?.delayMs || options?.deliverAt ? 'delayed' : 'normal';
245
+ const delayTimestamp = options?.deliverAt
246
+ ? new Date(options.deliverAt).getTime().toString()
247
+ : options?.delayMs
248
+ ? (Date.now() + options.delayMs).toString()
249
+ : '0';
250
+ const maxStreamLength = this.config.maxStreamLength ? String(this.config.maxStreamLength) : '0';
251
+ const minStreamId = this.config.minStreamId ?? '';
252
+ const deduplicationTTL = options?.deduplicationTTL ?? this.config.deduplicationTTL ?? 3600;
253
+ const payloadJson = JSON.stringify(payload);
254
+ const exactlyOnceFlag = options?.exactlyOnce ? 'true' : 'false';
255
+ const results = [];
256
+ for (const pattern of matchingPatterns) {
257
+ const streamKey = getStreamKey(pattern);
258
+ const dedupKey = options?.exactlyOnce
259
+ ? (this.config.generateDedupKey?.({ channel, payload, pattern }) ??
260
+ generateDedupKey({ channel, payload, pattern, side: 'pub' }))
261
+ : '';
262
+ try {
263
+ const result = await this.runLuaScript('publish-message', [streamKey, 'rotif:scheduled'], [
264
+ payloadJson,
265
+ timestamp,
266
+ channel,
267
+ attempt,
268
+ deliveryType,
269
+ delayTimestamp,
270
+ maxStreamLength,
271
+ minStreamId,
272
+ dedupKey,
273
+ deduplicationTTL.toString(),
274
+ generateUuidV7(),
275
+ exactlyOnceFlag,
276
+ pattern,
277
+ ]);
278
+ if (result === 'DUPLICATE') {
279
+ this.logger.info(`Duplicate message detected: ${dedupKey}`);
280
+ }
281
+ else {
282
+ results.push(result);
283
+ }
284
+ }
285
+ catch (err) {
286
+ this.logger.error({ err, streamKey }, 'Error publishing to stream');
287
+ await this.middleware.runOnError({ channel, payload, attempt: +attempt, id: '', timestamp: +timestamp, ack: async () => { } }, err);
288
+ }
289
+ }
290
+ if (results.length === 0) {
291
+ return 'DUPLICATE';
292
+ }
293
+ this.logger.debug({ channel }, `Published message to ${results.length} active streams`);
294
+ await this.middleware.runAfterPublish(channel, payload, results, options);
295
+ return results.length === 1 ? results[0] : results;
296
+ }
297
+ async publishBatch(messages) {
298
+ await this.initializationDefer.promise;
299
+ if (messages.length === 0)
300
+ return [];
301
+ if (messages.length < 3 || this.config.enablePipelining === false) {
302
+ return Promise.all(messages.map((m) => this.publish(m.channel, m.payload, m.options)));
303
+ }
304
+ const results = new Array(messages.length);
305
+ const batchSize = this.config.pipelineBatchSize ?? ROTIF_CONSTANTS.DEFAULT_PIPELINE_BATCH_SIZE;
306
+ const chunks = chunkArray(messages, batchSize);
307
+ for (const chunk of chunks) {
308
+ await Promise.all(chunk.map(async (msg, idx) => {
309
+ const globalIdx = chunks.indexOf(chunk) * batchSize + idx;
310
+ results[globalIdx] = await this.publish(msg.channel, msg.payload, msg.options);
311
+ }));
312
+ }
313
+ return results;
314
+ }
315
+ async subscribe(pattern, handler, options) {
316
+ await this.initializationDefer.promise;
317
+ const group = getGroupName(pattern, options?.groupName);
318
+ const consumer = this.config.consumerNameFn?.() || defaultConsumerName();
319
+ const stream = getStreamKey(pattern);
320
+ const retryStream = `${stream}:retry`;
321
+ const subId = generateUuidV7();
322
+ const stats = new StatsTracker();
323
+ await this.ensureStreamGroup(stream, group);
324
+ await this.ensureStreamGroup(retryStream, group);
325
+ const sub = {
326
+ id: subId,
327
+ pattern,
328
+ group,
329
+ options,
330
+ handler,
331
+ statsTracker: stats,
332
+ inflightCount: 0,
333
+ unsubscribe: async (removePattern = false) => {
334
+ sub.isPaused = true;
335
+ const startTime = Date.now();
336
+ while (sub.inflightCount > 0 && Date.now() - startTime < ROTIF_CONSTANTS.DEFAULT_MAX_WAIT_MS) {
337
+ await delayMs(10);
338
+ }
339
+ this.subscriptions.delete(subId);
340
+ const loopKey = getLoopKey(stream, group);
341
+ const retryLoopKey = getLoopKey(retryStream, group);
342
+ const loop = this.consumerLoops.get(loopKey);
343
+ loop?.subscriptions.delete(sub);
344
+ if (loop && loop.subscriptions.size === 0) {
345
+ this.consumerLoops.delete(loopKey);
346
+ }
347
+ const retryLoop = this.consumerLoops.get(retryLoopKey);
348
+ retryLoop?.subscriptions.delete(sub);
349
+ if (retryLoop && retryLoop.subscriptions.size === 0) {
350
+ this.consumerLoops.delete(retryLoopKey);
351
+ }
352
+ if (removePattern) {
353
+ const newCount = await this.runLuaScript('safe-unsubscribe', ['rotif:patterns'], [pattern]);
354
+ if (Number(newCount) === 0) {
355
+ this.activePatterns.delete(pattern);
356
+ await this.redis.publish('rotif:subscriptions:updates', `remove:${pattern}`);
357
+ this.logger.info(`Unsubscribed from pattern (no more subscribers): ${pattern}`);
358
+ }
359
+ }
360
+ },
361
+ pause: () => {
362
+ sub.isPaused = true;
363
+ },
364
+ resume: () => {
365
+ sub.isPaused = false;
366
+ const loopKey = `${stream}:${group}`;
367
+ const loop = this.consumerLoops.get(loopKey);
368
+ if (loop) {
369
+ loop.needsPendingRecovery = true;
370
+ }
371
+ },
372
+ isPaused: false,
373
+ stats: () => stats.getStats(),
374
+ };
375
+ const mainLoopSubscriptions = await this.startSharedConsumerLoop(stream, group, consumer);
376
+ mainLoopSubscriptions.add(sub);
377
+ const retryLoopSubscriptions = await this.startSharedConsumerLoop(retryStream, group, consumer);
378
+ retryLoopSubscriptions.add(sub);
379
+ const newCount = await this.redis.zincrby('rotif:patterns', 1, pattern);
380
+ if (Number(newCount) === 1) {
381
+ this.activePatterns.add(pattern);
382
+ await this.redis.publish('rotif:subscriptions:updates', `add:${pattern}`);
383
+ this.logger.info(`Subscribed to new pattern: ${pattern}`);
384
+ }
385
+ this.subscriptions.set(subId, sub);
386
+ return sub;
387
+ }
388
+ async startDelayScheduler() {
389
+ const scheduler = async () => {
390
+ if (!this.active)
391
+ return;
392
+ try {
393
+ const movedMessagesCount = await this.runLuaScript('move-scheduled-messages', ['rotif:scheduled'], [Date.now().toString(), String(this.config.scheduledBatchSize ?? 1000)]);
394
+ if (this.active && Number(movedMessagesCount) > 0) {
395
+ this.logger.debug(`Moved ${movedMessagesCount} scheduled messages`);
396
+ }
397
+ }
398
+ catch (err) {
399
+ if (this.active) {
400
+ this.logger.error({ err }, 'DelayScheduler error');
401
+ }
402
+ }
403
+ };
404
+ scheduler();
405
+ this.delayTimeoutId = setInterval(scheduler, this.config.checkDelayInterval ?? 1000);
406
+ }
407
+ async stopAll() {
408
+ if (!this.active) {
409
+ return;
410
+ }
411
+ this.logger.info('Stopping all subscriptions');
412
+ if (this.delayTimeoutId) {
413
+ clearInterval(this.delayTimeoutId);
414
+ }
415
+ this.dlqManager.stopAutoCleanup();
416
+ const unsubscribePromises = Array.from(this.subscriptions.values()).map((sub) => sub.unsubscribe(false));
417
+ await Promise.all(unsubscribePromises);
418
+ this.active = false;
419
+ if (this.dlqSubscriptionPromise) {
420
+ await Promise.race([
421
+ this.dlqSubscriptionPromise,
422
+ delayMs(3000),
423
+ ]);
424
+ }
425
+ const loopPromises = Array.from(this.consumerLoops.values()).map((loop) => loop.loopPromise);
426
+ if (loopPromises.length > 0) {
427
+ await Promise.race([
428
+ Promise.all(loopPromises),
429
+ delayMs(3000),
430
+ ]);
431
+ }
432
+ if (this.redis.status !== 'end') {
433
+ await this.redis.quit();
434
+ }
435
+ if (this.subClient && this.subClient.status !== 'end') {
436
+ await this.subClient.quit();
437
+ }
438
+ if (this.dlqClient && this.dlqClient.status !== 'end') {
439
+ await this.dlqClient.quit();
440
+ }
441
+ this.logger.info('All subscriptions stopped');
442
+ }
443
+ async subscribeToDLQ(handler) {
444
+ await this.initializationDefer.promise;
445
+ const streamKey = this.dlqKey;
446
+ const group = 'dlq-group';
447
+ const consumer = 'dlq-worker';
448
+ if (!this.dlqClient) {
449
+ this.dlqClient = new Redis(this.config.redis);
450
+ }
451
+ try {
452
+ await this.redis.xgroup('CREATE', streamKey, group, '0', 'MKSTREAM');
453
+ }
454
+ catch (err) {
455
+ if (!err?.message?.includes('BUSYGROUP'))
456
+ throw err;
457
+ }
458
+ this.logger.info('[DLQ] Subscribed to DLQ stream');
459
+ this.dlqSubscriptionPromise = (async () => {
460
+ while (this.active) {
461
+ try {
462
+ if (!this.active)
463
+ break;
464
+ const entries = (await this.dlqClient.xreadgroup('GROUP', group, consumer, 'COUNT', 1000, 'BLOCK', 1000, 'STREAMS', streamKey, '>'));
465
+ if (!entries)
466
+ continue;
467
+ for (const [, records] of entries) {
468
+ for (const [id, rawFields] of records) {
469
+ const fields = parseFields(rawFields);
470
+ const channel = fields['channel'] ?? 'unknown';
471
+ const payloadStr = fields['payload'] ?? '{}';
472
+ const timestamp = parseInt(fields['timestamp'] ?? Date.now().toString(), 10);
473
+ const attempt = parseInt(fields['attempt'] ?? '1', 10);
474
+ const msg = {
475
+ id,
476
+ channel,
477
+ payload: JSON.parse(payloadStr),
478
+ timestamp,
479
+ attempt,
480
+ ack: async () => {
481
+ await this.redis.xack(streamKey, group, id);
482
+ },
483
+ };
484
+ try {
485
+ await handler(msg);
486
+ await msg.ack();
487
+ }
488
+ catch (err) {
489
+ this.logger.error({ err, messageId: id }, '[DLQ] Handler failed');
490
+ }
491
+ }
492
+ }
493
+ }
494
+ catch (err) {
495
+ if (!this.active)
496
+ break;
497
+ if (err?.message?.includes('NOGROUP')) {
498
+ this.logger.debug(`[DLQ] Consumer group ${group} not found, creating it`);
499
+ try {
500
+ await this.redis.xgroup('CREATE', streamKey, group, '0', 'MKSTREAM');
501
+ }
502
+ catch (createErr) {
503
+ if (!createErr?.message?.includes('BUSYGROUP')) {
504
+ this.logger.error({ err: createErr }, '[DLQ] Failed to create consumer group');
505
+ }
506
+ }
507
+ await delayMs(100);
508
+ continue;
509
+ }
510
+ this.logger.error({ err }, '[DLQ] Processing error');
511
+ await delayMs(500);
512
+ }
513
+ }
514
+ })();
515
+ return this.dlqSubscriptionPromise;
516
+ }
517
+ async requeueFromDLQ(count = 10) {
518
+ await this.initializationDefer.promise;
519
+ const requeuedCount = await this.runLuaScript('requeue-from-dlq', [this.dlqKey], [count.toString()]);
520
+ this.logger.info(`Requeued ${requeuedCount} messages from DLQ`);
521
+ return Number(requeuedCount);
522
+ }
523
+ subscribeToPatternUpdates() {
524
+ const connect = () => {
525
+ if (!this.active)
526
+ return;
527
+ if (this.subClient) {
528
+ this.subClient.disconnect();
529
+ this.subClient.removeAllListeners();
530
+ }
531
+ this.subClient = new Redis(this.config.redis);
532
+ this.subClient.subscribe('rotif:subscriptions:updates').catch((err) => {
533
+ this.logger.error({ err }, 'Pub/Sub subscription failed');
534
+ });
535
+ this.subClient.on('message', (_, message) => {
536
+ const [action, pattern] = message.split(':');
537
+ if (action === 'add') {
538
+ this.activePatterns.add(pattern);
539
+ }
540
+ else if (action === 'remove') {
541
+ this.activePatterns.delete(pattern);
542
+ }
543
+ });
544
+ this.subClient.on('error', (err) => {
545
+ this.logger.error({ err }, 'Pub/Sub subscriber error');
546
+ });
547
+ this.subClient.on('end', () => {
548
+ if (!this.active)
549
+ return;
550
+ this.logger.warn('Pub/Sub subscriber disconnected, reconnecting...');
551
+ setTimeout(connect, 1000);
552
+ });
553
+ this.subClient.on('connect', () => {
554
+ this.syncPatterns();
555
+ this.logger.info('Pub/Sub subscriber connected');
556
+ });
557
+ };
558
+ connect();
559
+ }
560
+ async startSharedConsumerLoop(stream, group, consumer) {
561
+ const loopKey = getLoopKey(stream, group);
562
+ const existingLoop = this.consumerLoops.get(loopKey);
563
+ if (existingLoop) {
564
+ await existingLoop.readyPromise;
565
+ return existingLoop.subscriptions;
566
+ }
567
+ const subscriptions = new Set();
568
+ const readyDefer = defer();
569
+ this.backpressureStates.set(loopKey, { active: false, pendingCount: 0 });
570
+ const messageConcurrency = this.config.messageConcurrency ?? ROTIF_CONSTANTS.DEFAULT_MESSAGE_CONCURRENCY;
571
+ const handleMessage = async (id, rawFields) => {
572
+ const fields = this.enableFieldPooling ? parseFieldsFast(rawFields) : parseFields(rawFields);
573
+ const channel = fields['channel'] ?? '';
574
+ const payloadStr = fields['payload'] ?? '{}';
575
+ const timestamp = parseInt(fields['timestamp'] ?? '0');
576
+ const attempt = parseInt(fields['attempt'] ?? '1');
577
+ const exactlyOnce = (fields['exactlyOnce'] ?? 'false') === 'true';
578
+ const dedupTTL = fields['dedupTTL'];
579
+ const pattern = fields['pattern'] ?? channel;
580
+ let payload;
581
+ try {
582
+ payload = payloadStr ? JSON.parse(payloadStr) : null;
583
+ }
584
+ catch (parseError) {
585
+ this.logger.error({ err: parseError, messageId: id, payloadStr }, 'Failed to parse payload');
586
+ const errorMessage = parseError instanceof Error ? parseError.message : 'Failed to parse message payload';
587
+ await this.runLuaScript('move-to-dlq', [stream, this.dlqKey], [
588
+ group,
589
+ id,
590
+ channel,
591
+ payloadStr,
592
+ errorMessage,
593
+ timestamp.toString(),
594
+ attempt.toString(),
595
+ exactlyOnce ? 'true' : 'false',
596
+ dedupTTL ?? '3600',
597
+ ]);
598
+ return;
599
+ }
600
+ const msg = {
601
+ id,
602
+ channel,
603
+ payload,
604
+ timestamp,
605
+ attempt,
606
+ ack: async () => {
607
+ await this.runLuaScript('ack-message', [stream], [group, id, '1']);
608
+ },
609
+ };
610
+ const matchingSubs = [];
611
+ let hasAnyMatchingPattern = false;
612
+ for (const sub of subscriptions) {
613
+ let matcher = this.patternMatcherCache.get(sub.pattern);
614
+ if (!matcher) {
615
+ matcher = getCachedMatcher(sub.pattern, minimatch);
616
+ this.patternMatcherCache.set(sub.pattern, matcher);
617
+ }
618
+ if (matcher(channel)) {
619
+ hasAnyMatchingPattern = true;
620
+ if (!sub.isPaused) {
621
+ matchingSubs.push(sub);
622
+ }
623
+ }
624
+ }
625
+ if (matchingSubs.length === 0) {
626
+ if (hasAnyMatchingPattern) {
627
+ }
628
+ else {
629
+ this.logger.warn(`No matching subscriptions for channel=${channel}, msg=${id}`);
630
+ await this.runLuaScript('ack-message', [stream], [group, id, '1']);
631
+ }
632
+ if (this.enableFieldPooling && 'channel' in fields) {
633
+ releaseFields(fields);
634
+ }
635
+ return;
636
+ }
637
+ let subs;
638
+ if (this.config.localRoundRobin) {
639
+ const subIndex = this.getRoundRobinIndex(stream, group, matchingSubs.length);
640
+ subs = [matchingSubs[subIndex]];
641
+ }
642
+ else {
643
+ subs = matchingSubs;
644
+ }
645
+ for (const sub of subs) {
646
+ if (!subscriptions.has(sub) || sub.isPaused) {
647
+ continue;
648
+ }
649
+ sub.inflightCount += 1;
650
+ if (msg.attempt > 1) {
651
+ sub.statsTracker?.recordRetry();
652
+ }
653
+ const maxRetries = sub.options?.maxRetries ?? this.config.maxRetries ?? 5;
654
+ if (msg.attempt > 1 && msg.attempt > maxRetries + 1) {
655
+ await this.runLuaScript('move-to-dlq', [stream, this.dlqKey], [
656
+ group,
657
+ msg.id,
658
+ channel,
659
+ payloadStr,
660
+ 'Max retries exceeded',
661
+ msg.timestamp.toString(),
662
+ msg.attempt.toString(),
663
+ exactlyOnce ? 'true' : 'false',
664
+ dedupTTL ?? '3600',
665
+ ]);
666
+ sub.statsTracker?.recordFailure();
667
+ this.logger.error({ messageId: id }, 'Message moved to DLQ - max retries exceeded');
668
+ sub.inflightCount = Math.max(0, sub.inflightCount - 1);
669
+ continue;
670
+ }
671
+ let dedupKey = '';
672
+ if (exactlyOnce) {
673
+ dedupKey = generateDedupKey({ channel, payload: msg.payload, group, side: 'con' });
674
+ const wasSet = await this.redis.set(dedupKey, '1', 'EX', dedupTTL ? Number(dedupTTL) : 3600, 'NX');
675
+ if (!wasSet) {
676
+ await msg.ack();
677
+ this.logger.info(`Duplicate message detected for channel=${channel} and group=${group} msg=${id}`);
678
+ sub.inflightCount = Math.max(0, sub.inflightCount - 1);
679
+ continue;
680
+ }
681
+ }
682
+ try {
683
+ await this.middleware.runBeforeProcess(msg);
684
+ await sub.handler(msg);
685
+ await msg.ack();
686
+ await this.middleware.runAfterProcess(msg);
687
+ sub.statsTracker?.recordMessage();
688
+ }
689
+ catch (err) {
690
+ await this.middleware.runOnError(msg, err);
691
+ if (exactlyOnce && dedupKey) {
692
+ await this.redis.del(dedupKey);
693
+ }
694
+ if (msg.attempt >= maxRetries + 1) {
695
+ const errorMessage = err instanceof Error ? err.message : String(err);
696
+ await this.runLuaScript('move-to-dlq', [stream, this.dlqKey], [
697
+ group,
698
+ msg.id,
699
+ channel,
700
+ payloadStr,
701
+ errorMessage,
702
+ msg.timestamp.toString(),
703
+ msg.attempt.toString(),
704
+ exactlyOnce ? 'true' : 'false',
705
+ dedupTTL ?? '3600',
706
+ ]);
707
+ sub.statsTracker?.recordFailure();
708
+ this.logger.error({ messageId: id, error: errorMessage }, 'Message moved to DLQ after error');
709
+ sub.inflightCount = Math.max(0, sub.inflightCount - 1);
710
+ continue;
711
+ }
712
+ let retryDelay;
713
+ if (sub.options?.retryStrategy) {
714
+ const retryFn = createRetryDelayFn(sub.options.retryStrategy);
715
+ retryDelay = retryFn(msg.attempt, msg);
716
+ }
717
+ else if (this.config.retryStrategy) {
718
+ const retryFn = createRetryDelayFn(this.config.retryStrategy);
719
+ retryDelay = retryFn(msg.attempt, msg);
720
+ }
721
+ else if (typeof sub.options?.retryDelay === 'function') {
722
+ retryDelay = sub.options.retryDelay(msg.attempt, msg);
723
+ }
724
+ else {
725
+ retryDelay = Number(sub.options?.retryDelay ?? this.config.retryDelay ?? 1000);
726
+ }
727
+ const mainStream = stream.endsWith(':retry')
728
+ ? stream.slice(0, -6)
729
+ : stream;
730
+ const nextAttempt = attempt + 1;
731
+ const retryAt = Date.now() + retryDelay;
732
+ try {
733
+ this.logger.debug(`Scheduling retry: stream=${mainStream}, attempt=${nextAttempt}, delay=${retryDelay}ms`);
734
+ const result = await this.runLuaScript('retry-message', [stream, 'rotif:scheduled'], [
735
+ group,
736
+ msg.id,
737
+ channel,
738
+ payloadStr,
739
+ timestamp.toString(),
740
+ nextAttempt.toString(),
741
+ retryAt.toString(),
742
+ generateUuidV7(),
743
+ fields['exactlyOnce'] ?? 'false',
744
+ dedupTTL ?? '3600',
745
+ mainStream,
746
+ pattern,
747
+ ]);
748
+ this.logger.debug(`Retry scheduled successfully: ${result}`);
749
+ }
750
+ catch (luaErr) {
751
+ this.logger.error({ err: luaErr }, 'Failed to schedule retry');
752
+ throw luaErr;
753
+ }
754
+ }
755
+ finally {
756
+ sub.inflightCount = Math.max(0, sub.inflightCount - 1);
757
+ }
758
+ }
759
+ if (this.enableFieldPooling && 'channel' in fields && typeof fields.channel === 'string') {
760
+ releaseFields(fields);
761
+ }
762
+ };
763
+ const loopEntry = {
764
+ loopPromise: null,
765
+ subscriptions,
766
+ readyPromise: readyDefer.promise,
767
+ };
768
+ this.consumerLoops.set(loopKey, loopEntry);
769
+ loopEntry.loopPromise = (async () => {
770
+ this.logger.info(`Starting shared consumer loop for ${stream}:${group}`);
771
+ let lastPendingCheck = Date.now();
772
+ const pendingCheckInterval = this.config.pendingCheckInterval ?? 30000;
773
+ const idleThreshold = this.config.pendingIdleThreshold ?? 60000;
774
+ readyDefer.resolve?.(undefined);
775
+ while (this.active) {
776
+ if (subscriptions.size === 0) {
777
+ if (!this.consumerLoops.has(loopKey)) {
778
+ break;
779
+ }
780
+ await delayMs(100);
781
+ continue;
782
+ }
783
+ if (this.shouldApplyBackpressure(loopKey)) {
784
+ this.logger.debug({ loopKey }, 'Backpressure active, pausing consumption');
785
+ await delayMs(50);
786
+ continue;
787
+ }
788
+ try {
789
+ if (!this.config.disablePendingMessageRecovery) {
790
+ const now = Date.now();
791
+ const loopData = this.consumerLoops.get(loopKey);
792
+ const forceRecovery = loopData?.needsPendingRecovery;
793
+ if (forceRecovery) {
794
+ loopData.needsPendingRecovery = false;
795
+ }
796
+ if (forceRecovery || now - lastPendingCheck >= pendingCheckInterval) {
797
+ lastPendingCheck = now;
798
+ try {
799
+ const effectiveIdleThreshold = forceRecovery ? 0 : idleThreshold;
800
+ const pendingEntries = await this.redis.xpending(stream, group, 'IDLE', effectiveIdleThreshold, '-', '+', 100);
801
+ if (pendingEntries && pendingEntries.length > 0) {
802
+ const staleIds = pendingEntries.map((entry) => entry[0]);
803
+ const claimedMessages = (await this.redis.xclaim(stream, group, consumer, effectiveIdleThreshold, ...staleIds));
804
+ if (messageConcurrency > 1 && claimedMessages.length > 1) {
805
+ this.updateBackpressure(loopKey, claimedMessages.length);
806
+ try {
807
+ await processWithConcurrency(claimedMessages, async ([id, rawFields]) => {
808
+ await handleMessage(id, rawFields);
809
+ }, messageConcurrency);
810
+ }
811
+ finally {
812
+ this.updateBackpressure(loopKey, -claimedMessages.length);
813
+ }
814
+ }
815
+ else {
816
+ for (const [id, rawFields] of claimedMessages) {
817
+ this.updateBackpressure(loopKey, 1);
818
+ try {
819
+ await handleMessage(id, rawFields);
820
+ }
821
+ finally {
822
+ this.updateBackpressure(loopKey, -1);
823
+ }
824
+ }
825
+ }
826
+ }
827
+ }
828
+ catch (pendingErr) {
829
+ if (pendingErr?.message?.includes('NOGROUP')) {
830
+ this.logger.debug(`Consumer group ${group} not found for stream ${stream}, creating it`);
831
+ await this.ensureStreamGroup(stream, group);
832
+ continue;
833
+ }
834
+ throw pendingErr;
835
+ }
836
+ }
837
+ }
838
+ const entries = await this.redis.xreadgroup('GROUP', group, consumer, 'COUNT', ROTIF_CONSTANTS.DEFAULT_READ_COUNT, 'BLOCK', this.config.blockInterval ?? ROTIF_CONSTANTS.DEFAULT_MAX_WAIT_MS, 'STREAMS', stream, '>');
839
+ if (!entries) {
840
+ continue;
841
+ }
842
+ const typedEntries = entries;
843
+ for (const [_streamName, records] of typedEntries) {
844
+ if (messageConcurrency > 1 && records.length > 1) {
845
+ this.updateBackpressure(loopKey, records.length);
846
+ try {
847
+ await processWithConcurrency(records, async ([id, rawFields]) => {
848
+ await handleMessage(id, rawFields);
849
+ }, messageConcurrency);
850
+ }
851
+ finally {
852
+ this.updateBackpressure(loopKey, -records.length);
853
+ }
854
+ }
855
+ else {
856
+ for (const [id, rawFields] of records) {
857
+ this.updateBackpressure(loopKey, 1);
858
+ try {
859
+ await handleMessage(id, rawFields);
860
+ }
861
+ finally {
862
+ this.updateBackpressure(loopKey, -1);
863
+ }
864
+ }
865
+ }
866
+ }
867
+ }
868
+ catch (err) {
869
+ if (!this.active)
870
+ break;
871
+ if (err?.message?.includes('NOGROUP')) {
872
+ this.logger.debug(`Consumer group ${group} not found for stream ${stream}, creating it`);
873
+ await this.ensureStreamGroup(stream, group);
874
+ await delayMs(100);
875
+ continue;
876
+ }
877
+ this.logger.error({ err, stream, group }, 'Error reading stream');
878
+ await delayMs(500);
879
+ }
880
+ }
881
+ if (this.active) {
882
+ this.logger.info(`Stopped shared consumer loop for ${stream}:${group}`);
883
+ }
884
+ })();
885
+ await readyDefer.promise;
886
+ return subscriptions;
887
+ }
888
+ async syncPatterns() {
889
+ try {
890
+ const patterns = await this.redis.zrangebyscore('rotif:patterns', 1, '+inf');
891
+ this.activePatterns = new Set(patterns);
892
+ }
893
+ catch (err) {
894
+ this.logger.error({ err }, 'Error syncing patterns');
895
+ }
896
+ }
897
+ async ensureStreamGroup(stream, group, startId = '0') {
898
+ try {
899
+ await this.redis.xgroup('CREATE', stream, group, startId, 'MKSTREAM');
900
+ }
901
+ catch (err) {
902
+ if (!err?.message?.includes('BUSYGROUP'))
903
+ throw err;
904
+ }
905
+ }
906
+ getRoundRobinIndex(stream, group, count) {
907
+ const key = `${stream}:${group}`;
908
+ const current = this.roundRobinIndices.get(key) || 0;
909
+ const next = (current + 1) % count;
910
+ this.roundRobinIndices.set(key, next);
911
+ return current;
912
+ }
913
+ async getDLQStats() {
914
+ return this.dlqManager.getStats();
915
+ }
916
+ async getDLQMessages(options) {
917
+ return this.dlqManager.getMessages(options);
918
+ }
919
+ async cleanupDLQ() {
920
+ return this.dlqManager.cleanup();
921
+ }
922
+ async clearDLQ() {
923
+ return this.dlqManager.clear();
924
+ }
925
+ updateDLQConfig(config) {
926
+ this.dlqManager.updateConfig(config);
927
+ }
928
+ static { this.RetryStrategies = RetryStrategies; }
929
+ static { this.createRetryDelayFn = createRetryDelayFn; }
930
+ getSubscriptionStats() {
931
+ let active = 0;
932
+ let paused = 0;
933
+ for (const sub of this.subscriptions.values()) {
934
+ if (sub.isPaused) {
935
+ paused++;
936
+ }
937
+ else {
938
+ active++;
939
+ }
940
+ }
941
+ return {
942
+ count: this.subscriptions.size,
943
+ active,
944
+ paused,
945
+ };
946
+ }
947
+ }
948
+ //# sourceMappingURL=rotif.js.map