@burdenoff/be-sdk 2026.514.2 → 2026.516.2

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 (66) hide show
  1. package/dist/EventQueueFactory-6UJ3UIP4.js +6 -0
  2. package/dist/{EventQueueFactory-DGHBOV7I.js.map → EventQueueFactory-6UJ3UIP4.js.map} +1 -1
  3. package/dist/cache/index.d.ts +1 -1
  4. package/dist/cache/index.js +1 -1
  5. package/dist/{chunk-FT74HIIG.js → chunk-24VR7PF3.js} +2 -2
  6. package/dist/{chunk-FT74HIIG.js.map → chunk-24VR7PF3.js.map} +1 -1
  7. package/dist/chunk-75VTKG4Q.js +243 -0
  8. package/dist/chunk-75VTKG4Q.js.map +1 -0
  9. package/dist/{chunk-M3PYLAPT.js → chunk-7Y3RNUS3.js} +4 -4
  10. package/dist/{chunk-M3PYLAPT.js.map → chunk-7Y3RNUS3.js.map} +1 -1
  11. package/dist/{chunk-FSTWNBRX.js → chunk-MQ6OE5QR.js} +10 -33
  12. package/dist/chunk-MQ6OE5QR.js.map +1 -0
  13. package/dist/{chunk-N52W3RQA.js → chunk-MVHOP4IG.js} +3 -174
  14. package/dist/chunk-MVHOP4IG.js.map +1 -0
  15. package/dist/{chunk-S74C6CEN.js → chunk-Q6N74R6S.js} +61 -68
  16. package/dist/chunk-Q6N74R6S.js.map +1 -0
  17. package/dist/chunk-RRFNSBDZ.js +181 -0
  18. package/dist/chunk-RRFNSBDZ.js.map +1 -0
  19. package/dist/{chunk-D35GTG7Y.js → chunk-SNW4BLF2.js} +3 -3
  20. package/dist/{chunk-D35GTG7Y.js.map → chunk-SNW4BLF2.js.map} +1 -1
  21. package/dist/chunk-TM5RQ6P2.js +925 -0
  22. package/dist/chunk-TM5RQ6P2.js.map +1 -0
  23. package/dist/{chunk-IX5QCHWE.js → chunk-U455UF4O.js} +3 -3
  24. package/dist/{chunk-IX5QCHWE.js.map → chunk-U455UF4O.js.map} +1 -1
  25. package/dist/{chunk-CCV2AVAI.js → chunk-V4RLPTTT.js} +3 -3
  26. package/dist/{chunk-CCV2AVAI.js.map → chunk-V4RLPTTT.js.map} +1 -1
  27. package/dist/{chunk-KLYAIEAX.js → chunk-VKSB2K5E.js} +15 -30
  28. package/dist/chunk-VKSB2K5E.js.map +1 -0
  29. package/dist/event-queue/index.d.ts +2 -2
  30. package/dist/event-queue/index.js +4 -6
  31. package/dist/export/index.js +3 -3
  32. package/dist/gateway/index.js +2 -2
  33. package/dist/gateway/security/index.js +1 -1
  34. package/dist/graph/index.d.ts +2 -2
  35. package/dist/graph/index.js +5 -6
  36. package/dist/{graph-emitter-Bk0FqD53.d.ts → graph-emitter-Dp7UE1Yd.d.ts} +3 -2
  37. package/dist/graphql/index.d.ts +1 -1
  38. package/dist/graphql/index.js +2 -2
  39. package/dist/{index-C1ojTQq0.d.ts → index-B6IwtUb1.d.ts} +2 -0
  40. package/dist/{index-DZO2nvC9.d.ts → index-Bo58dlMU.d.ts} +2 -2
  41. package/dist/{index-syMAjErz.d.ts → index-D_Nc4UHi.d.ts} +6 -84
  42. package/dist/index-joONjwLt.d.ts +33 -0
  43. package/dist/{index-XY9x2I6b.d.ts → index-tJYziwMs.d.ts} +1 -0
  44. package/dist/index.d.ts +8 -8
  45. package/dist/index.js +14 -15
  46. package/dist/index.js.map +1 -1
  47. package/dist/init/index.d.ts +1 -1
  48. package/dist/init/index.js +3 -6
  49. package/dist/prisma/index.js +4 -6
  50. package/package.json +1 -6
  51. package/dist/EventQueueFactory-DGHBOV7I.js +0 -8
  52. package/dist/chunk-7V6GUNGP.js +0 -438
  53. package/dist/chunk-7V6GUNGP.js.map +0 -1
  54. package/dist/chunk-FSTWNBRX.js.map +0 -1
  55. package/dist/chunk-KLYAIEAX.js.map +0 -1
  56. package/dist/chunk-LRGXT37B.js +0 -1966
  57. package/dist/chunk-LRGXT37B.js.map +0 -1
  58. package/dist/chunk-N52W3RQA.js.map +0 -1
  59. package/dist/chunk-Q4HKXQVD.js +0 -478
  60. package/dist/chunk-Q4HKXQVD.js.map +0 -1
  61. package/dist/chunk-S74C6CEN.js.map +0 -1
  62. package/dist/chunk-UVYDP6P6.js +0 -13
  63. package/dist/chunk-UVYDP6P6.js.map +0 -1
  64. package/dist/config-QVYSAUMT.js +0 -4
  65. package/dist/config-QVYSAUMT.js.map +0 -1
  66. package/dist/index-CDFQRL-h.d.ts +0 -66
@@ -1,1966 +0,0 @@
1
- import { QueueType } from './chunk-UVYDP6P6.js';
2
- import { NatsConnectionManager, RedisStreamsConnection, isWildcard, streamKey, boundaryOf, dlqKey, registryKey, delayQueueKey, delayLockKey, dedupKey, replyKey, matchSubject } from './chunk-N52W3RQA.js';
3
- import { DEFAULT_LAYER_RESOURCES } from './chunk-NGMEI42S.js';
4
- import { logger } from './chunk-CBZNP6RF.js';
5
- import { __name } from './chunk-XE4OXN2W.js';
6
- import { RetentionPolicy, StorageType, AckPolicy, DeliverPolicy, headers } from 'nats';
7
- import { randomUUID } from 'crypto';
8
- import { hostname } from 'os';
9
-
10
- // src/event-queue/implementations/nats/trace-context.ts
11
- var otelApiPromise = null;
12
- async function loadOtelApi() {
13
- if (otelApiPromise) {
14
- return otelApiPromise;
15
- }
16
- otelApiPromise = (async () => {
17
- try {
18
- const mod = await import('./esm-M2M7HGV4.js');
19
- return mod;
20
- } catch {
21
- logger.debug("[trace-context] @opentelemetry/api not available; NATS traces disabled");
22
- return null;
23
- }
24
- })();
25
- return otelApiPromise;
26
- }
27
- __name(loadOtelApi, "loadOtelApi");
28
- var setter = {
29
- set(carrier, key, value) {
30
- carrier[key] = value;
31
- }
32
- };
33
- var getter = {
34
- get(carrier, key) {
35
- return carrier[key];
36
- },
37
- keys(carrier) {
38
- return Object.keys(carrier);
39
- }
40
- };
41
- async function injectW3CTraceContext(hdrs) {
42
- const api = await loadOtelApi();
43
- if (!api) return;
44
- try {
45
- const carrier = {};
46
- api.propagation.inject(api.context.active(), carrier, setter);
47
- for (const [key, value] of Object.entries(carrier)) {
48
- if (value) hdrs.set(key, value);
49
- }
50
- } catch (err) {
51
- logger.debug("[trace-context] injection failed", {
52
- error: err instanceof Error ? err.message : String(err)
53
- });
54
- }
55
- }
56
- __name(injectW3CTraceContext, "injectW3CTraceContext");
57
- async function extractW3CTraceContext(hdrs) {
58
- const api = await loadOtelApi();
59
- if (!api || !hdrs) return void 0;
60
- try {
61
- const carrier = {};
62
- for (const key of [
63
- "traceparent",
64
- "tracestate",
65
- "baggage"
66
- ]) {
67
- const value = hdrs.get(key);
68
- if (value) carrier[key] = value;
69
- }
70
- return api.propagation.extract(api.context.active(), carrier, getter);
71
- } catch (err) {
72
- logger.debug("[trace-context] extraction failed", {
73
- error: err instanceof Error ? err.message : String(err)
74
- });
75
- return void 0;
76
- }
77
- }
78
- __name(extractW3CTraceContext, "extractW3CTraceContext");
79
- async function runWithConsumerSpan(subject, hdrs, handler) {
80
- const api = await loadOtelApi();
81
- if (!api) return handler();
82
- try {
83
- const parentCtx = await extractW3CTraceContext(hdrs);
84
- const tracer = api.trace.getTracer("@burdenoff/be-sdk/nats");
85
- return await new Promise((resolve, reject) => {
86
- tracer.startActiveSpan(`nats.consume ${subject}`, {
87
- kind: 5,
88
- attributes: {
89
- "messaging.system": "nats",
90
- "messaging.destination.name": subject
91
- }
92
- }, parentCtx, async (span) => {
93
- try {
94
- const result = await handler();
95
- span.setStatus({
96
- code: 1
97
- });
98
- span.end();
99
- resolve(result);
100
- } catch (err) {
101
- span.recordException(err);
102
- span.setStatus({
103
- code: 2,
104
- message: err instanceof Error ? err.message : String(err)
105
- });
106
- span.end();
107
- reject(err);
108
- }
109
- });
110
- });
111
- } catch (err) {
112
- logger.debug("[trace-context] consumer span failed to start; running without span", {
113
- error: err instanceof Error ? err.message : String(err)
114
- });
115
- return handler();
116
- }
117
- }
118
- __name(runWithConsumerSpan, "runWithConsumerSpan");
119
- var DEFAULT_STREAM_MAX_BYTES = 10 * 1024 * 1024;
120
- var NatsSubscription = class NatsSubscription2 {
121
- static {
122
- __name(this, "NatsSubscription");
123
- }
124
- id;
125
- subject;
126
- stopFn;
127
- active = true;
128
- stats = {
129
- messagesReceived: 0,
130
- messagesProcessed: 0,
131
- messagesFailed: 0,
132
- lastActivity: (/* @__PURE__ */ new Date()).toISOString()
133
- };
134
- constructor(id, subject, stopFn) {
135
- this.id = id;
136
- this.subject = subject;
137
- this.stopFn = stopFn;
138
- }
139
- async unsubscribe() {
140
- if (!this.active) {
141
- return Promise.resolve();
142
- }
143
- this.active = false;
144
- this.stopFn();
145
- return Promise.resolve();
146
- }
147
- isActive() {
148
- return this.active;
149
- }
150
- getStats() {
151
- return {
152
- messagesReceived: this.stats.messagesReceived,
153
- messagesProcessed: this.stats.messagesProcessed,
154
- messagesFailed: this.stats.messagesFailed,
155
- lastActivity: this.stats.lastActivity
156
- };
157
- }
158
- incrementReceived() {
159
- this.stats.messagesReceived++;
160
- this.stats.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
161
- }
162
- incrementProcessed() {
163
- this.stats.messagesProcessed++;
164
- this.stats.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
165
- }
166
- incrementFailed() {
167
- this.stats.messagesFailed++;
168
- this.stats.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
169
- }
170
- };
171
- var NatsEventConsumer = class {
172
- static {
173
- __name(this, "NatsEventConsumer");
174
- }
175
- config;
176
- connectionManager;
177
- subscriptions = /* @__PURE__ */ new Map();
178
- constructor(config) {
179
- this.config = config;
180
- const baseConfig = {
181
- type: config.type || "nats",
182
- url: config.url || "nats://localhost:4222",
183
- user: config.user,
184
- password: config.password,
185
- token: config.token,
186
- creds: config.creds,
187
- credsFile: config.credsFile,
188
- maxReconnectAttempts: config.maxReconnectAttempts,
189
- reconnectTimeWait: config.reconnectTimeWait,
190
- connectionTimeout: config.connectionTimeout,
191
- name: config.name
192
- };
193
- this.connectionManager = new NatsConnectionManager(baseConfig);
194
- }
195
- /**
196
- * Connect to NATS server
197
- */
198
- async connect() {
199
- await this.connectionManager.connect();
200
- }
201
- /**
202
- * Disconnect from NATS server
203
- */
204
- async disconnect() {
205
- await this.unsubscribeAll();
206
- await this.connectionManager.disconnect();
207
- }
208
- /**
209
- * Check if connected
210
- */
211
- isConnected() {
212
- return this.connectionManager.isConnected();
213
- }
214
- /**
215
- * Health check
216
- */
217
- async healthCheck() {
218
- await Promise.resolve();
219
- const isConnected = this.isConnected();
220
- return {
221
- status: isConnected ? "healthy" : "unhealthy",
222
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
223
- connected: isConnected,
224
- details: {
225
- type: "nats",
226
- url: this.config.url,
227
- activeSubscriptions: this.subscriptions.size
228
- }
229
- };
230
- }
231
- /**
232
- * Get queue statistics
233
- */
234
- async getStatistics() {
235
- await Promise.resolve();
236
- let totalReceived = 0;
237
- let totalProcessed = 0;
238
- let totalFailed = 0;
239
- let lastActivity = null;
240
- for (const subscription of this.subscriptions.values()) {
241
- const stats = subscription.getStats();
242
- totalReceived += stats.messagesReceived;
243
- totalProcessed += stats.messagesProcessed;
244
- totalFailed += stats.messagesFailed;
245
- if (stats.lastActivity && (!lastActivity || stats.lastActivity > lastActivity)) {
246
- lastActivity = stats.lastActivity;
247
- }
248
- }
249
- return {
250
- messagesPublished: 0,
251
- messagesConsumed: totalProcessed,
252
- messagesFailed: totalFailed,
253
- activeConsumers: this.subscriptions.size,
254
- activePublishers: 0,
255
- queueSize: 0,
256
- lastActivity,
257
- details: {
258
- totalReceived,
259
- type: "nats"
260
- }
261
- };
262
- }
263
- /**
264
- * Ensure a stream exists
265
- */
266
- async ensureStream(config) {
267
- const jsm = this.connectionManager.getJetStreamManager();
268
- try {
269
- try {
270
- await jsm.streams.info(config.name);
271
- logger.debug("[NatsEventConsumer] Stream already exists", {
272
- stream: config.name
273
- });
274
- return;
275
- } catch {
276
- }
277
- const streamConfig = {
278
- name: config.name,
279
- subjects: config.subjects,
280
- retention: this.mapRetentionPolicy(config.retention),
281
- storage: this.mapStorageType(config.storage),
282
- max_consumers: config.maxConsumers,
283
- max_msgs: config.maxMsgs,
284
- max_bytes: config.maxBytes ?? DEFAULT_STREAM_MAX_BYTES,
285
- max_age: config.maxAge,
286
- duplicate_window: config.duplicateWindow
287
- };
288
- await jsm.streams.add(streamConfig);
289
- logger.info("[NatsEventConsumer] Stream created successfully", {
290
- stream: config.name,
291
- subjects: config.subjects
292
- });
293
- } catch (error) {
294
- logger.error("[NatsEventConsumer] Failed to ensure stream", {
295
- stream: config.name,
296
- error: error instanceof Error ? error.message : "Unknown error"
297
- });
298
- throw error;
299
- }
300
- }
301
- /**
302
- * Ensure a consumer exists
303
- */
304
- async ensureConsumer(config) {
305
- const jsm = this.connectionManager.getJetStreamManager();
306
- try {
307
- await jsm.consumers.add(config.stream, {
308
- name: config.consumer,
309
- durable_name: config.consumer,
310
- filter_subject: config.filterSubject,
311
- ack_policy: this.mapAckPolicy(config.ackPolicy),
312
- deliver_policy: this.mapDeliverPolicy(config.deliverPolicy),
313
- max_deliver: config.maxDeliver || 3,
314
- ack_wait: config.ackWait || 3e10,
315
- max_ack_pending: config.maxAckPending || 100
316
- });
317
- logger.info("[NatsEventConsumer] Consumer created successfully", {
318
- stream: config.stream,
319
- consumer: config.consumer
320
- });
321
- } catch (error) {
322
- if (error instanceof Error && error.message?.includes("already exists")) {
323
- logger.debug("[NatsEventConsumer] Consumer already exists", {
324
- stream: config.stream,
325
- consumer: config.consumer
326
- });
327
- } else {
328
- logger.error("[NatsEventConsumer] Failed to ensure consumer", {
329
- stream: config.stream,
330
- consumer: config.consumer,
331
- error: error instanceof Error ? error.message : "Unknown error"
332
- });
333
- throw error;
334
- }
335
- }
336
- }
337
- /**
338
- * Derive stream subject pattern from subscription subject
339
- * Examples:
340
- * - "channel.conversation.message" → ["channel.>"]
341
- * - "wspace.tags.created" → ["wspace.>"]
342
- * - "global.auth.login" → ["global.>"]
343
- */
344
- deriveStreamSubjects(subject) {
345
- const firstSegment = subject.split(".")[0];
346
- if (firstSegment) {
347
- return [
348
- `${firstSegment}.>`
349
- ];
350
- }
351
- return [
352
- `${subject.replace(/\.[^.]+$/, ".>")}`
353
- ];
354
- }
355
- /**
356
- * Subscribe to a subject
357
- */
358
- async subscribe(options) {
359
- const js = this.connectionManager.getJetStream();
360
- const jsm = this.connectionManager.getJetStreamManager();
361
- try {
362
- let streamName = options.options?.stream || this.config.stream;
363
- const consumerName = options.options?.consumer || `${this.config.consumer}-${options.subject.replace(/\./g, "-")}`;
364
- const streamSubjects = options.options?.streamSubjects || this.deriveStreamSubjects(options.subject);
365
- try {
366
- await this.ensureStream({
367
- name: streamName,
368
- subjects: streamSubjects,
369
- retention: options.options?.retention || "limits",
370
- storage: options.options?.storage || "file"
371
- });
372
- } catch (error) {
373
- const errorMessage = error instanceof Error ? error.message : String(error);
374
- if (!errorMessage.includes("subjects overlap")) {
375
- throw error;
376
- }
377
- streamName = await jsm.streams.find(options.subject);
378
- logger.info("[NatsEventConsumer] Using existing stream for overlapping subject", {
379
- requestedStream: options.options?.stream || this.config.stream,
380
- stream: streamName,
381
- subject: options.subject
382
- });
383
- }
384
- await this.ensureConsumer({
385
- type: this.config.type,
386
- url: this.config.url,
387
- consumer: consumerName,
388
- stream: streamName,
389
- filterSubject: options.subject,
390
- ackPolicy: options.options?.ackPolicy,
391
- deliverPolicy: options.options?.deliverPolicy,
392
- maxDeliver: options.options?.maxDeliver || this.config.maxDeliver,
393
- ackWait: options.options?.ackWait || this.config.ackWait,
394
- maxAckPending: options.options?.maxAckPending
395
- });
396
- const consumer = await js.consumers.get(streamName, consumerName);
397
- const subscriptionId = `sub_${Date.now()}_${crypto.randomUUID().substring(0, 7)}`;
398
- let stopRequested = false;
399
- const stopFn = /* @__PURE__ */ __name(() => {
400
- stopRequested = true;
401
- }, "stopFn");
402
- const subscription = new NatsSubscription(subscriptionId, options.subject, stopFn);
403
- this.subscriptions.set(subscriptionId, subscription);
404
- this.consumeMessages(consumer, subscription, options.handler, options.options?.maxConcurrent || this.config.maxConcurrent || 1, () => stopRequested).catch((error) => {
405
- logger.error("[NatsEventConsumer] Error in message consumption loop", {
406
- subject: options.subject,
407
- error: error instanceof Error ? error.message : "Unknown error"
408
- });
409
- });
410
- logger.info("[NatsEventConsumer] Subscription created", {
411
- subscriptionId,
412
- subject: options.subject
413
- });
414
- return subscription;
415
- } catch (error) {
416
- logger.error("[NatsEventConsumer] Failed to subscribe", {
417
- subject: options.subject,
418
- error: error instanceof Error ? error.message : "Unknown error"
419
- });
420
- throw error;
421
- }
422
- }
423
- /**
424
- * Subscribe to multiple subjects
425
- */
426
- async subscribeMultiple(subjects, handler, options) {
427
- const subscriptions = [];
428
- for (const subject of subjects) {
429
- const subscription = await this.subscribe({
430
- subject,
431
- handler,
432
- options
433
- });
434
- subscriptions.push(subscription);
435
- }
436
- return subscriptions;
437
- }
438
- /**
439
- * Pull messages manually
440
- */
441
- async pull(options) {
442
- const js = this.connectionManager.getJetStream();
443
- try {
444
- const consumer = await js.consumers.get(this.config.stream, this.config.consumer);
445
- const messages = await consumer.fetch({
446
- max_messages: options.batch || 10,
447
- expires: options.timeout || 3e4
448
- });
449
- const events = [];
450
- for await (const msg of messages) {
451
- const event = this.wrapMessage(msg);
452
- events.push(event);
453
- }
454
- return events;
455
- } catch (error) {
456
- logger.error("[NatsEventConsumer] Failed to pull messages", {
457
- subject: options.subject,
458
- error: error instanceof Error ? error.message : "Unknown error"
459
- });
460
- throw error;
461
- }
462
- }
463
- /**
464
- * Unsubscribe from all active subscriptions
465
- */
466
- async unsubscribeAll() {
467
- const unsubscribePromises = Array.from(this.subscriptions.values()).map(async (subscription) => subscription.unsubscribe());
468
- await Promise.all(unsubscribePromises);
469
- this.subscriptions.clear();
470
- logger.info("[NatsEventConsumer] All subscriptions unsubscribed");
471
- }
472
- /**
473
- * Get all active subscriptions
474
- */
475
- getSubscriptions() {
476
- return Array.from(this.subscriptions.values());
477
- }
478
- /**
479
- * Process pending messages in dead letter queue
480
- */
481
- async processDLQ(_handler) {
482
- await Promise.resolve();
483
- logger.warn("[NatsEventConsumer] DLQ processing not yet implemented");
484
- }
485
- /**
486
- * List subjects for the configured stream
487
- */
488
- async listSubjects(streamName) {
489
- const jsm = this.connectionManager.getJetStreamManager();
490
- const info = await jsm.streams.info(streamName || this.config.stream);
491
- return info.config.subjects || [];
492
- }
493
- /**
494
- * Consume messages from consumer
495
- */
496
- async consumeMessages(consumer, subscription, handler, maxConcurrent, stopRequested) {
497
- try {
498
- const messages = await consumer.consume({
499
- max_messages: maxConcurrent,
500
- expires: 3e4
501
- });
502
- for await (const msg of messages) {
503
- if (stopRequested()) {
504
- break;
505
- }
506
- subscription.incrementReceived();
507
- try {
508
- const event = this.wrapMessage(msg);
509
- await runWithConsumerSpan(msg.subject, msg.headers, async () => handler(event));
510
- subscription.incrementProcessed();
511
- } catch (error) {
512
- subscription.incrementFailed();
513
- logger.error("[NatsEventConsumer] Error processing message", {
514
- subject: msg.subject,
515
- error: error instanceof Error ? error.message : "Unknown error"
516
- });
517
- msg.nak();
518
- }
519
- }
520
- } catch (error) {
521
- logger.error("[NatsEventConsumer] Error consuming messages", {
522
- error: error instanceof Error ? error.message : "Unknown error"
523
- });
524
- }
525
- }
526
- /**
527
- * Wrap NATS message in AcknowledgeableEvent
528
- */
529
- wrapMessage(msg) {
530
- const eventMessage = JSON.parse(msg.data.toString());
531
- return {
532
- ...eventMessage,
533
- sequence: msg.seq,
534
- ack: /* @__PURE__ */ __name(async () => {
535
- await Promise.resolve();
536
- msg.ack();
537
- }, "ack"),
538
- nak: /* @__PURE__ */ __name(async (delay) => {
539
- await Promise.resolve();
540
- if (delay) {
541
- msg.nak(delay);
542
- } else {
543
- msg.nak();
544
- }
545
- }, "nak"),
546
- term: /* @__PURE__ */ __name(async () => {
547
- await Promise.resolve();
548
- msg.term();
549
- }, "term"),
550
- isRedelivered: /* @__PURE__ */ __name(() => {
551
- return msg.redelivered;
552
- }, "isRedelivered"),
553
- getDeliveryAttempt: /* @__PURE__ */ __name(() => {
554
- return msg.info.deliveryCount;
555
- }, "getDeliveryAttempt")
556
- };
557
- }
558
- /**
559
- * Map retention policy string to NATS enum
560
- */
561
- mapRetentionPolicy(policy) {
562
- switch (policy?.toLowerCase()) {
563
- case "limits":
564
- return RetentionPolicy.Limits;
565
- case "interest":
566
- return RetentionPolicy.Interest;
567
- case "workqueue":
568
- default:
569
- return RetentionPolicy.Workqueue;
570
- }
571
- }
572
- /**
573
- * Map storage type string to NATS enum
574
- */
575
- mapStorageType(storage) {
576
- switch (storage?.toLowerCase()) {
577
- case "memory":
578
- return StorageType.Memory;
579
- case "file":
580
- default:
581
- return StorageType.File;
582
- }
583
- }
584
- /**
585
- * Map ack policy string to NATS enum
586
- */
587
- mapAckPolicy(policy) {
588
- switch (policy?.toLowerCase()) {
589
- case "none":
590
- return AckPolicy.None;
591
- case "all":
592
- return AckPolicy.All;
593
- case "explicit":
594
- default:
595
- return AckPolicy.Explicit;
596
- }
597
- }
598
- /**
599
- * Map deliver policy string to NATS enum
600
- */
601
- mapDeliverPolicy(policy) {
602
- switch (policy?.toLowerCase()) {
603
- case "new":
604
- return DeliverPolicy.New;
605
- case "last":
606
- return DeliverPolicy.Last;
607
- case "lastpersubject":
608
- return DeliverPolicy.LastPerSubject;
609
- case "all":
610
- default:
611
- return DeliverPolicy.All;
612
- }
613
- }
614
- };
615
- var DEFAULT_STREAM_MAX_BYTES2 = 10 * 1024 * 1024;
616
- var NatsEventPublisher = class {
617
- static {
618
- __name(this, "NatsEventPublisher");
619
- }
620
- config;
621
- connectionManager;
622
- publishCount = 0;
623
- lastPublishTime = null;
624
- constructor(config) {
625
- this.config = config;
626
- this.connectionManager = new NatsConnectionManager(config);
627
- }
628
- /**
629
- * Connect to NATS server
630
- */
631
- async connect() {
632
- await this.connectionManager.connect();
633
- }
634
- /**
635
- * Disconnect from NATS server
636
- */
637
- async disconnect() {
638
- await this.connectionManager.disconnect();
639
- }
640
- /**
641
- * Check if connected
642
- */
643
- isConnected() {
644
- return this.connectionManager.isConnected();
645
- }
646
- /**
647
- * Health check
648
- */
649
- async healthCheck() {
650
- await Promise.resolve();
651
- const isConnected = this.isConnected();
652
- return {
653
- status: isConnected ? "healthy" : "unhealthy",
654
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
655
- details: {
656
- connected: isConnected,
657
- type: "nats",
658
- url: this.config.url
659
- }
660
- };
661
- }
662
- /**
663
- * Get queue statistics
664
- */
665
- async getStatistics() {
666
- const jsm = this.connectionManager.getJetStreamManager();
667
- try {
668
- const streams = await jsm.streams.list().next();
669
- const streamCount = streams.length;
670
- return {
671
- messagesPublished: this.publishCount,
672
- messagesConsumed: 0,
673
- messagesFailed: 0,
674
- activeConsumers: 0,
675
- activePublishers: 1,
676
- queueSize: 0,
677
- lastActivity: this.lastPublishTime?.toISOString() || null,
678
- details: {
679
- streamCount,
680
- type: "nats"
681
- }
682
- };
683
- } catch (error) {
684
- logger.error("[NatsEventPublisher] Failed to get statistics", {
685
- error: error instanceof Error ? error.message : "Unknown error"
686
- });
687
- throw error;
688
- }
689
- }
690
- /**
691
- * Ensure a stream exists
692
- */
693
- async ensureStream(config) {
694
- const jsm = this.connectionManager.getJetStreamManager();
695
- try {
696
- try {
697
- await jsm.streams.info(config.name);
698
- logger.debug("[NatsEventPublisher] Stream already exists", {
699
- stream: config.name
700
- });
701
- return;
702
- } catch {
703
- }
704
- const streamConfig = {
705
- name: config.name,
706
- subjects: config.subjects,
707
- retention: this.mapRetentionPolicy(config.retention),
708
- storage: this.mapStorageType(config.storage),
709
- max_consumers: config.maxConsumers,
710
- max_msgs: config.maxMsgs,
711
- max_bytes: config.maxBytes ?? DEFAULT_STREAM_MAX_BYTES2,
712
- max_age: config.maxAge,
713
- duplicate_window: config.duplicateWindow
714
- };
715
- await jsm.streams.add(streamConfig);
716
- logger.info("[NatsEventPublisher] Stream created successfully", {
717
- stream: config.name,
718
- subjects: config.subjects
719
- });
720
- } catch (error) {
721
- logger.error("[NatsEventPublisher] Failed to ensure stream", {
722
- stream: config.name,
723
- error: error instanceof Error ? error.message : "Unknown error"
724
- });
725
- throw error;
726
- }
727
- }
728
- /**
729
- * Derive stream subject pattern from subscription subject
730
- * Examples:
731
- * - "channel.conversation.message" → ["channel.>"]
732
- * - "wspace.tags.created" → ["wspace.>"]
733
- * - "global.auth.login" → ["global.>"]
734
- */
735
- deriveStreamSubjects(subject) {
736
- const firstSegment = subject.split(".")[0];
737
- if (firstSegment) {
738
- return [
739
- `${firstSegment}.>`
740
- ];
741
- }
742
- return [
743
- `${subject.replace(/\.[^.]+$/, ".>")}`
744
- ];
745
- }
746
- /**
747
- * Derive stream name from subject
748
- * Examples:
749
- * - "channel.conversation.message" → "CHANNEL_EVENTS"
750
- * - "wspace.tags.created" → "WSPACE_EVENTS"
751
- * - "global.auth.login" → "GLOBAL_EVENTS"
752
- */
753
- deriveStreamName(subject) {
754
- const firstSegment = subject.split(".")[0];
755
- if (firstSegment) {
756
- return `${firstSegment.toUpperCase()}_EVENTS`;
757
- }
758
- return "EVENTS";
759
- }
760
- /**
761
- * Publish an event to a subject
762
- */
763
- async publish(options) {
764
- const js = this.connectionManager.getJetStream();
765
- try {
766
- const streamName = options.options?.stream || this.deriveStreamName(options.subject);
767
- const streamSubjects = options.options?.streamSubjects || this.deriveStreamSubjects(options.subject);
768
- await this.ensureStream({
769
- name: streamName,
770
- subjects: streamSubjects,
771
- retention: options.options?.retention || "limits",
772
- storage: options.options?.storage || "file"
773
- });
774
- const message = {
775
- id: options.options?.messageId || this.generateMessageId(),
776
- subject: options.subject,
777
- data: options.data,
778
- metadata: {
779
- source: options.metadata?.source || "workspaces-backend",
780
- correlationId: options.metadata?.correlationId || this.generateCorrelationId(),
781
- userId: options.metadata?.userId,
782
- workspaceId: options.metadata?.workspaceId,
783
- priority: options.options?.priority || this.config.defaultPriority || "normal",
784
- ...options.metadata
785
- },
786
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
787
- };
788
- const hdrs = headers();
789
- hdrs.set("message-id", message.id);
790
- hdrs.set("correlation-id", message.metadata.correlationId);
791
- if (message.metadata.source) {
792
- hdrs.set("source", message.metadata.source);
793
- }
794
- if (message.metadata["priority"] && typeof message.metadata["priority"] === "string") {
795
- hdrs.set("priority", message.metadata["priority"]);
796
- }
797
- if (message.metadata.userId) {
798
- hdrs.set("user-id", message.metadata.userId);
799
- }
800
- if (message.metadata.workspaceId) {
801
- hdrs.set("workspace-id", message.metadata.workspaceId);
802
- }
803
- await injectW3CTraceContext(hdrs);
804
- const publishOpts = {
805
- msgID: this.config.enableDeduplication ? message.id : void 0,
806
- headers: hdrs
807
- };
808
- if (options.options?.ttl) {
809
- logger.warn("[NatsEventPublisher] Per-message TTL not supported in NATS", {
810
- subject: options.subject,
811
- ttl: options.options.ttl
812
- });
813
- }
814
- if (options.options?.delay) {
815
- logger.warn("[NatsEventPublisher] Message delay not supported in NATS", {
816
- subject: options.subject,
817
- delay: options.options.delay
818
- });
819
- }
820
- const ack = await js.publish(options.subject, JSON.stringify(message), publishOpts);
821
- this.publishCount++;
822
- this.lastPublishTime = /* @__PURE__ */ new Date();
823
- logger.debug("[NatsEventPublisher] Event published", {
824
- subject: options.subject,
825
- messageId: message.id,
826
- sequence: ack.seq
827
- });
828
- return ack.seq;
829
- } catch (error) {
830
- logger.error("[NatsEventPublisher] Failed to publish event", {
831
- subject: options.subject,
832
- error: error instanceof Error ? error.message : "Unknown error"
833
- });
834
- throw error;
835
- }
836
- }
837
- /**
838
- * Publish multiple events in a batch
839
- */
840
- async publishBatch(events) {
841
- const results = [];
842
- for (const event of events) {
843
- const seq = await this.publish(event);
844
- results.push(seq);
845
- }
846
- return results;
847
- }
848
- /**
849
- * Publish an event and wait for acknowledgment
850
- * Note: This is not natively supported by NATS JetStream
851
- * Would require implementing request-reply pattern
852
- */
853
- async publishWithAck(options) {
854
- const nc = this.connectionManager.getNatsConnection();
855
- try {
856
- const message = {
857
- id: this.generateMessageId(),
858
- subject: options.subject,
859
- data: options.data,
860
- metadata: {
861
- source: options.metadata?.source || "workspaces-backend",
862
- correlationId: options.metadata?.correlationId || this.generateCorrelationId(),
863
- userId: options.metadata?.userId,
864
- workspaceId: options.metadata?.workspaceId,
865
- ...options.metadata
866
- },
867
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
868
- };
869
- const response = await nc.request(options.subject, JSON.stringify(message), {
870
- timeout: options.timeout || 3e4
871
- });
872
- const result = JSON.parse(response.data.toString());
873
- logger.debug("[NatsEventPublisher] Event published with ack", {
874
- subject: options.subject,
875
- messageId: message.id
876
- });
877
- return result;
878
- } catch (error) {
879
- logger.error("[NatsEventPublisher] Failed to publish event with ack", {
880
- subject: options.subject,
881
- error: error instanceof Error ? error.message : "Unknown error"
882
- });
883
- throw error;
884
- }
885
- }
886
- /**
887
- * Map retention policy string to NATS enum
888
- */
889
- mapRetentionPolicy(policy) {
890
- switch (policy?.toLowerCase()) {
891
- case "limits":
892
- return RetentionPolicy.Limits;
893
- case "interest":
894
- return RetentionPolicy.Interest;
895
- case "workqueue":
896
- default:
897
- return RetentionPolicy.Workqueue;
898
- }
899
- }
900
- /**
901
- * Map storage type string to NATS enum
902
- */
903
- mapStorageType(storage) {
904
- switch (storage?.toLowerCase()) {
905
- case "memory":
906
- return StorageType.Memory;
907
- case "file":
908
- default:
909
- return StorageType.File;
910
- }
911
- }
912
- /**
913
- * Generate unique message ID
914
- */
915
- generateMessageId() {
916
- return `msg_${Date.now()}_${crypto.randomUUID().substring(0, 13)}`;
917
- }
918
- /**
919
- * Generate correlation ID
920
- */
921
- generateCorrelationId() {
922
- return `corr_${Date.now()}_${crypto.randomUUID().substring(0, 13)}`;
923
- }
924
- };
925
-
926
- // src/event-queue/implementations/redis-streams/trace-context.ts
927
- var otelApiPromise2 = null;
928
- async function loadOtelApi2() {
929
- if (otelApiPromise2) return otelApiPromise2;
930
- otelApiPromise2 = (async () => {
931
- try {
932
- const mod = await import('./esm-M2M7HGV4.js');
933
- return mod;
934
- } catch {
935
- logger.debug("[redis-streams/trace-context] @opentelemetry/api not available; tracing disabled");
936
- return null;
937
- }
938
- })();
939
- return otelApiPromise2;
940
- }
941
- __name(loadOtelApi2, "loadOtelApi");
942
- var TRACE_KEYS = [
943
- "traceparent",
944
- "tracestate",
945
- "baggage"
946
- ];
947
- async function injectTraceFields() {
948
- const api = await loadOtelApi2();
949
- if (!api) return {};
950
- const carrier = {};
951
- try {
952
- api.propagation.inject(api.context.active(), carrier, {
953
- set(c, k, v) {
954
- c[k] = v;
955
- }
956
- });
957
- } catch (err) {
958
- logger.debug("[redis-streams/trace-context] inject failed", {
959
- error: err instanceof Error ? err.message : String(err)
960
- });
961
- }
962
- return carrier;
963
- }
964
- __name(injectTraceFields, "injectTraceFields");
965
- async function extractTraceContext(fields) {
966
- const api = await loadOtelApi2();
967
- if (!api) return void 0;
968
- const carrier = {};
969
- for (const key of TRACE_KEYS) {
970
- const value = fields[key];
971
- if (value) carrier[key] = value;
972
- }
973
- try {
974
- return api.propagation.extract(api.context.active(), carrier, {
975
- get(c, k) {
976
- return c[k];
977
- },
978
- keys(c) {
979
- return Object.keys(c);
980
- }
981
- });
982
- } catch {
983
- return void 0;
984
- }
985
- }
986
- __name(extractTraceContext, "extractTraceContext");
987
- async function runWithConsumerSpan2(subject, fields, handler) {
988
- const api = await loadOtelApi2();
989
- if (!api) return handler();
990
- try {
991
- const parentCtx = await extractTraceContext(fields);
992
- const tracer = api.trace.getTracer("@burdenoff/be-sdk/redis-streams");
993
- return await new Promise((resolve, reject) => {
994
- tracer.startActiveSpan(`redis-streams.consume ${subject}`, {
995
- kind: 5,
996
- attributes: {
997
- "messaging.system": "redis",
998
- "messaging.destination.name": subject
999
- }
1000
- }, parentCtx, async (span) => {
1001
- try {
1002
- const result = await handler();
1003
- span.setStatus({
1004
- code: 1
1005
- });
1006
- span.end();
1007
- resolve(result);
1008
- } catch (err) {
1009
- span.recordException(err);
1010
- span.setStatus({
1011
- code: 2,
1012
- message: err instanceof Error ? err.message : String(err)
1013
- });
1014
- span.end();
1015
- reject(err);
1016
- }
1017
- });
1018
- });
1019
- } catch {
1020
- return handler();
1021
- }
1022
- }
1023
- __name(runWithConsumerSpan2, "runWithConsumerSpan");
1024
-
1025
- // src/event-queue/implementations/redis-streams/RedisStreamsEventConsumer.ts
1026
- var DEFAULT_BLOCK_MS = 5e3;
1027
- var DEFAULT_BATCH = 10;
1028
- var REGISTRY_REFRESH_MS = 1e4;
1029
- var DEFAULT_ACK_WAIT_MS = 3e4;
1030
- var DEFAULT_MAX_DELIVER = 3;
1031
- var SWEEP_INTERVAL_MS = 15e3;
1032
- var DELAYQ_INTERVAL_MS = 1e3;
1033
- var RedisStreamsSubscription = class RedisStreamsSubscription2 {
1034
- static {
1035
- __name(this, "RedisStreamsSubscription");
1036
- }
1037
- subject;
1038
- unsubscribeFn;
1039
- id = randomUUID();
1040
- active = true;
1041
- receivedCount = 0;
1042
- processedCount = 0;
1043
- failedCount = 0;
1044
- lastActivity = (/* @__PURE__ */ new Date()).toISOString();
1045
- constructor(subject, unsubscribeFn) {
1046
- this.subject = subject;
1047
- this.unsubscribeFn = unsubscribeFn;
1048
- }
1049
- async unsubscribe() {
1050
- if (!this.active) return;
1051
- this.active = false;
1052
- await this.unsubscribeFn();
1053
- }
1054
- isActive() {
1055
- return this.active;
1056
- }
1057
- getStats() {
1058
- return {
1059
- messagesReceived: this.receivedCount,
1060
- messagesProcessed: this.processedCount,
1061
- messagesFailed: this.failedCount,
1062
- lastActivity: this.lastActivity
1063
- };
1064
- }
1065
- recordReceived() {
1066
- this.receivedCount++;
1067
- this.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
1068
- }
1069
- recordProcessed() {
1070
- this.processedCount++;
1071
- this.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
1072
- }
1073
- recordFailed() {
1074
- this.failedCount++;
1075
- this.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
1076
- }
1077
- };
1078
- var RedisStreamsEventConsumer = class {
1079
- static {
1080
- __name(this, "RedisStreamsEventConsumer");
1081
- }
1082
- connection;
1083
- subscriptions = [];
1084
- subscriptionLoops = /* @__PURE__ */ new Set();
1085
- keyPrefix;
1086
- consumerName;
1087
- group;
1088
- maxDeliver;
1089
- ackWaitMs;
1090
- maxConcurrent;
1091
- consumedCount = 0;
1092
- failedCount = 0;
1093
- lastActivity = null;
1094
- stopped = false;
1095
- sweepTimer = null;
1096
- delayqTimer = null;
1097
- knownStreams = /* @__PURE__ */ new Map();
1098
- constructor(config) {
1099
- this.connection = new RedisStreamsConnection({
1100
- type: "redis-streams",
1101
- url: config.url ?? process.env["REDIS_URL"] ?? "redis://localhost:6379",
1102
- user: config.user,
1103
- password: config.password,
1104
- name: config.name,
1105
- connectionTimeout: config.connectionTimeout
1106
- });
1107
- this.keyPrefix = config.keyPrefix ?? process.env["REDIS_STREAMS_KEY_PREFIX"] ?? "boff:events";
1108
- this.group = config.consumer || config.name || "default-consumer";
1109
- this.consumerName = `${this.group}:${hostname()}:${process.pid}`;
1110
- this.maxDeliver = config.maxDeliver ?? DEFAULT_MAX_DELIVER;
1111
- this.ackWaitMs = config.ackWait ? Math.max(1e3, Math.round(config.ackWait / 1e6)) : DEFAULT_ACK_WAIT_MS;
1112
- this.maxConcurrent = config.maxConcurrent ?? 5;
1113
- }
1114
- async connect() {
1115
- await this.connection.connect();
1116
- if (!this.sweepTimer) {
1117
- const t = setInterval(() => {
1118
- void this.sweepPending().catch((err) => {
1119
- logger.debug("[RedisStreamsEventConsumer] sweep error", {
1120
- error: err instanceof Error ? err.message : String(err)
1121
- });
1122
- });
1123
- }, SWEEP_INTERVAL_MS);
1124
- t.unref?.();
1125
- this.sweepTimer = t;
1126
- }
1127
- if (!this.delayqTimer) {
1128
- const t = setInterval(() => {
1129
- void this.drainDelayQueues().catch(() => void 0);
1130
- }, DELAYQ_INTERVAL_MS);
1131
- t.unref?.();
1132
- this.delayqTimer = t;
1133
- }
1134
- }
1135
- async disconnect() {
1136
- this.stopped = true;
1137
- if (this.sweepTimer) clearInterval(this.sweepTimer);
1138
- if (this.delayqTimer) clearInterval(this.delayqTimer);
1139
- await this.unsubscribeAll();
1140
- await this.connection.disconnect();
1141
- }
1142
- isConnected() {
1143
- return this.connection.isConnected();
1144
- }
1145
- async healthCheck() {
1146
- try {
1147
- const t0 = Date.now();
1148
- const pong = await this.connection.ping();
1149
- return {
1150
- status: pong === "PONG" ? "healthy" : "degraded",
1151
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1152
- connected: this.isConnected(),
1153
- latencyMs: Date.now() - t0,
1154
- details: {
1155
- type: "redis-streams",
1156
- subscriptions: this.subscriptions.length
1157
- }
1158
- };
1159
- } catch (err) {
1160
- return {
1161
- status: "unhealthy",
1162
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1163
- connected: false,
1164
- details: {
1165
- type: "redis-streams"
1166
- },
1167
- error: err instanceof Error ? err.message : String(err)
1168
- };
1169
- }
1170
- }
1171
- async getStatistics() {
1172
- return Promise.resolve({
1173
- messagesConsumed: this.consumedCount,
1174
- messagesFailed: this.failedCount,
1175
- messagesPublished: 0,
1176
- activeConsumers: this.subscriptions.length,
1177
- lastActivity: this.lastActivity?.toISOString() ?? null,
1178
- details: {
1179
- type: "redis-streams",
1180
- group: this.group
1181
- }
1182
- });
1183
- }
1184
- async ensureStream(_config) {
1185
- return Promise.resolve();
1186
- }
1187
- async ensureConsumer(_config) {
1188
- return Promise.resolve();
1189
- }
1190
- async subscribe(opts) {
1191
- await this.connect();
1192
- const sub = new RedisStreamsSubscription(opts.subject, async () => {
1193
- this.subscriptions = this.subscriptions.filter((s) => s !== sub);
1194
- });
1195
- this.subscriptions.push(sub);
1196
- const startId = this.resolveStartId(opts.options?.deliverPolicy);
1197
- const wildcard = isWildcard(opts.subject);
1198
- const handlerFn = opts.handler;
1199
- if (!wildcard) {
1200
- const stream = streamKey(opts.subject, {
1201
- prefix: this.keyPrefix
1202
- });
1203
- await this.ensureGroup(stream, startId);
1204
- this.knownStreams.set(stream, opts.subject);
1205
- this.spawnLoop(sub, stream, opts.subject, handlerFn);
1206
- } else {
1207
- const boundary = boundaryOf(opts.subject);
1208
- const refresh = /* @__PURE__ */ __name(async () => {
1209
- const client = this.connection.getClient();
1210
- const subjects = await client.smembers(registryKey(boundary));
1211
- for (const s of subjects) {
1212
- if (!matchSubject(opts.subject, s)) continue;
1213
- const stream = streamKey(s, {
1214
- prefix: this.keyPrefix
1215
- });
1216
- if (this.knownStreams.has(stream)) continue;
1217
- await this.ensureGroup(stream, startId);
1218
- this.knownStreams.set(stream, s);
1219
- this.spawnLoop(sub, stream, s, handlerFn);
1220
- }
1221
- }, "refresh");
1222
- await refresh();
1223
- const t = setInterval(() => {
1224
- if (this.stopped || !sub.isActive()) {
1225
- clearInterval(t);
1226
- return;
1227
- }
1228
- void refresh().catch(() => void 0);
1229
- }, REGISTRY_REFRESH_MS);
1230
- t.unref?.();
1231
- }
1232
- return sub;
1233
- }
1234
- async subscribeMultiple(subjects, handler, options) {
1235
- const out = [];
1236
- for (const subject of subjects) {
1237
- out.push(await this.subscribe({
1238
- subject,
1239
- handler,
1240
- options
1241
- }));
1242
- }
1243
- return out;
1244
- }
1245
- async pull(opts) {
1246
- await this.connect();
1247
- const stream = streamKey(opts.subject, {
1248
- prefix: this.keyPrefix
1249
- });
1250
- await this.ensureGroup(stream, "$");
1251
- const client = this.connection.getClient();
1252
- const raw = await client.xreadgroup("GROUP", this.group, this.consumerName, "COUNT", opts.batch ?? DEFAULT_BATCH, "BLOCK", opts.timeout ?? DEFAULT_BLOCK_MS, "STREAMS", stream, ">");
1253
- if (!raw) return [];
1254
- const out = [];
1255
- for (const [streamName, entries] of raw) {
1256
- for (const [id, rawFields] of entries) {
1257
- const parsed = this.parseEntry(streamName, id, rawFields);
1258
- out.push(this.toAcknowledgeable(streamName, id, parsed));
1259
- }
1260
- }
1261
- return out;
1262
- }
1263
- async unsubscribeAll() {
1264
- for (const sub of [
1265
- ...this.subscriptions
1266
- ]) {
1267
- await sub.unsubscribe();
1268
- }
1269
- this.subscriptions = [];
1270
- this.subscriptionLoops.clear();
1271
- }
1272
- getSubscriptions() {
1273
- return [
1274
- ...this.subscriptions
1275
- ];
1276
- }
1277
- async processDLQ(handler) {
1278
- await this.connect();
1279
- const client = this.connection.getClient();
1280
- const dlqGroup = `${this.group}-dlq`;
1281
- for (const [stream] of this.knownStreams) {
1282
- const dlq = dlqKey(stream);
1283
- try {
1284
- await client.xgroup("CREATE", dlq, dlqGroup, "0", "MKSTREAM");
1285
- } catch {
1286
- }
1287
- const res = await client.xreadgroup("GROUP", dlqGroup, this.consumerName, "COUNT", 50, "BLOCK", 100, "STREAMS", dlq, ">");
1288
- if (!res) continue;
1289
- for (const [, entries] of res) {
1290
- for (const [id, rawFields] of entries) {
1291
- const parsed = this.parseEntry(dlq, id, rawFields);
1292
- const evt = this.toAcknowledgeable(dlq, id, parsed, dlqGroup);
1293
- try {
1294
- await handler(evt);
1295
- } catch (err) {
1296
- logger.error("[RedisStreamsEventConsumer] DLQ handler error", {
1297
- error: err instanceof Error ? err.message : String(err)
1298
- });
1299
- }
1300
- }
1301
- }
1302
- }
1303
- }
1304
- async listSubjects(_stream) {
1305
- await this.connect();
1306
- const client = this.connection.getClient();
1307
- const seen = /* @__PURE__ */ new Set();
1308
- for (const subject of this.knownStreams.values()) {
1309
- const members = await client.smembers(registryKey(boundaryOf(subject)));
1310
- for (const m of members) seen.add(m);
1311
- }
1312
- return [
1313
- ...seen
1314
- ];
1315
- }
1316
- // ---- internals ----
1317
- resolveStartId(policy) {
1318
- switch (policy) {
1319
- case "all":
1320
- return "0";
1321
- case "new":
1322
- return "$";
1323
- case "last":
1324
- return "$";
1325
- default:
1326
- return "$";
1327
- }
1328
- }
1329
- async ensureGroup(stream, startId) {
1330
- const client = this.connection.getClient();
1331
- try {
1332
- await client.xgroup("CREATE", stream, this.group, startId, "MKSTREAM");
1333
- logger.debug("[RedisStreamsEventConsumer] group created", {
1334
- stream,
1335
- group: this.group,
1336
- startId
1337
- });
1338
- } catch (err) {
1339
- const msg = err instanceof Error ? err.message : String(err);
1340
- if (!msg.includes("BUSYGROUP")) {
1341
- throw err;
1342
- }
1343
- }
1344
- }
1345
- spawnLoop(sub, stream, subject, handler) {
1346
- const loop = /* @__PURE__ */ __name(async () => {
1347
- const client = await this.connection.makeBlockingClient();
1348
- try {
1349
- while (!this.stopped && sub.isActive()) {
1350
- let raw = null;
1351
- try {
1352
- raw = await client.xreadgroup("GROUP", this.group, this.consumerName, "COUNT", this.maxConcurrent, "BLOCK", DEFAULT_BLOCK_MS, "STREAMS", stream, ">");
1353
- } catch (err) {
1354
- const msg = err instanceof Error ? err.message : String(err);
1355
- if (msg.includes("NOGROUP")) {
1356
- await this.ensureGroup(stream, "$");
1357
- continue;
1358
- }
1359
- logger.warn("[RedisStreamsEventConsumer] read error", {
1360
- stream,
1361
- error: msg
1362
- });
1363
- await new Promise((res) => setTimeout(res, 1e3));
1364
- continue;
1365
- }
1366
- if (!raw) continue;
1367
- for (const [, entries] of raw) {
1368
- for (const [id, rawFields] of entries) {
1369
- sub.recordReceived();
1370
- this.consumedCount++;
1371
- this.lastActivity = /* @__PURE__ */ new Date();
1372
- const parsed = this.parseEntry(stream, id, rawFields);
1373
- const evt = this.toAcknowledgeable(stream, id, parsed);
1374
- try {
1375
- await runWithConsumerSpan2(subject, parsed.fields, () => handler(evt));
1376
- sub.recordProcessed();
1377
- } catch (err) {
1378
- sub.recordFailed();
1379
- this.failedCount++;
1380
- logger.error("[RedisStreamsEventConsumer] handler error", {
1381
- subject,
1382
- id,
1383
- error: err instanceof Error ? err.message : String(err)
1384
- });
1385
- try {
1386
- await evt.nak();
1387
- } catch {
1388
- }
1389
- }
1390
- }
1391
- }
1392
- }
1393
- } finally {
1394
- try {
1395
- client.disconnect();
1396
- } catch {
1397
- }
1398
- }
1399
- }, "loop");
1400
- void loop().catch((err) => {
1401
- logger.error("[RedisStreamsEventConsumer] loop crashed", {
1402
- stream,
1403
- error: err instanceof Error ? err.message : String(err)
1404
- });
1405
- });
1406
- }
1407
- parseEntry(stream, id, rawFields) {
1408
- const fields = {};
1409
- for (let i = 0; i + 1 < rawFields.length; i += 2) {
1410
- const key = rawFields[i];
1411
- const val = rawFields[i + 1];
1412
- if (key === void 0 || val === void 0) continue;
1413
- fields[key] = val;
1414
- }
1415
- let data;
1416
- try {
1417
- data = JSON.parse(fields["payload"] ?? "null");
1418
- } catch {
1419
- data = fields["payload"];
1420
- }
1421
- let metadata;
1422
- try {
1423
- metadata = JSON.parse(fields["metadata"] ?? "{}");
1424
- } catch {
1425
- metadata = {
1426
- correlationId: fields["correlation-id"] ?? ""
1427
- };
1428
- }
1429
- if (!metadata.correlationId) metadata.correlationId = fields["correlation-id"] ?? "";
1430
- return {
1431
- id,
1432
- stream,
1433
- subject: fields["subject"] ?? "",
1434
- data,
1435
- metadata,
1436
- timestamp: fields["timestamp"] ?? (/* @__PURE__ */ new Date()).toISOString(),
1437
- fields,
1438
- deliveryCount: 1
1439
- };
1440
- }
1441
- toAcknowledgeable(stream, id, parsed, group = this.group) {
1442
- const connection = this.connection;
1443
- let acked = false;
1444
- return {
1445
- id,
1446
- subject: parsed.subject,
1447
- data: parsed.data,
1448
- metadata: parsed.metadata,
1449
- timestamp: parsed.timestamp,
1450
- async ack() {
1451
- if (acked) return;
1452
- acked = true;
1453
- const client = connection.getClient();
1454
- await client.xack(stream, group, id);
1455
- await client.xdel(stream, id).catch(() => void 0);
1456
- },
1457
- async nak(delay = 0) {
1458
- if (acked) return;
1459
- acked = true;
1460
- const client = connection.getClient();
1461
- if (delay > 0) {
1462
- const score = Date.now() + delay;
1463
- const payload = JSON.stringify(parsed.fields);
1464
- await client.zadd(delayQueueKey(stream), score, `${id}|${payload}`);
1465
- await client.xack(stream, group, id);
1466
- await client.xdel(stream, id).catch(() => void 0);
1467
- }
1468
- },
1469
- async term() {
1470
- if (acked) return;
1471
- acked = true;
1472
- const client = connection.getClient();
1473
- const dlq = dlqKey(stream);
1474
- const flat = [];
1475
- for (const [k, v] of Object.entries(parsed.fields)) flat.push(k, v);
1476
- await client.xadd(dlq, "MAXLEN", "~", 1e4, "*", ...flat);
1477
- await client.xack(stream, group, id);
1478
- await client.xdel(stream, id).catch(() => void 0);
1479
- },
1480
- isRedelivered() {
1481
- return parsed.deliveryCount > 1;
1482
- },
1483
- getDeliveryAttempt() {
1484
- return parsed.deliveryCount;
1485
- }
1486
- };
1487
- }
1488
- async sweepPending() {
1489
- if (this.stopped || this.knownStreams.size === 0) return;
1490
- const client = this.connection.getClient();
1491
- for (const [stream] of this.knownStreams) {
1492
- try {
1493
- const claimed = await client.xautoclaim(stream, this.group, this.consumerName, this.ackWaitMs, "0", "COUNT", 50);
1494
- if (!claimed) continue;
1495
- const entries = claimed[1] ?? [];
1496
- for (const [id, rawFields] of entries) {
1497
- const pending = await client.xpending(stream, this.group, "IDLE", 0, "-", "+", 1, this.consumerName);
1498
- const deliveryCount = Array.isArray(pending) && pending[0] ? pending[0][3] : 1;
1499
- if (deliveryCount > this.maxDeliver) {
1500
- const flat = [];
1501
- for (let i = 0; i + 1 < rawFields.length; i += 2) {
1502
- flat.push(rawFields[i], rawFields[i + 1]);
1503
- }
1504
- flat.push("dlq-reason", "max-deliver-exceeded");
1505
- flat.push("dlq-deliveries", String(deliveryCount));
1506
- await client.xadd(dlqKey(stream), "MAXLEN", "~", 1e4, "*", ...flat);
1507
- await client.xack(stream, this.group, id);
1508
- await client.xdel(stream, id).catch(() => void 0);
1509
- logger.warn("[RedisStreamsEventConsumer] message moved to DLQ", {
1510
- stream,
1511
- id,
1512
- deliveryCount
1513
- });
1514
- }
1515
- }
1516
- } catch (err) {
1517
- const msg = err instanceof Error ? err.message : String(err);
1518
- if (msg.includes("NOGROUP")) continue;
1519
- logger.debug("[RedisStreamsEventConsumer] sweep iteration error", {
1520
- stream,
1521
- error: msg
1522
- });
1523
- }
1524
- }
1525
- }
1526
- async drainDelayQueues() {
1527
- if (this.stopped || this.knownStreams.size === 0) return;
1528
- const client = this.connection.getClient();
1529
- for (const [stream] of this.knownStreams) {
1530
- const lockKey = delayLockKey(stream);
1531
- const got = await client.set(lockKey, this.consumerName, "NX", "EX", 30).catch(() => null);
1532
- if (got !== "OK") continue;
1533
- try {
1534
- const due = await client.zrangebyscore(delayQueueKey(stream), 0, Date.now(), "LIMIT", 0, 50);
1535
- for (const member of due) {
1536
- const split = member.indexOf("|");
1537
- if (split < 0) continue;
1538
- const payload = member.slice(split + 1);
1539
- let fields = {};
1540
- try {
1541
- fields = JSON.parse(payload);
1542
- } catch {
1543
- continue;
1544
- }
1545
- const flat = [];
1546
- for (const [k, v] of Object.entries(fields)) flat.push(k, v);
1547
- await client.xadd(stream, "MAXLEN", "~", 1e5, "*", ...flat);
1548
- await client.zrem(delayQueueKey(stream), member);
1549
- }
1550
- } finally {
1551
- await client.del(lockKey).catch(() => void 0);
1552
- }
1553
- }
1554
- }
1555
- };
1556
- var RedisStreamsEventPublisher = class {
1557
- static {
1558
- __name(this, "RedisStreamsEventPublisher");
1559
- }
1560
- config;
1561
- connection;
1562
- publishCount = 0;
1563
- lastPublishTime = null;
1564
- maxLen;
1565
- dedupTtl;
1566
- keyPrefix;
1567
- constructor(config) {
1568
- this.config = config;
1569
- this.connection = new RedisStreamsConnection(config);
1570
- this.maxLen = config.maxLen ?? parseInt(process.env["REDIS_STREAMS_MAXLEN"] ?? "100000", 10);
1571
- this.dedupTtl = config.dedupTtlSeconds ?? parseInt(process.env["REDIS_STREAMS_DEDUP_TTL"] ?? "120", 10);
1572
- this.keyPrefix = config.keyPrefix ?? process.env["REDIS_STREAMS_KEY_PREFIX"] ?? "boff:events";
1573
- }
1574
- async connect() {
1575
- await this.connection.connect();
1576
- }
1577
- async disconnect() {
1578
- await this.connection.disconnect();
1579
- }
1580
- isConnected() {
1581
- return this.connection.isConnected();
1582
- }
1583
- async healthCheck() {
1584
- try {
1585
- const t0 = Date.now();
1586
- const pong = await this.connection.ping();
1587
- return {
1588
- status: pong === "PONG" ? "healthy" : "degraded",
1589
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1590
- connected: this.isConnected(),
1591
- latencyMs: Date.now() - t0,
1592
- details: {
1593
- type: "redis-streams",
1594
- url: this.config.url
1595
- }
1596
- };
1597
- } catch (err) {
1598
- return {
1599
- status: "unhealthy",
1600
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1601
- connected: false,
1602
- details: {
1603
- type: "redis-streams"
1604
- },
1605
- error: err instanceof Error ? err.message : String(err)
1606
- };
1607
- }
1608
- }
1609
- async getStatistics() {
1610
- return {
1611
- messagesPublished: this.publishCount,
1612
- messagesConsumed: 0,
1613
- messagesFailed: 0,
1614
- activePublishers: 1,
1615
- activeConsumers: 0,
1616
- lastActivity: this.lastPublishTime?.toISOString() ?? null,
1617
- details: {
1618
- type: "redis-streams"
1619
- }
1620
- };
1621
- }
1622
- async ensureStream(_config) {
1623
- return Promise.resolve();
1624
- }
1625
- async publish(options) {
1626
- return this.publishInternal(options);
1627
- }
1628
- async publishInternal(opts) {
1629
- await this.connect();
1630
- const client = this.connection.getClient();
1631
- const stream = streamKey(opts.subject, {
1632
- prefix: this.keyPrefix
1633
- });
1634
- const msgId = opts.options?.messageId ?? randomUUID();
1635
- const correlationId = opts.metadata?.correlationId ?? randomUUID();
1636
- const enableDedup = this.config.enableDeduplication === true || opts.options?.messageId !== void 0;
1637
- if (enableDedup) {
1638
- const ok = await client.set(dedupKey(stream, msgId), "1", "NX", "EX", this.dedupTtl);
1639
- if (ok !== "OK") {
1640
- logger.debug("[RedisStreamsEventPublisher] dedup hit; skipping publish", {
1641
- subject: opts.subject,
1642
- msgId
1643
- });
1644
- return msgId;
1645
- }
1646
- }
1647
- const trace = await injectTraceFields();
1648
- const fields = {
1649
- "msg-id": msgId,
1650
- subject: opts.subject,
1651
- "correlation-id": correlationId,
1652
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1653
- priority: opts.options?.priority ?? this.config.defaultPriority ?? "normal",
1654
- source: opts.metadata?.source ?? this.config.name ?? "unknown",
1655
- payload: JSON.stringify(opts.data ?? null),
1656
- metadata: JSON.stringify(opts.metadata ?? {}),
1657
- ...trace
1658
- };
1659
- if (opts.metadata?.userId) fields["user-id"] = String(opts.metadata.userId);
1660
- if (opts.metadata?.workspaceId) fields["workspace-id"] = String(opts.metadata.workspaceId);
1661
- if (opts.metadata?.tenantId) fields["tenant-id"] = String(opts.metadata.tenantId);
1662
- const flat = [];
1663
- for (const [k, v] of Object.entries(fields)) {
1664
- flat.push(k, v);
1665
- }
1666
- const id = await client.xadd(stream, "MAXLEN", "~", this.maxLen, "*", ...flat);
1667
- void client.sadd(registryKey(boundaryOf(opts.subject)), opts.subject).catch(() => void 0);
1668
- this.publishCount++;
1669
- this.lastPublishTime = /* @__PURE__ */ new Date();
1670
- logger.debug("[RedisStreamsEventPublisher] published", {
1671
- subject: opts.subject,
1672
- stream,
1673
- id
1674
- });
1675
- return id;
1676
- }
1677
- async publishBatch(events) {
1678
- const out = [];
1679
- for (const e of events) {
1680
- out.push(await this.publishInternal(e));
1681
- }
1682
- return out;
1683
- }
1684
- /**
1685
- * Emulated request/response: writer XADDs onto its own subject, then
1686
- * blocks on a one-shot reply stream keyed by correlationId.
1687
- */
1688
- async publishWithAck(opts) {
1689
- await this.connect();
1690
- const client = this.connection.getClient();
1691
- const correlationId = opts.metadata?.correlationId ?? randomUUID();
1692
- const reply = replyKey(correlationId);
1693
- await this.publishInternal({
1694
- subject: opts.subject,
1695
- data: opts.data,
1696
- metadata: {
1697
- ...opts.metadata,
1698
- correlationId,
1699
- replyTo: reply
1700
- }
1701
- });
1702
- const timeoutMs = opts.timeout ?? 5e3;
1703
- const t0 = Date.now();
1704
- while (Date.now() - t0 < timeoutMs) {
1705
- const entries = await client.xrange(reply, "-", "+");
1706
- if (Array.isArray(entries) && entries.length > 0) {
1707
- const last = entries[entries.length - 1];
1708
- if (!last) break;
1709
- const rawFields = last[1];
1710
- const payloadIdx = rawFields.indexOf("payload");
1711
- const payload = payloadIdx >= 0 ? rawFields[payloadIdx + 1] : "{}";
1712
- await client.del(reply);
1713
- return JSON.parse(payload ?? "{}");
1714
- }
1715
- await new Promise((res) => setTimeout(res, 50));
1716
- }
1717
- await client.del(reply).catch(() => void 0);
1718
- throw new Error(`[RedisStreamsEventPublisher] publishWithAck timed out for subject=${opts.subject}`);
1719
- }
1720
- /** Internal helper used by the consumer's reply path. */
1721
- async sendReply(correlationId, data) {
1722
- await this.connect();
1723
- const client = this.connection.getClient();
1724
- const key = replyKey(correlationId);
1725
- await client.xadd(key, "*", "payload", JSON.stringify(data ?? null));
1726
- await client.expire(key, 60);
1727
- }
1728
- };
1729
-
1730
- // src/event-queue/factory/EventQueueFactory.ts
1731
- function resolveQueueType() {
1732
- const raw = (process.env["EVENT_QUEUE_TYPE"] ?? process.env["QUEUE_TYPE"] ?? "").toLowerCase();
1733
- if (raw === "redis-streams" || raw === "redis" || raw === "streams") return QueueType.REDIS_STREAMS;
1734
- if (raw === "nats") return QueueType.NATS;
1735
- if (!process.env["NATS_URL"] && !process.env["NATS_SERVERS"] && process.env["REDIS_URL"]) {
1736
- return QueueType.REDIS_STREAMS;
1737
- }
1738
- return QueueType.NATS;
1739
- }
1740
- __name(resolveQueueType, "resolveQueueType");
1741
- var EventQueueFactory = class _EventQueueFactory {
1742
- static {
1743
- __name(this, "EventQueueFactory");
1744
- }
1745
- /**
1746
- * Create an event publisher based on configuration
1747
- */
1748
- static createPublisher(config) {
1749
- logger.info("[EventQueueFactory] Creating event publisher", {
1750
- type: config.type,
1751
- url: config.url
1752
- });
1753
- if (config.type === QueueType.NATS) {
1754
- return new NatsEventPublisher(config);
1755
- }
1756
- if (config.type === QueueType.REDIS_STREAMS) {
1757
- return new RedisStreamsEventPublisher(config);
1758
- }
1759
- throw new Error(`Unsupported queue type: ${config.type}`);
1760
- }
1761
- /**
1762
- * Create an event consumer based on configuration
1763
- */
1764
- static createConsumer(config) {
1765
- logger.info("[EventQueueFactory] Creating event consumer", {
1766
- type: config.type,
1767
- url: config.url,
1768
- stream: config.stream,
1769
- consumer: config.consumer
1770
- });
1771
- if (config.type === QueueType.NATS) {
1772
- return new NatsEventConsumer(config);
1773
- }
1774
- if (config.type === QueueType.REDIS_STREAMS) {
1775
- return new RedisStreamsEventConsumer(config);
1776
- }
1777
- throw new Error(`Unsupported queue type: ${config.type}`);
1778
- }
1779
- /**
1780
- * Create a publisher from environment variables
1781
- */
1782
- static createPublisherFromEnv() {
1783
- const type = resolveQueueType();
1784
- if (type === QueueType.REDIS_STREAMS) {
1785
- return _EventQueueFactory.createPublisher({
1786
- type,
1787
- url: process.env["REDIS_URL"] ?? "redis://localhost:6379",
1788
- password: process.env["REDIS_PASSWORD"],
1789
- name: process.env["QUEUE_CLIENT_NAME"] ?? process.env["SERVICE_NAME"] ?? "be-sdk-publisher",
1790
- enableDeduplication: process.env["QUEUE_ENABLE_DEDUPLICATION"] === "true",
1791
- defaultPriority: process.env["QUEUE_DEFAULT_PRIORITY"] ?? "normal"
1792
- });
1793
- }
1794
- const config = {
1795
- type,
1796
- url: process.env["NATS_URL"] || "nats://localhost:4222",
1797
- user: process.env["NATS_USER"],
1798
- password: process.env["NATS_PASSWORD"],
1799
- token: process.env["NATS_TOKEN"],
1800
- creds: process.env["NATS_CREDS"],
1801
- credsFile: process.env["NATS_CREDS_FILE"],
1802
- name: process.env["QUEUE_CLIENT_NAME"] || "workspaces-backend-publisher",
1803
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
1804
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
1805
- enableDeduplication: process.env["QUEUE_ENABLE_DEDUPLICATION"] === "true",
1806
- defaultPriority: process.env["QUEUE_DEFAULT_PRIORITY"] || "normal",
1807
- defaultTTL: process.env["QUEUE_DEFAULT_TTL"] ? parseInt(process.env["QUEUE_DEFAULT_TTL"], 10) : void 0
1808
- };
1809
- return _EventQueueFactory.createPublisher(config);
1810
- }
1811
- /**
1812
- * Create a consumer from environment variables
1813
- */
1814
- static createConsumerFromEnv(stream, consumer) {
1815
- const type = resolveQueueType();
1816
- if (type === QueueType.REDIS_STREAMS) {
1817
- return _EventQueueFactory.createConsumer({
1818
- type,
1819
- url: process.env["REDIS_URL"] ?? "redis://localhost:6379",
1820
- password: process.env["REDIS_PASSWORD"],
1821
- name: process.env["QUEUE_CLIENT_NAME"] ?? process.env["SERVICE_NAME"] ?? consumer,
1822
- stream,
1823
- consumer,
1824
- maxConcurrent: process.env["QUEUE_MAX_CONCURRENT"] ? parseInt(process.env["QUEUE_MAX_CONCURRENT"], 10) : 5,
1825
- maxDeliver: process.env["QUEUE_MAX_DELIVER"] ? parseInt(process.env["QUEUE_MAX_DELIVER"], 10) : 3,
1826
- ackWait: process.env["QUEUE_ACK_WAIT"] ? parseInt(process.env["QUEUE_ACK_WAIT"], 10) * 1e9 : 3e10
1827
- });
1828
- }
1829
- const config = {
1830
- type,
1831
- url: process.env["NATS_URL"] || "nats://localhost:4222",
1832
- user: process.env["NATS_USER"],
1833
- password: process.env["NATS_PASSWORD"],
1834
- token: process.env["NATS_TOKEN"],
1835
- creds: process.env["NATS_CREDS"],
1836
- credsFile: process.env["NATS_CREDS_FILE"],
1837
- name: process.env["QUEUE_CLIENT_NAME"] || "workspaces-workers-consumer",
1838
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
1839
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
1840
- stream,
1841
- consumer,
1842
- maxConcurrent: process.env["QUEUE_MAX_CONCURRENT"] ? parseInt(process.env["QUEUE_MAX_CONCURRENT"], 10) : 5,
1843
- maxDeliver: process.env["QUEUE_MAX_DELIVER"] ? parseInt(process.env["QUEUE_MAX_DELIVER"], 10) : 3,
1844
- ackWait: process.env["QUEUE_ACK_WAIT"] ? parseInt(process.env["QUEUE_ACK_WAIT"], 10) * 1e9 : 3e10
1845
- };
1846
- return _EventQueueFactory.createConsumer(config);
1847
- }
1848
- // ========================================================================
1849
- // Layer-Aware Factory Methods
1850
- // ========================================================================
1851
- /**
1852
- * Create a publisher for a specific layer
1853
- *
1854
- * @param layer - Service layer ('wspace' or 'global')
1855
- * @param serviceName - Service name for identification
1856
- * @returns Publisher configured for the layer
1857
- *
1858
- * @example
1859
- * ```typescript
1860
- * const publisher = EventQueueFactory.createPublisherForLayer('wspace', 'wspace-tags-svc');
1861
- * await publisher.connect();
1862
- * await publisher.publish({ subject: 'wspace.tags.created', data: { id: '123' } });
1863
- * ```
1864
- */
1865
- static createPublisherForLayer(layer, serviceName) {
1866
- const envPrefix = layer.toUpperCase();
1867
- const defaults = DEFAULT_LAYER_RESOURCES[layer];
1868
- const type = resolveQueueType();
1869
- if (type === QueueType.REDIS_STREAMS) {
1870
- return _EventQueueFactory.createPublisher({
1871
- type,
1872
- url: process.env["REDIS_URL"] ?? "redis://localhost:6379",
1873
- password: process.env["REDIS_PASSWORD"],
1874
- name: serviceName,
1875
- enableDeduplication: process.env["QUEUE_ENABLE_DEDUPLICATION"] === "true",
1876
- defaultPriority: process.env["QUEUE_DEFAULT_PRIORITY"] || "normal"
1877
- });
1878
- }
1879
- const config = {
1880
- type,
1881
- url: process.env[`${envPrefix}_NATS_URL`] || process.env["NATS_URL"] || defaults.natsUrl,
1882
- user: process.env["NATS_USER"],
1883
- password: process.env["NATS_PASSWORD"],
1884
- token: process.env["NATS_TOKEN"],
1885
- creds: process.env["NATS_CREDS"],
1886
- credsFile: process.env["NATS_CREDS_FILE"],
1887
- name: serviceName,
1888
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
1889
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
1890
- enableDeduplication: process.env["QUEUE_ENABLE_DEDUPLICATION"] === "true",
1891
- defaultPriority: process.env["QUEUE_DEFAULT_PRIORITY"] || "normal",
1892
- defaultTTL: process.env["QUEUE_DEFAULT_TTL"] ? parseInt(process.env["QUEUE_DEFAULT_TTL"], 10) : void 0
1893
- };
1894
- logger.info("[EventQueueFactory] Creating layer publisher", {
1895
- layer,
1896
- serviceName,
1897
- url: config.url
1898
- });
1899
- return _EventQueueFactory.createPublisher(config);
1900
- }
1901
- /**
1902
- * Create a consumer for a specific layer
1903
- *
1904
- * @param layer - Service layer ('wspace' or 'global')
1905
- * @param serviceName - Service name for identification
1906
- * @param stream - NATS stream name
1907
- * @param consumer - Consumer name
1908
- * @returns Consumer configured for the layer
1909
- *
1910
- * @example
1911
- * ```typescript
1912
- * const consumer = EventQueueFactory.createConsumerForLayer(
1913
- * 'wspace', 'wspace-tags-svc', 'WSPACE_EVENTS', 'tags-consumer'
1914
- * );
1915
- * await consumer.connect();
1916
- * await consumer.consume(async (msg) => { console.log(msg); });
1917
- * ```
1918
- */
1919
- static createConsumerForLayer(layer, serviceName, stream, consumer) {
1920
- const envPrefix = layer.toUpperCase();
1921
- const defaults = DEFAULT_LAYER_RESOURCES[layer];
1922
- const type = resolveQueueType();
1923
- if (type === QueueType.REDIS_STREAMS) {
1924
- return _EventQueueFactory.createConsumer({
1925
- type,
1926
- url: process.env["REDIS_URL"] ?? "redis://localhost:6379",
1927
- password: process.env["REDIS_PASSWORD"],
1928
- name: serviceName,
1929
- stream,
1930
- consumer,
1931
- maxConcurrent: process.env["QUEUE_MAX_CONCURRENT"] ? parseInt(process.env["QUEUE_MAX_CONCURRENT"], 10) : 5,
1932
- maxDeliver: process.env["QUEUE_MAX_DELIVER"] ? parseInt(process.env["QUEUE_MAX_DELIVER"], 10) : 3,
1933
- ackWait: process.env["QUEUE_ACK_WAIT"] ? parseInt(process.env["QUEUE_ACK_WAIT"], 10) * 1e9 : 3e10
1934
- });
1935
- }
1936
- const config = {
1937
- type,
1938
- url: process.env[`${envPrefix}_NATS_URL`] || process.env["NATS_URL"] || defaults.natsUrl,
1939
- user: process.env["NATS_USER"],
1940
- password: process.env["NATS_PASSWORD"],
1941
- token: process.env["NATS_TOKEN"],
1942
- creds: process.env["NATS_CREDS"],
1943
- credsFile: process.env["NATS_CREDS_FILE"],
1944
- name: serviceName,
1945
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
1946
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
1947
- stream,
1948
- consumer,
1949
- maxConcurrent: process.env["QUEUE_MAX_CONCURRENT"] ? parseInt(process.env["QUEUE_MAX_CONCURRENT"], 10) : 5,
1950
- maxDeliver: process.env["QUEUE_MAX_DELIVER"] ? parseInt(process.env["QUEUE_MAX_DELIVER"], 10) : 3,
1951
- ackWait: process.env["QUEUE_ACK_WAIT"] ? parseInt(process.env["QUEUE_ACK_WAIT"], 10) * 1e9 : 3e10
1952
- };
1953
- logger.info("[EventQueueFactory] Creating layer consumer", {
1954
- layer,
1955
- serviceName,
1956
- stream,
1957
- consumer,
1958
- url: config.url
1959
- });
1960
- return _EventQueueFactory.createConsumer(config);
1961
- }
1962
- };
1963
-
1964
- export { EventQueueFactory, NatsEventConsumer, NatsEventPublisher, RedisStreamsEventConsumer, RedisStreamsEventPublisher };
1965
- //# sourceMappingURL=chunk-LRGXT37B.js.map
1966
- //# sourceMappingURL=chunk-LRGXT37B.js.map