@burdenoff/be-sdk 2026.512.103 → 2026.513.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 (37) hide show
  1. package/dist/EventQueueFactory-JQHBTQG3.js +8 -0
  2. package/dist/{EventQueueFactory-FNE7H66N.js.map → EventQueueFactory-JQHBTQG3.js.map} +1 -1
  3. package/dist/{chunk-WPGSKLAG.js → chunk-4YCH5SUK.js} +23 -5
  4. package/dist/chunk-4YCH5SUK.js.map +1 -0
  5. package/dist/chunk-BQRXB4CW.js +2183 -0
  6. package/dist/chunk-BQRXB4CW.js.map +1 -0
  7. package/dist/{chunk-DR5AQJT6.js → chunk-EODPHHEH.js} +3 -3
  8. package/dist/{chunk-DR5AQJT6.js.map → chunk-EODPHHEH.js.map} +1 -1
  9. package/dist/{chunk-S52PJKSW.js → chunk-I2PO7JBF.js} +3 -3
  10. package/dist/{chunk-S52PJKSW.js.map → chunk-I2PO7JBF.js.map} +1 -1
  11. package/dist/{chunk-LRL6GKXI.js → chunk-LIOZLSID.js} +3 -3
  12. package/dist/{chunk-LRL6GKXI.js.map → chunk-LIOZLSID.js.map} +1 -1
  13. package/dist/{chunk-SXIL2AJF.js → chunk-ORMCFQNW.js} +5 -5
  14. package/dist/{chunk-SXIL2AJF.js.map → chunk-ORMCFQNW.js.map} +1 -1
  15. package/dist/{chunk-VOFKF27Q.js → chunk-UVYDP6P6.js} +3 -2
  16. package/dist/chunk-UVYDP6P6.js.map +1 -0
  17. package/dist/config-QVYSAUMT.js +4 -0
  18. package/dist/{config-7U7J3QXQ.js.map → config-QVYSAUMT.js.map} +1 -1
  19. package/dist/esm-M2M7HGV4.js +1356 -0
  20. package/dist/esm-M2M7HGV4.js.map +1 -0
  21. package/dist/event-queue/index.d.ts +1 -1
  22. package/dist/event-queue/index.js +4 -4
  23. package/dist/graph/index.js +5 -5
  24. package/dist/{index-BF2uh_h9.d.ts → index-eUvoVdr7.d.ts} +158 -2
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.js +9 -9
  27. package/dist/init/index.js +3 -3
  28. package/dist/prisma/index.js +4 -4
  29. package/package.json +9 -1
  30. package/dist/EventQueueFactory-FNE7H66N.js +0 -8
  31. package/dist/chunk-KSO6QQVD.js +0 -1094
  32. package/dist/chunk-KSO6QQVD.js.map +0 -1
  33. package/dist/chunk-VOFKF27Q.js.map +0 -1
  34. package/dist/chunk-WPGSKLAG.js.map +0 -1
  35. package/dist/config-7U7J3QXQ.js +0 -4
  36. package/dist/esm-K6H7EIWK.js +0 -1450
  37. package/dist/esm-K6H7EIWK.js.map +0 -1
@@ -1,1094 +0,0 @@
1
- import { QueueType } from './chunk-VOFKF27Q.js';
2
- import { NatsConnectionManager } from './chunk-COSUYUCB.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
-
8
- // src/event-queue/implementations/nats/trace-context.ts
9
- var otelApiPromise = null;
10
- async function loadOtelApi() {
11
- if (otelApiPromise) {
12
- return otelApiPromise;
13
- }
14
- otelApiPromise = (async () => {
15
- try {
16
- const mod = await import('./esm-K6H7EIWK.js');
17
- return mod;
18
- } catch {
19
- logger.debug("[trace-context] @opentelemetry/api not available; NATS traces disabled");
20
- return null;
21
- }
22
- })();
23
- return otelApiPromise;
24
- }
25
- __name(loadOtelApi, "loadOtelApi");
26
- var setter = {
27
- set(carrier, key, value) {
28
- carrier[key] = value;
29
- }
30
- };
31
- var getter = {
32
- get(carrier, key) {
33
- return carrier[key];
34
- },
35
- keys(carrier) {
36
- return Object.keys(carrier);
37
- }
38
- };
39
- async function injectW3CTraceContext(hdrs) {
40
- const api = await loadOtelApi();
41
- if (!api) return;
42
- try {
43
- const carrier = {};
44
- api.propagation.inject(api.context.active(), carrier, setter);
45
- for (const [key, value] of Object.entries(carrier)) {
46
- if (value) hdrs.set(key, value);
47
- }
48
- } catch (err) {
49
- logger.debug("[trace-context] injection failed", {
50
- error: err instanceof Error ? err.message : String(err)
51
- });
52
- }
53
- }
54
- __name(injectW3CTraceContext, "injectW3CTraceContext");
55
- async function extractW3CTraceContext(hdrs) {
56
- const api = await loadOtelApi();
57
- if (!api || !hdrs) return void 0;
58
- try {
59
- const carrier = {};
60
- for (const key of [
61
- "traceparent",
62
- "tracestate",
63
- "baggage"
64
- ]) {
65
- const value = hdrs.get(key);
66
- if (value) carrier[key] = value;
67
- }
68
- return api.propagation.extract(api.context.active(), carrier, getter);
69
- } catch (err) {
70
- logger.debug("[trace-context] extraction failed", {
71
- error: err instanceof Error ? err.message : String(err)
72
- });
73
- return void 0;
74
- }
75
- }
76
- __name(extractW3CTraceContext, "extractW3CTraceContext");
77
- async function runWithConsumerSpan(subject, hdrs, handler) {
78
- const api = await loadOtelApi();
79
- if (!api) return handler();
80
- try {
81
- const parentCtx = await extractW3CTraceContext(hdrs);
82
- const tracer = api.trace.getTracer("@burdenoff/be-sdk/nats");
83
- return await new Promise((resolve, reject) => {
84
- tracer.startActiveSpan(`nats.consume ${subject}`, {
85
- kind: 5,
86
- attributes: {
87
- "messaging.system": "nats",
88
- "messaging.destination.name": subject
89
- }
90
- }, parentCtx, async (span) => {
91
- try {
92
- const result = await handler();
93
- span.setStatus({
94
- code: 1
95
- });
96
- span.end();
97
- resolve(result);
98
- } catch (err) {
99
- span.recordException(err);
100
- span.setStatus({
101
- code: 2,
102
- message: err instanceof Error ? err.message : String(err)
103
- });
104
- span.end();
105
- reject(err);
106
- }
107
- });
108
- });
109
- } catch (err) {
110
- logger.debug("[trace-context] consumer span failed to start; running without span", {
111
- error: err instanceof Error ? err.message : String(err)
112
- });
113
- return handler();
114
- }
115
- }
116
- __name(runWithConsumerSpan, "runWithConsumerSpan");
117
- var DEFAULT_STREAM_MAX_BYTES = 10 * 1024 * 1024;
118
- var NatsSubscription = class NatsSubscription2 {
119
- static {
120
- __name(this, "NatsSubscription");
121
- }
122
- id;
123
- subject;
124
- stopFn;
125
- active = true;
126
- stats = {
127
- messagesReceived: 0,
128
- messagesProcessed: 0,
129
- messagesFailed: 0,
130
- lastActivity: (/* @__PURE__ */ new Date()).toISOString()
131
- };
132
- constructor(id, subject, stopFn) {
133
- this.id = id;
134
- this.subject = subject;
135
- this.stopFn = stopFn;
136
- }
137
- async unsubscribe() {
138
- if (!this.active) {
139
- return Promise.resolve();
140
- }
141
- this.active = false;
142
- this.stopFn();
143
- return Promise.resolve();
144
- }
145
- isActive() {
146
- return this.active;
147
- }
148
- getStats() {
149
- return {
150
- messagesReceived: this.stats.messagesReceived,
151
- messagesProcessed: this.stats.messagesProcessed,
152
- messagesFailed: this.stats.messagesFailed,
153
- lastActivity: this.stats.lastActivity
154
- };
155
- }
156
- incrementReceived() {
157
- this.stats.messagesReceived++;
158
- this.stats.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
159
- }
160
- incrementProcessed() {
161
- this.stats.messagesProcessed++;
162
- this.stats.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
163
- }
164
- incrementFailed() {
165
- this.stats.messagesFailed++;
166
- this.stats.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
167
- }
168
- };
169
- var NatsEventConsumer = class {
170
- static {
171
- __name(this, "NatsEventConsumer");
172
- }
173
- config;
174
- connectionManager;
175
- subscriptions = /* @__PURE__ */ new Map();
176
- constructor(config) {
177
- this.config = config;
178
- const baseConfig = {
179
- type: config.type || "nats",
180
- url: config.url || "nats://localhost:4222",
181
- user: config.user,
182
- password: config.password,
183
- token: config.token,
184
- creds: config.creds,
185
- credsFile: config.credsFile,
186
- maxReconnectAttempts: config.maxReconnectAttempts,
187
- reconnectTimeWait: config.reconnectTimeWait,
188
- connectionTimeout: config.connectionTimeout,
189
- name: config.name
190
- };
191
- this.connectionManager = new NatsConnectionManager(baseConfig);
192
- }
193
- /**
194
- * Connect to NATS server
195
- */
196
- async connect() {
197
- await this.connectionManager.connect();
198
- }
199
- /**
200
- * Disconnect from NATS server
201
- */
202
- async disconnect() {
203
- await this.unsubscribeAll();
204
- await this.connectionManager.disconnect();
205
- }
206
- /**
207
- * Check if connected
208
- */
209
- isConnected() {
210
- return this.connectionManager.isConnected();
211
- }
212
- /**
213
- * Health check
214
- */
215
- async healthCheck() {
216
- await Promise.resolve();
217
- const isConnected = this.isConnected();
218
- return {
219
- status: isConnected ? "healthy" : "unhealthy",
220
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
221
- connected: isConnected,
222
- details: {
223
- type: "nats",
224
- url: this.config.url,
225
- activeSubscriptions: this.subscriptions.size
226
- }
227
- };
228
- }
229
- /**
230
- * Get queue statistics
231
- */
232
- async getStatistics() {
233
- await Promise.resolve();
234
- let totalReceived = 0;
235
- let totalProcessed = 0;
236
- let totalFailed = 0;
237
- let lastActivity = null;
238
- for (const subscription of this.subscriptions.values()) {
239
- const stats = subscription.getStats();
240
- totalReceived += stats.messagesReceived;
241
- totalProcessed += stats.messagesProcessed;
242
- totalFailed += stats.messagesFailed;
243
- if (stats.lastActivity && (!lastActivity || stats.lastActivity > lastActivity)) {
244
- lastActivity = stats.lastActivity;
245
- }
246
- }
247
- return {
248
- messagesPublished: 0,
249
- messagesConsumed: totalProcessed,
250
- messagesFailed: totalFailed,
251
- activeConsumers: this.subscriptions.size,
252
- activePublishers: 0,
253
- queueSize: 0,
254
- lastActivity,
255
- details: {
256
- totalReceived,
257
- type: "nats"
258
- }
259
- };
260
- }
261
- /**
262
- * Ensure a stream exists
263
- */
264
- async ensureStream(config) {
265
- const jsm = this.connectionManager.getJetStreamManager();
266
- try {
267
- try {
268
- await jsm.streams.info(config.name);
269
- logger.debug("[NatsEventConsumer] Stream already exists", {
270
- stream: config.name
271
- });
272
- return;
273
- } catch {
274
- }
275
- const streamConfig = {
276
- name: config.name,
277
- subjects: config.subjects,
278
- retention: this.mapRetentionPolicy(config.retention),
279
- storage: this.mapStorageType(config.storage),
280
- max_consumers: config.maxConsumers,
281
- max_msgs: config.maxMsgs,
282
- max_bytes: config.maxBytes ?? DEFAULT_STREAM_MAX_BYTES,
283
- max_age: config.maxAge,
284
- duplicate_window: config.duplicateWindow
285
- };
286
- await jsm.streams.add(streamConfig);
287
- logger.info("[NatsEventConsumer] Stream created successfully", {
288
- stream: config.name,
289
- subjects: config.subjects
290
- });
291
- } catch (error) {
292
- logger.error("[NatsEventConsumer] Failed to ensure stream", {
293
- stream: config.name,
294
- error: error instanceof Error ? error.message : "Unknown error"
295
- });
296
- throw error;
297
- }
298
- }
299
- /**
300
- * Ensure a consumer exists
301
- */
302
- async ensureConsumer(config) {
303
- const jsm = this.connectionManager.getJetStreamManager();
304
- try {
305
- await jsm.consumers.add(config.stream, {
306
- name: config.consumer,
307
- durable_name: config.consumer,
308
- filter_subject: config.filterSubject,
309
- ack_policy: this.mapAckPolicy(config.ackPolicy),
310
- deliver_policy: this.mapDeliverPolicy(config.deliverPolicy),
311
- max_deliver: config.maxDeliver || 3,
312
- ack_wait: config.ackWait || 3e10,
313
- max_ack_pending: config.maxAckPending || 100
314
- });
315
- logger.info("[NatsEventConsumer] Consumer created successfully", {
316
- stream: config.stream,
317
- consumer: config.consumer
318
- });
319
- } catch (error) {
320
- if (error instanceof Error && error.message?.includes("already exists")) {
321
- logger.debug("[NatsEventConsumer] Consumer already exists", {
322
- stream: config.stream,
323
- consumer: config.consumer
324
- });
325
- } else {
326
- logger.error("[NatsEventConsumer] Failed to ensure consumer", {
327
- stream: config.stream,
328
- consumer: config.consumer,
329
- error: error instanceof Error ? error.message : "Unknown error"
330
- });
331
- throw error;
332
- }
333
- }
334
- }
335
- /**
336
- * Derive stream subject pattern from subscription subject
337
- * Examples:
338
- * - "channel.conversation.message" → ["channel.>"]
339
- * - "wspace.tags.created" → ["wspace.>"]
340
- * - "global.auth.login" → ["global.>"]
341
- */
342
- deriveStreamSubjects(subject) {
343
- const firstSegment = subject.split(".")[0];
344
- if (firstSegment) {
345
- return [
346
- `${firstSegment}.>`
347
- ];
348
- }
349
- return [
350
- `${subject.replace(/\.[^.]+$/, ".>")}`
351
- ];
352
- }
353
- /**
354
- * Subscribe to a subject
355
- */
356
- async subscribe(options) {
357
- const js = this.connectionManager.getJetStream();
358
- const jsm = this.connectionManager.getJetStreamManager();
359
- try {
360
- let streamName = options.options?.stream || this.config.stream;
361
- const consumerName = options.options?.consumer || `${this.config.consumer}-${options.subject.replace(/\./g, "-")}`;
362
- const streamSubjects = options.options?.streamSubjects || this.deriveStreamSubjects(options.subject);
363
- try {
364
- await this.ensureStream({
365
- name: streamName,
366
- subjects: streamSubjects,
367
- retention: options.options?.retention || "limits",
368
- storage: options.options?.storage || "file"
369
- });
370
- } catch (error) {
371
- const errorMessage = error instanceof Error ? error.message : String(error);
372
- if (!errorMessage.includes("subjects overlap")) {
373
- throw error;
374
- }
375
- streamName = await jsm.streams.find(options.subject);
376
- logger.info("[NatsEventConsumer] Using existing stream for overlapping subject", {
377
- requestedStream: options.options?.stream || this.config.stream,
378
- stream: streamName,
379
- subject: options.subject
380
- });
381
- }
382
- await this.ensureConsumer({
383
- type: this.config.type,
384
- url: this.config.url,
385
- consumer: consumerName,
386
- stream: streamName,
387
- filterSubject: options.subject,
388
- ackPolicy: options.options?.ackPolicy,
389
- deliverPolicy: options.options?.deliverPolicy,
390
- maxDeliver: options.options?.maxDeliver || this.config.maxDeliver,
391
- ackWait: options.options?.ackWait || this.config.ackWait,
392
- maxAckPending: options.options?.maxAckPending
393
- });
394
- const consumer = await js.consumers.get(streamName, consumerName);
395
- const subscriptionId = `sub_${Date.now()}_${crypto.randomUUID().substring(0, 7)}`;
396
- let stopRequested = false;
397
- const stopFn = /* @__PURE__ */ __name(() => {
398
- stopRequested = true;
399
- }, "stopFn");
400
- const subscription = new NatsSubscription(subscriptionId, options.subject, stopFn);
401
- this.subscriptions.set(subscriptionId, subscription);
402
- this.consumeMessages(consumer, subscription, options.handler, options.options?.maxConcurrent || this.config.maxConcurrent || 1, () => stopRequested).catch((error) => {
403
- logger.error("[NatsEventConsumer] Error in message consumption loop", {
404
- subject: options.subject,
405
- error: error instanceof Error ? error.message : "Unknown error"
406
- });
407
- });
408
- logger.info("[NatsEventConsumer] Subscription created", {
409
- subscriptionId,
410
- subject: options.subject
411
- });
412
- return subscription;
413
- } catch (error) {
414
- logger.error("[NatsEventConsumer] Failed to subscribe", {
415
- subject: options.subject,
416
- error: error instanceof Error ? error.message : "Unknown error"
417
- });
418
- throw error;
419
- }
420
- }
421
- /**
422
- * Subscribe to multiple subjects
423
- */
424
- async subscribeMultiple(subjects, handler, options) {
425
- const subscriptions = [];
426
- for (const subject of subjects) {
427
- const subscription = await this.subscribe({
428
- subject,
429
- handler,
430
- options
431
- });
432
- subscriptions.push(subscription);
433
- }
434
- return subscriptions;
435
- }
436
- /**
437
- * Pull messages manually
438
- */
439
- async pull(options) {
440
- const js = this.connectionManager.getJetStream();
441
- try {
442
- const consumer = await js.consumers.get(this.config.stream, this.config.consumer);
443
- const messages = await consumer.fetch({
444
- max_messages: options.batch || 10,
445
- expires: options.timeout || 3e4
446
- });
447
- const events = [];
448
- for await (const msg of messages) {
449
- const event = this.wrapMessage(msg);
450
- events.push(event);
451
- }
452
- return events;
453
- } catch (error) {
454
- logger.error("[NatsEventConsumer] Failed to pull messages", {
455
- subject: options.subject,
456
- error: error instanceof Error ? error.message : "Unknown error"
457
- });
458
- throw error;
459
- }
460
- }
461
- /**
462
- * Unsubscribe from all active subscriptions
463
- */
464
- async unsubscribeAll() {
465
- const unsubscribePromises = Array.from(this.subscriptions.values()).map(async (subscription) => subscription.unsubscribe());
466
- await Promise.all(unsubscribePromises);
467
- this.subscriptions.clear();
468
- logger.info("[NatsEventConsumer] All subscriptions unsubscribed");
469
- }
470
- /**
471
- * Get all active subscriptions
472
- */
473
- getSubscriptions() {
474
- return Array.from(this.subscriptions.values());
475
- }
476
- /**
477
- * Process pending messages in dead letter queue
478
- */
479
- async processDLQ(_handler) {
480
- await Promise.resolve();
481
- logger.warn("[NatsEventConsumer] DLQ processing not yet implemented");
482
- }
483
- /**
484
- * List subjects for the configured stream
485
- */
486
- async listSubjects(streamName) {
487
- const jsm = this.connectionManager.getJetStreamManager();
488
- const info = await jsm.streams.info(streamName || this.config.stream);
489
- return info.config.subjects || [];
490
- }
491
- /**
492
- * Consume messages from consumer
493
- */
494
- async consumeMessages(consumer, subscription, handler, maxConcurrent, stopRequested) {
495
- try {
496
- const messages = await consumer.consume({
497
- max_messages: maxConcurrent,
498
- expires: 3e4
499
- });
500
- for await (const msg of messages) {
501
- if (stopRequested()) {
502
- break;
503
- }
504
- subscription.incrementReceived();
505
- try {
506
- const event = this.wrapMessage(msg);
507
- await runWithConsumerSpan(msg.subject, msg.headers, async () => handler(event));
508
- subscription.incrementProcessed();
509
- } catch (error) {
510
- subscription.incrementFailed();
511
- logger.error("[NatsEventConsumer] Error processing message", {
512
- subject: msg.subject,
513
- error: error instanceof Error ? error.message : "Unknown error"
514
- });
515
- msg.nak();
516
- }
517
- }
518
- } catch (error) {
519
- logger.error("[NatsEventConsumer] Error consuming messages", {
520
- error: error instanceof Error ? error.message : "Unknown error"
521
- });
522
- }
523
- }
524
- /**
525
- * Wrap NATS message in AcknowledgeableEvent
526
- */
527
- wrapMessage(msg) {
528
- const eventMessage = JSON.parse(msg.data.toString());
529
- return {
530
- ...eventMessage,
531
- sequence: msg.seq,
532
- ack: /* @__PURE__ */ __name(async () => {
533
- await Promise.resolve();
534
- msg.ack();
535
- }, "ack"),
536
- nak: /* @__PURE__ */ __name(async (delay) => {
537
- await Promise.resolve();
538
- if (delay) {
539
- msg.nak(delay);
540
- } else {
541
- msg.nak();
542
- }
543
- }, "nak"),
544
- term: /* @__PURE__ */ __name(async () => {
545
- await Promise.resolve();
546
- msg.term();
547
- }, "term"),
548
- isRedelivered: /* @__PURE__ */ __name(() => {
549
- return msg.redelivered;
550
- }, "isRedelivered"),
551
- getDeliveryAttempt: /* @__PURE__ */ __name(() => {
552
- return msg.info.deliveryCount;
553
- }, "getDeliveryAttempt")
554
- };
555
- }
556
- /**
557
- * Map retention policy string to NATS enum
558
- */
559
- mapRetentionPolicy(policy) {
560
- switch (policy?.toLowerCase()) {
561
- case "limits":
562
- return RetentionPolicy.Limits;
563
- case "interest":
564
- return RetentionPolicy.Interest;
565
- case "workqueue":
566
- default:
567
- return RetentionPolicy.Workqueue;
568
- }
569
- }
570
- /**
571
- * Map storage type string to NATS enum
572
- */
573
- mapStorageType(storage) {
574
- switch (storage?.toLowerCase()) {
575
- case "memory":
576
- return StorageType.Memory;
577
- case "file":
578
- default:
579
- return StorageType.File;
580
- }
581
- }
582
- /**
583
- * Map ack policy string to NATS enum
584
- */
585
- mapAckPolicy(policy) {
586
- switch (policy?.toLowerCase()) {
587
- case "none":
588
- return AckPolicy.None;
589
- case "all":
590
- return AckPolicy.All;
591
- case "explicit":
592
- default:
593
- return AckPolicy.Explicit;
594
- }
595
- }
596
- /**
597
- * Map deliver policy string to NATS enum
598
- */
599
- mapDeliverPolicy(policy) {
600
- switch (policy?.toLowerCase()) {
601
- case "new":
602
- return DeliverPolicy.New;
603
- case "last":
604
- return DeliverPolicy.Last;
605
- case "lastpersubject":
606
- return DeliverPolicy.LastPerSubject;
607
- case "all":
608
- default:
609
- return DeliverPolicy.All;
610
- }
611
- }
612
- };
613
- var DEFAULT_STREAM_MAX_BYTES2 = 10 * 1024 * 1024;
614
- var NatsEventPublisher = class {
615
- static {
616
- __name(this, "NatsEventPublisher");
617
- }
618
- config;
619
- connectionManager;
620
- publishCount = 0;
621
- lastPublishTime = null;
622
- constructor(config) {
623
- this.config = config;
624
- this.connectionManager = new NatsConnectionManager(config);
625
- }
626
- /**
627
- * Connect to NATS server
628
- */
629
- async connect() {
630
- await this.connectionManager.connect();
631
- }
632
- /**
633
- * Disconnect from NATS server
634
- */
635
- async disconnect() {
636
- await this.connectionManager.disconnect();
637
- }
638
- /**
639
- * Check if connected
640
- */
641
- isConnected() {
642
- return this.connectionManager.isConnected();
643
- }
644
- /**
645
- * Health check
646
- */
647
- async healthCheck() {
648
- await Promise.resolve();
649
- const isConnected = this.isConnected();
650
- return {
651
- status: isConnected ? "healthy" : "unhealthy",
652
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
653
- details: {
654
- connected: isConnected,
655
- type: "nats",
656
- url: this.config.url
657
- }
658
- };
659
- }
660
- /**
661
- * Get queue statistics
662
- */
663
- async getStatistics() {
664
- const jsm = this.connectionManager.getJetStreamManager();
665
- try {
666
- const streams = await jsm.streams.list().next();
667
- const streamCount = streams.length;
668
- return {
669
- messagesPublished: this.publishCount,
670
- messagesConsumed: 0,
671
- messagesFailed: 0,
672
- activeConsumers: 0,
673
- activePublishers: 1,
674
- queueSize: 0,
675
- lastActivity: this.lastPublishTime?.toISOString() || null,
676
- details: {
677
- streamCount,
678
- type: "nats"
679
- }
680
- };
681
- } catch (error) {
682
- logger.error("[NatsEventPublisher] Failed to get statistics", {
683
- error: error instanceof Error ? error.message : "Unknown error"
684
- });
685
- throw error;
686
- }
687
- }
688
- /**
689
- * Ensure a stream exists
690
- */
691
- async ensureStream(config) {
692
- const jsm = this.connectionManager.getJetStreamManager();
693
- try {
694
- try {
695
- await jsm.streams.info(config.name);
696
- logger.debug("[NatsEventPublisher] Stream already exists", {
697
- stream: config.name
698
- });
699
- return;
700
- } catch {
701
- }
702
- const streamConfig = {
703
- name: config.name,
704
- subjects: config.subjects,
705
- retention: this.mapRetentionPolicy(config.retention),
706
- storage: this.mapStorageType(config.storage),
707
- max_consumers: config.maxConsumers,
708
- max_msgs: config.maxMsgs,
709
- max_bytes: config.maxBytes ?? DEFAULT_STREAM_MAX_BYTES2,
710
- max_age: config.maxAge,
711
- duplicate_window: config.duplicateWindow
712
- };
713
- await jsm.streams.add(streamConfig);
714
- logger.info("[NatsEventPublisher] Stream created successfully", {
715
- stream: config.name,
716
- subjects: config.subjects
717
- });
718
- } catch (error) {
719
- logger.error("[NatsEventPublisher] Failed to ensure stream", {
720
- stream: config.name,
721
- error: error instanceof Error ? error.message : "Unknown error"
722
- });
723
- throw error;
724
- }
725
- }
726
- /**
727
- * Derive stream subject pattern from subscription subject
728
- * Examples:
729
- * - "channel.conversation.message" → ["channel.>"]
730
- * - "wspace.tags.created" → ["wspace.>"]
731
- * - "global.auth.login" → ["global.>"]
732
- */
733
- deriveStreamSubjects(subject) {
734
- const firstSegment = subject.split(".")[0];
735
- if (firstSegment) {
736
- return [
737
- `${firstSegment}.>`
738
- ];
739
- }
740
- return [
741
- `${subject.replace(/\.[^.]+$/, ".>")}`
742
- ];
743
- }
744
- /**
745
- * Derive stream name from subject
746
- * Examples:
747
- * - "channel.conversation.message" → "CHANNEL_EVENTS"
748
- * - "wspace.tags.created" → "WSPACE_EVENTS"
749
- * - "global.auth.login" → "GLOBAL_EVENTS"
750
- */
751
- deriveStreamName(subject) {
752
- const firstSegment = subject.split(".")[0];
753
- if (firstSegment) {
754
- return `${firstSegment.toUpperCase()}_EVENTS`;
755
- }
756
- return "EVENTS";
757
- }
758
- /**
759
- * Publish an event to a subject
760
- */
761
- async publish(options) {
762
- const js = this.connectionManager.getJetStream();
763
- try {
764
- const streamName = options.options?.stream || this.deriveStreamName(options.subject);
765
- const streamSubjects = options.options?.streamSubjects || this.deriveStreamSubjects(options.subject);
766
- await this.ensureStream({
767
- name: streamName,
768
- subjects: streamSubjects,
769
- retention: options.options?.retention || "limits",
770
- storage: options.options?.storage || "file"
771
- });
772
- const message = {
773
- id: options.options?.messageId || this.generateMessageId(),
774
- subject: options.subject,
775
- data: options.data,
776
- metadata: {
777
- source: options.metadata?.source || "workspaces-backend",
778
- correlationId: options.metadata?.correlationId || this.generateCorrelationId(),
779
- userId: options.metadata?.userId,
780
- workspaceId: options.metadata?.workspaceId,
781
- priority: options.options?.priority || this.config.defaultPriority || "normal",
782
- ...options.metadata
783
- },
784
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
785
- };
786
- const hdrs = headers();
787
- hdrs.set("message-id", message.id);
788
- hdrs.set("correlation-id", message.metadata.correlationId);
789
- if (message.metadata.source) {
790
- hdrs.set("source", message.metadata.source);
791
- }
792
- if (message.metadata["priority"] && typeof message.metadata["priority"] === "string") {
793
- hdrs.set("priority", message.metadata["priority"]);
794
- }
795
- if (message.metadata.userId) {
796
- hdrs.set("user-id", message.metadata.userId);
797
- }
798
- if (message.metadata.workspaceId) {
799
- hdrs.set("workspace-id", message.metadata.workspaceId);
800
- }
801
- await injectW3CTraceContext(hdrs);
802
- const publishOpts = {
803
- msgID: this.config.enableDeduplication ? message.id : void 0,
804
- headers: hdrs
805
- };
806
- if (options.options?.ttl) {
807
- logger.warn("[NatsEventPublisher] Per-message TTL not supported in NATS", {
808
- subject: options.subject,
809
- ttl: options.options.ttl
810
- });
811
- }
812
- if (options.options?.delay) {
813
- logger.warn("[NatsEventPublisher] Message delay not supported in NATS", {
814
- subject: options.subject,
815
- delay: options.options.delay
816
- });
817
- }
818
- const ack = await js.publish(options.subject, JSON.stringify(message), publishOpts);
819
- this.publishCount++;
820
- this.lastPublishTime = /* @__PURE__ */ new Date();
821
- logger.debug("[NatsEventPublisher] Event published", {
822
- subject: options.subject,
823
- messageId: message.id,
824
- sequence: ack.seq
825
- });
826
- return ack.seq;
827
- } catch (error) {
828
- logger.error("[NatsEventPublisher] Failed to publish event", {
829
- subject: options.subject,
830
- error: error instanceof Error ? error.message : "Unknown error"
831
- });
832
- throw error;
833
- }
834
- }
835
- /**
836
- * Publish multiple events in a batch
837
- */
838
- async publishBatch(events) {
839
- const results = [];
840
- for (const event of events) {
841
- const seq = await this.publish(event);
842
- results.push(seq);
843
- }
844
- return results;
845
- }
846
- /**
847
- * Publish an event and wait for acknowledgment
848
- * Note: This is not natively supported by NATS JetStream
849
- * Would require implementing request-reply pattern
850
- */
851
- async publishWithAck(options) {
852
- const nc = this.connectionManager.getNatsConnection();
853
- try {
854
- const message = {
855
- id: this.generateMessageId(),
856
- subject: options.subject,
857
- data: options.data,
858
- metadata: {
859
- source: options.metadata?.source || "workspaces-backend",
860
- correlationId: options.metadata?.correlationId || this.generateCorrelationId(),
861
- userId: options.metadata?.userId,
862
- workspaceId: options.metadata?.workspaceId,
863
- ...options.metadata
864
- },
865
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
866
- };
867
- const response = await nc.request(options.subject, JSON.stringify(message), {
868
- timeout: options.timeout || 3e4
869
- });
870
- const result = JSON.parse(response.data.toString());
871
- logger.debug("[NatsEventPublisher] Event published with ack", {
872
- subject: options.subject,
873
- messageId: message.id
874
- });
875
- return result;
876
- } catch (error) {
877
- logger.error("[NatsEventPublisher] Failed to publish event with ack", {
878
- subject: options.subject,
879
- error: error instanceof Error ? error.message : "Unknown error"
880
- });
881
- throw error;
882
- }
883
- }
884
- /**
885
- * Map retention policy string to NATS enum
886
- */
887
- mapRetentionPolicy(policy) {
888
- switch (policy?.toLowerCase()) {
889
- case "limits":
890
- return RetentionPolicy.Limits;
891
- case "interest":
892
- return RetentionPolicy.Interest;
893
- case "workqueue":
894
- default:
895
- return RetentionPolicy.Workqueue;
896
- }
897
- }
898
- /**
899
- * Map storage type string to NATS enum
900
- */
901
- mapStorageType(storage) {
902
- switch (storage?.toLowerCase()) {
903
- case "memory":
904
- return StorageType.Memory;
905
- case "file":
906
- default:
907
- return StorageType.File;
908
- }
909
- }
910
- /**
911
- * Generate unique message ID
912
- */
913
- generateMessageId() {
914
- return `msg_${Date.now()}_${crypto.randomUUID().substring(0, 13)}`;
915
- }
916
- /**
917
- * Generate correlation ID
918
- */
919
- generateCorrelationId() {
920
- return `corr_${Date.now()}_${crypto.randomUUID().substring(0, 13)}`;
921
- }
922
- };
923
-
924
- // src/event-queue/factory/EventQueueFactory.ts
925
- var EventQueueFactory = class _EventQueueFactory {
926
- static {
927
- __name(this, "EventQueueFactory");
928
- }
929
- /**
930
- * Create an event publisher based on configuration
931
- */
932
- static createPublisher(config) {
933
- logger.info("[EventQueueFactory] Creating event publisher", {
934
- type: config.type,
935
- url: config.url
936
- });
937
- if (config.type === QueueType.NATS) {
938
- return new NatsEventPublisher(config);
939
- }
940
- throw new Error(`Unsupported queue type: ${config.type}`);
941
- }
942
- /**
943
- * Create an event consumer based on configuration
944
- */
945
- static createConsumer(config) {
946
- logger.info("[EventQueueFactory] Creating event consumer", {
947
- type: config.type,
948
- url: config.url,
949
- stream: config.stream,
950
- consumer: config.consumer
951
- });
952
- if (config.type === QueueType.NATS) {
953
- return new NatsEventConsumer(config);
954
- }
955
- throw new Error(`Unsupported queue type: ${config.type}`);
956
- }
957
- /**
958
- * Create a publisher from environment variables
959
- */
960
- static createPublisherFromEnv() {
961
- const config = {
962
- type: process.env["QUEUE_TYPE"] || QueueType.NATS,
963
- url: process.env["NATS_URL"] || "nats://localhost:4222",
964
- user: process.env["NATS_USER"],
965
- password: process.env["NATS_PASSWORD"],
966
- token: process.env["NATS_TOKEN"],
967
- creds: process.env["NATS_CREDS"],
968
- credsFile: process.env["NATS_CREDS_FILE"],
969
- name: process.env["QUEUE_CLIENT_NAME"] || "workspaces-backend-publisher",
970
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
971
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
972
- enableDeduplication: process.env["QUEUE_ENABLE_DEDUPLICATION"] === "true",
973
- defaultPriority: process.env["QUEUE_DEFAULT_PRIORITY"] || "normal",
974
- defaultTTL: process.env["QUEUE_DEFAULT_TTL"] ? parseInt(process.env["QUEUE_DEFAULT_TTL"], 10) : void 0
975
- };
976
- return _EventQueueFactory.createPublisher(config);
977
- }
978
- /**
979
- * Create a consumer from environment variables
980
- */
981
- static createConsumerFromEnv(stream, consumer) {
982
- const config = {
983
- type: process.env["QUEUE_TYPE"] || QueueType.NATS,
984
- url: process.env["NATS_URL"] || "nats://localhost:4222",
985
- user: process.env["NATS_USER"],
986
- password: process.env["NATS_PASSWORD"],
987
- token: process.env["NATS_TOKEN"],
988
- creds: process.env["NATS_CREDS"],
989
- credsFile: process.env["NATS_CREDS_FILE"],
990
- name: process.env["QUEUE_CLIENT_NAME"] || "workspaces-workers-consumer",
991
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
992
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
993
- stream,
994
- consumer,
995
- maxConcurrent: process.env["QUEUE_MAX_CONCURRENT"] ? parseInt(process.env["QUEUE_MAX_CONCURRENT"], 10) : 5,
996
- maxDeliver: process.env["QUEUE_MAX_DELIVER"] ? parseInt(process.env["QUEUE_MAX_DELIVER"], 10) : 3,
997
- ackWait: process.env["QUEUE_ACK_WAIT"] ? parseInt(process.env["QUEUE_ACK_WAIT"], 10) * 1e9 : 3e10
998
- };
999
- return _EventQueueFactory.createConsumer(config);
1000
- }
1001
- // ========================================================================
1002
- // Layer-Aware Factory Methods
1003
- // ========================================================================
1004
- /**
1005
- * Create a publisher for a specific layer
1006
- *
1007
- * @param layer - Service layer ('wspace' or 'global')
1008
- * @param serviceName - Service name for identification
1009
- * @returns Publisher configured for the layer
1010
- *
1011
- * @example
1012
- * ```typescript
1013
- * const publisher = EventQueueFactory.createPublisherForLayer('wspace', 'wspace-tags-svc');
1014
- * await publisher.connect();
1015
- * await publisher.publish({ subject: 'wspace.tags.created', data: { id: '123' } });
1016
- * ```
1017
- */
1018
- static createPublisherForLayer(layer, serviceName) {
1019
- const envPrefix = layer.toUpperCase();
1020
- const defaults = DEFAULT_LAYER_RESOURCES[layer];
1021
- const config = {
1022
- type: QueueType.NATS,
1023
- url: process.env[`${envPrefix}_NATS_URL`] || process.env["NATS_URL"] || defaults.natsUrl,
1024
- user: process.env["NATS_USER"],
1025
- password: process.env["NATS_PASSWORD"],
1026
- token: process.env["NATS_TOKEN"],
1027
- creds: process.env["NATS_CREDS"],
1028
- credsFile: process.env["NATS_CREDS_FILE"],
1029
- name: serviceName,
1030
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
1031
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
1032
- enableDeduplication: process.env["QUEUE_ENABLE_DEDUPLICATION"] === "true",
1033
- defaultPriority: process.env["QUEUE_DEFAULT_PRIORITY"] || "normal",
1034
- defaultTTL: process.env["QUEUE_DEFAULT_TTL"] ? parseInt(process.env["QUEUE_DEFAULT_TTL"], 10) : void 0
1035
- };
1036
- logger.info("[EventQueueFactory] Creating layer publisher", {
1037
- layer,
1038
- serviceName,
1039
- url: config.url
1040
- });
1041
- return _EventQueueFactory.createPublisher(config);
1042
- }
1043
- /**
1044
- * Create a consumer for a specific layer
1045
- *
1046
- * @param layer - Service layer ('wspace' or 'global')
1047
- * @param serviceName - Service name for identification
1048
- * @param stream - NATS stream name
1049
- * @param consumer - Consumer name
1050
- * @returns Consumer configured for the layer
1051
- *
1052
- * @example
1053
- * ```typescript
1054
- * const consumer = EventQueueFactory.createConsumerForLayer(
1055
- * 'wspace', 'wspace-tags-svc', 'WSPACE_EVENTS', 'tags-consumer'
1056
- * );
1057
- * await consumer.connect();
1058
- * await consumer.consume(async (msg) => { console.log(msg); });
1059
- * ```
1060
- */
1061
- static createConsumerForLayer(layer, serviceName, stream, consumer) {
1062
- const envPrefix = layer.toUpperCase();
1063
- const defaults = DEFAULT_LAYER_RESOURCES[layer];
1064
- const config = {
1065
- type: QueueType.NATS,
1066
- url: process.env[`${envPrefix}_NATS_URL`] || process.env["NATS_URL"] || defaults.natsUrl,
1067
- user: process.env["NATS_USER"],
1068
- password: process.env["NATS_PASSWORD"],
1069
- token: process.env["NATS_TOKEN"],
1070
- creds: process.env["NATS_CREDS"],
1071
- credsFile: process.env["NATS_CREDS_FILE"],
1072
- name: serviceName,
1073
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
1074
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
1075
- stream,
1076
- consumer,
1077
- maxConcurrent: process.env["QUEUE_MAX_CONCURRENT"] ? parseInt(process.env["QUEUE_MAX_CONCURRENT"], 10) : 5,
1078
- maxDeliver: process.env["QUEUE_MAX_DELIVER"] ? parseInt(process.env["QUEUE_MAX_DELIVER"], 10) : 3,
1079
- ackWait: process.env["QUEUE_ACK_WAIT"] ? parseInt(process.env["QUEUE_ACK_WAIT"], 10) * 1e9 : 3e10
1080
- };
1081
- logger.info("[EventQueueFactory] Creating layer consumer", {
1082
- layer,
1083
- serviceName,
1084
- stream,
1085
- consumer,
1086
- url: config.url
1087
- });
1088
- return _EventQueueFactory.createConsumer(config);
1089
- }
1090
- };
1091
-
1092
- export { EventQueueFactory, NatsEventConsumer, NatsEventPublisher };
1093
- //# sourceMappingURL=chunk-KSO6QQVD.js.map
1094
- //# sourceMappingURL=chunk-KSO6QQVD.js.map