@spinajs/queue-amqp-transport 2.0.482 → 2.0.485

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.
@@ -0,0 +1,529 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.AmqpQueueClient = void 0;
16
+ const exceptions_1 = require("@spinajs/exceptions");
17
+ const queue_1 = require("@spinajs/queue");
18
+ const amqplib_1 = __importDefault(require("amqplib"));
19
+ const lodash_1 = __importDefault(require("lodash"));
20
+ const di_1 = require("@spinajs/di");
21
+ const util_1 = require("@spinajs/util");
22
+ /**
23
+ * Default prefix that marks a channel as a topic ( pub-sub / fanout exchange ).
24
+ * Every other channel is treated as a durable work queue ( single consumer, job semantics ).
25
+ *
26
+ * This keeps parity with the STOMP transport convention of `/topic/...` vs `/queue/...`.
27
+ */
28
+ const DEFAULT_TOPIC_PREFIX = '/topic/';
29
+ /** Header carrying the retry attempt count across redeliveries. */
30
+ const RETRY_COUNT_HEADER = 'x-retry-count';
31
+ let AmqpQueueClient = class AmqpQueueClient extends queue_1.QueueClient {
32
+ get ClientId() {
33
+ return this.Options.clientId ?? this.Options.name;
34
+ }
35
+ get TopicPrefix() {
36
+ return this.Options.options?.topicPrefix ?? DEFAULT_TOPIC_PREFIX;
37
+ }
38
+ get ReconnectDelay() {
39
+ return this.Options.reconnectDelay ?? 5000;
40
+ }
41
+ get Prefetch() {
42
+ return this.Options.options?.prefetch ?? 1;
43
+ }
44
+ get IsConnected() {
45
+ return this.Connected;
46
+ }
47
+ constructor(options) {
48
+ super(options);
49
+ this.Subscriptions = new Map();
50
+ // destinations already declared on the broker, so we assert each one only once per connection
51
+ // ( assert is a network round-trip ). Cleared on reconnect because channels are recreated.
52
+ this.AssertedQueues = new Set();
53
+ this.AssertedExchanges = new Set();
54
+ this.AssertedRetryQueues = new Set();
55
+ /** Messages emitted while disconnected - flushed on (re)connect. */
56
+ this.PendingEmits = [];
57
+ this.Connected = false;
58
+ this.Disposing = false;
59
+ /** Publisher-side resilience: time-bound + retry each publish so transient broker hiccups
60
+ * don't lose an emit. Safe against the resulting duplicates because consumers dedupe by JobId. */
61
+ this.EmitPipeline = this.buildEmitPipeline();
62
+ }
63
+ async resolve() {
64
+ await this.connect();
65
+ }
66
+ /**
67
+ * Creates the underlying amqplib connection. Isolated as a seam so tests can inject a fake
68
+ * broker without a real server ( mirrors the STOMP transport's createClient seam ).
69
+ */
70
+ createConnection(url, socketOptions) {
71
+ return amqplib_1.default.connect(url, socketOptions);
72
+ }
73
+ /**
74
+ * Builds the amqplib connection target from the configured options.
75
+ *
76
+ * A url-style host ( `amqp://.../vhost` ) is parsed into an explicit {@link Options.Connect}
77
+ * object rather than passed as a raw string, so every setting - crucially the credentials - is a
78
+ * clear field instead of being buried in the url. amqplib derives credentials for a *string* url
79
+ * only from the url's own userinfo, which is why the discrete `login` / `password` config fields
80
+ * were previously ignored for a url host. Credentials embedded in the url still win; the config
81
+ * fields are the fallback when the url carries none ( matching amqplib's own precedence ).
82
+ */
83
+ buildConnectionTarget() {
84
+ const host = this.Options.host;
85
+ // discrete-fields host ( no scheme ) - build straight from the individual config fields
86
+ if (!host || !host.includes('://')) {
87
+ return this.connectOptionsFromFields(host ?? 'localhost');
88
+ }
89
+ let parsed;
90
+ try {
91
+ parsed = new URL(host);
92
+ }
93
+ catch {
94
+ // not a parseable url - treat the whole value as a bare hostname and use the config fields
95
+ return this.connectOptionsFromFields(host);
96
+ }
97
+ const protocol = parsed.protocol.replace(/:$/, '') || 'amqp';
98
+ // amqplib treats the url's credentials as authoritative when it carries either field; only when
99
+ // it carries neither do we fall back to the login / password config fields.
100
+ const urlHasCredentials = parsed.username !== '' || parsed.password !== '';
101
+ const target = {
102
+ protocol,
103
+ // strip IPv6 brackets - amqplib uses hostname verbatim as the socket host in object mode
104
+ hostname: parsed.hostname.replace(/^\[|\]$/g, ''),
105
+ port: parsed.port ? Number(parsed.port) : this.Options.port ?? (protocol === 'amqps' ? 5671 : 5672),
106
+ username: urlHasCredentials ? decodeURIComponent(parsed.username) : this.Options.login,
107
+ password: urlHasCredentials ? decodeURIComponent(parsed.password) : this.Options.password,
108
+ // keep the vhost percent-encoded - amqplib unescapes it exactly once ( decoding here too would
109
+ // double-decode, eg. %2f -> / -> wrong vhost ). An empty path keeps the broker default.
110
+ vhost: parsed.pathname && parsed.pathname !== '/' ? parsed.pathname.slice(1) : '/',
111
+ };
112
+ // connection tuning params live in the url query string in string-mode; carry the ones amqplib
113
+ // understands over so switching to object-mode does not silently drop them.
114
+ const heartbeat = parsed.searchParams.get('heartbeat');
115
+ const frameMax = parsed.searchParams.get('frameMax');
116
+ const locale = parsed.searchParams.get('locale');
117
+ if (heartbeat !== null)
118
+ target.heartbeat = Number(heartbeat);
119
+ if (frameMax !== null)
120
+ target.frameMax = Number(frameMax);
121
+ if (locale !== null)
122
+ target.locale = locale;
123
+ return target;
124
+ }
125
+ /** Connect-options object built from the discrete `host` / `port` / `login` / `password` fields. */
126
+ connectOptionsFromFields(hostname) {
127
+ return {
128
+ protocol: 'amqp',
129
+ hostname,
130
+ port: this.Options.port ?? 5672,
131
+ username: this.Options.login,
132
+ password: this.Options.password,
133
+ vhost: this.Options.options?.vhost ?? '/',
134
+ };
135
+ }
136
+ async dispose() {
137
+ this.Log.info(`Disposing queue connection ${this.Options.name} ...`);
138
+ this.Disposing = true;
139
+ if (this.ReconnectTimer) {
140
+ clearTimeout(this.ReconnectTimer);
141
+ this.ReconnectTimer = undefined;
142
+ }
143
+ await this.closeChannel(this.PublishChannel);
144
+ await this.closeChannel(this.ConsumeChannel);
145
+ try {
146
+ if (this.Connection) {
147
+ await this.Connection.close();
148
+ }
149
+ }
150
+ catch (err) {
151
+ this.Log.warn(`Error while closing AMQP connection for ${this.Options.name}: ${err?.message}`);
152
+ }
153
+ this.Connected = false;
154
+ this.Subscriptions.clear();
155
+ this.Log.success(`AMQP connection ${this.Options.name} disposed`);
156
+ }
157
+ /**
158
+ * Establishes the connection + channels, then replays subscriptions and flushes buffered emits.
159
+ * Called on initial resolve and on every reconnect.
160
+ */
161
+ async connect() {
162
+ this.Log.info(`Connecting to AMQP queue at ${this.Options.host ?? 'localhost'} with client-id: ${this.ClientId} ...`);
163
+ // channels are recreated - forget what the previous ( dead ) channels had asserted
164
+ this.AssertedQueues.clear();
165
+ this.AssertedExchanges.clear();
166
+ this.AssertedRetryQueues.clear();
167
+ try {
168
+ // resolve the connection target from config. A url-style host is parsed into an explicit
169
+ // Options.Connect object ( see buildConnectionTarget ) so the credentials and every other
170
+ // setting are clear fields instead of being hidden inside a url string.
171
+ const url = this.buildConnectionTarget();
172
+ this.Connection = await this.createConnection(url, {
173
+ clientProperties: { connection_name: this.ClientId },
174
+ ...this.Options.options,
175
+ });
176
+ }
177
+ catch (err) {
178
+ throw new exceptions_1.UnexpectedServerError(`Cannot connect to AMQP queue server at ${this.Options.host ?? 'localhost'}`, err);
179
+ }
180
+ this.Connection.on('error', (err) => {
181
+ this.Log.error(`AMQP connection error, client-id: ${this.ClientId}, name: ${this.Options.name}: ${err?.message}`);
182
+ });
183
+ this.Connection.on('close', () => {
184
+ this.onConnectionLost();
185
+ });
186
+ // confirm channel for publishing ( emit() waits for the broker ack ), plain channel for consuming
187
+ this.PublishChannel = await this.Connection.createConfirmChannel();
188
+ this.ConsumeChannel = await this.Connection.createChannel();
189
+ // limit in-flight unacked messages per consumer. Defaults to 1 ( fair dispatch, mirrors STOMP
190
+ // `activemq.prefetchSize: 1` ). Raise via options.prefetch to trade fairness for throughput.
191
+ await this.ConsumeChannel.prefetch(this.Prefetch);
192
+ this.Connected = true;
193
+ this.Log.success(`Connected to AMQP broker, client-id: ${this.ClientId}`);
194
+ await this.replaySubscriptions();
195
+ await this.flushPendingEmits();
196
+ }
197
+ /**
198
+ * Handles an unexpected connection drop by scheduling a reconnect ( unless we are disposing ).
199
+ */
200
+ onConnectionLost() {
201
+ if (this.Disposing || !this.Connected) {
202
+ return;
203
+ }
204
+ this.Connected = false;
205
+ this.Log.warn(`AMQP connection ${this.Options.name} lost, scheduling reconnect in ${this.ReconnectDelay}ms`);
206
+ this.scheduleReconnect();
207
+ }
208
+ scheduleReconnect() {
209
+ if (this.ReconnectTimer || this.Disposing) {
210
+ return;
211
+ }
212
+ this.ReconnectTimer = setTimeout(() => {
213
+ this.ReconnectTimer = undefined;
214
+ this.connect().catch((err) => {
215
+ this.Log.error(`AMQP reconnect for ${this.Options.name} failed: ${err?.message}. Retrying in ${this.ReconnectDelay}ms`);
216
+ this.scheduleReconnect();
217
+ });
218
+ }, this.ReconnectDelay);
219
+ }
220
+ async emit(message) {
221
+ this.warnOnUnsupportedScheduling(message);
222
+ // buffer while disconnected so callers can emit during a reconnect window
223
+ if (!this.Connected) {
224
+ return new Promise((resolve, reject) => {
225
+ this.PendingEmits.push({ message, resolve, reject });
226
+ });
227
+ }
228
+ return this.publishMessage(message);
229
+ }
230
+ async subscribe(channelOrMessage, callback, subscriptionId, durable) {
231
+ const channels = lodash_1.default.isString(channelOrMessage) ? [channelOrMessage] : this.getChannelForMessage(channelOrMessage);
232
+ for (const c of channels) {
233
+ if (this.Subscriptions.has(c)) {
234
+ this.Log.warn(`Channel ${c} already subscribed !`);
235
+ continue;
236
+ }
237
+ const descriptor = { channel: c, callback, subscriptionId, durable: !!durable };
238
+ this.Subscriptions.set(c, descriptor);
239
+ await this.startConsumer(descriptor);
240
+ }
241
+ }
242
+ unsubscribe(channelOrMessage, _removeDurable) {
243
+ const channels = lodash_1.default.isString(channelOrMessage) ? [channelOrMessage] : this.getChannelForMessage(channelOrMessage);
244
+ for (const c of channels) {
245
+ const sub = this.Subscriptions.get(c);
246
+ if (!sub) {
247
+ continue;
248
+ }
249
+ this.Subscriptions.delete(c);
250
+ // cancel only the consumer. For durable subscriptions the bound queue is left in place
251
+ // so messages keep accumulating while no consumer is attached ( same semantics as STOMP ).
252
+ if (sub.consumerTag) {
253
+ this.ConsumeChannel.cancel(sub.consumerTag).catch((err) => {
254
+ this.Log.warn(`Error while cancelling consumer for channel ${c}: ${err?.message}`);
255
+ });
256
+ }
257
+ }
258
+ }
259
+ /**
260
+ * Re-establishes every known subscription. Called after a (re)connect.
261
+ */
262
+ async replaySubscriptions() {
263
+ for (const descriptor of this.Subscriptions.values()) {
264
+ await this.startConsumer(descriptor);
265
+ }
266
+ }
267
+ /**
268
+ * Declares the queue for a subscription and starts consuming, wiring ack/nack + retry/dead-letter.
269
+ */
270
+ async startConsumer(descriptor) {
271
+ const c = descriptor.channel;
272
+ const queue = await this.assertSubscriptionQueue(c, descriptor.subscriptionId, descriptor.durable);
273
+ descriptor.queue = queue;
274
+ const { consumerTag } = await this.ConsumeChannel.consume(queue, (msg) => {
275
+ // null is delivered when the consumer is cancelled by the broker
276
+ if (!msg) {
277
+ return;
278
+ }
279
+ let qMessage;
280
+ try {
281
+ qMessage = JSON.parse(msg.content.toString());
282
+ }
283
+ catch (err) {
284
+ this.Log.error(`Cannot parse incoming message on channel ${c}, dead-lettering it: ${err?.message}`);
285
+ this.deadLetterRaw(msg, this.Options.defaultQueueDeadLetterChannel, c, err?.message ?? String(err));
286
+ return;
287
+ }
288
+ descriptor
289
+ .callback(qMessage)
290
+ .then(() => this.ConsumeChannel.ack(msg))
291
+ .catch((err) => this.handleFailedMessage(msg, qMessage, c, err));
292
+ }, { noAck: false });
293
+ descriptor.consumerTag = consumerTag;
294
+ this.Log.success(`Channel ${c}, durable: ${descriptor.durable ? 'true' : 'false'} subscribed and ready to receive messages !`);
295
+ }
296
+ /**
297
+ * Handles a message whose consumer callback rejected.
298
+ *
299
+ * Events are fire-and-forget - logged and acked ( dropped ). Jobs are retried up to their
300
+ * RetryCount by re-publishing to a TTL "retry" queue that dead-letters back to the work queue
301
+ * after an exponential delay, then dead-lettered once retries are exhausted.
302
+ */
303
+ handleFailedMessage(msg, qMessage, channel, err) {
304
+ const reason = err?.message ?? String(err);
305
+ // events are not retried or tracked - drop them
306
+ if (qMessage.Type !== queue_1.QueueMessageType.Job || this.isTopic(channel)) {
307
+ this.Log.warn(`Handler failed on channel ${channel}, dropping message ${qMessage.Name}. ${reason}`);
308
+ this.ConsumeChannel.ack(msg);
309
+ return;
310
+ }
311
+ const maxRetries = qMessage.RetryCount ?? 0;
312
+ const attempt = Number(msg.properties.headers?.[RETRY_COUNT_HEADER] ?? 0);
313
+ if (attempt < maxRetries) {
314
+ this.retryJob(msg, qMessage, channel, attempt + 1, reason).catch((retryErr) => {
315
+ this.Log.error(`Failed to reschedule job ${qMessage.Name} on ${channel}, nacking instead: ${retryErr.message}`);
316
+ this.ConsumeChannel.nack(msg, false, false);
317
+ });
318
+ return;
319
+ }
320
+ // retries exhausted - route to the dead-letter queue
321
+ this.deadLetterRaw(msg, this.getDeadLetterChannelForMessage(qMessage), channel, reason, attempt);
322
+ }
323
+ /**
324
+ * Republishes a failed job to a per-delay TTL retry queue that dead-letters back to the work
325
+ * queue after the delay, giving broker-side ( crash-safe ) exponential backoff. Then acks original.
326
+ */
327
+ async retryJob(msg, qMessage, workQueue, nextAttempt, reason) {
328
+ const delay = this.retryBackoff(nextAttempt);
329
+ const retryQueue = await this.assertRetryQueue(workQueue, delay);
330
+ this.ConsumeChannel.sendToQueue(retryQueue, msg.content, {
331
+ persistent: true,
332
+ contentType: 'application/json',
333
+ priority: msg.properties.priority,
334
+ headers: { ...msg.properties.headers, [RETRY_COUNT_HEADER]: nextAttempt },
335
+ });
336
+ this.ConsumeChannel.ack(msg);
337
+ this.Log.warn(`Job ${qMessage.Name} failed on ${workQueue}, retry ${nextAttempt}/${qMessage.RetryCount} scheduled in ${delay}ms. ${reason}`);
338
+ }
339
+ /**
340
+ * Publishes a failed/unparseable message to the dead-letter queue and acks the original to
341
+ * unblock the source queue. When no dead-letter queue is configured the message is dropped
342
+ * ( acked ) with a warning - we never nack-loop a poison message forever.
343
+ */
344
+ deadLetterRaw(msg, dlq, channel, reason, attempt) {
345
+ if (!dlq) {
346
+ this.Log.warn(`Message failed on channel ${channel}, no dead-letter queue configured - dropping. ${reason}`);
347
+ this.ConsumeChannel.ack(msg);
348
+ return;
349
+ }
350
+ this.assertQueue(this.ConsumeChannel, dlq)
351
+ .then(() => {
352
+ this.ConsumeChannel.sendToQueue(dlq, msg.content, {
353
+ persistent: true,
354
+ contentType: 'application/json',
355
+ headers: { ...msg.properties.headers, 'x-error': reason, ...(attempt !== undefined ? { [RETRY_COUNT_HEADER]: attempt } : {}) },
356
+ });
357
+ this.ConsumeChannel.ack(msg);
358
+ this.Log.warn(`Message failed on channel ${channel}, routed to dead-letter ${dlq}. ${reason}`);
359
+ })
360
+ .catch((dlqErr) => {
361
+ this.Log.error(`Failed to route message to dead-letter ${dlq}, nacking instead: ${dlqErr.message}`);
362
+ this.ConsumeChannel.nack(msg, false, false);
363
+ });
364
+ }
365
+ /**
366
+ * Exponential backoff ( ms ) for the given retry attempt, based on `Options.retryDelay`.
367
+ * Returns 0 ( immediate redelivery ) when no base delay is configured.
368
+ */
369
+ retryBackoff(attempt) {
370
+ const base = this.Options.retryDelay ?? 0;
371
+ return base > 0 ? base * 2 ** (attempt - 1) : 0;
372
+ }
373
+ /**
374
+ * Publisher-side resilience pipeline: bounds each publish by a timeout and retries transient
375
+ * failures / nacks with exponential backoff. Consumer dedup ( by JobId ) makes the resulting
376
+ * rare duplicates harmless.
377
+ */
378
+ buildEmitPipeline() {
379
+ const attempts = this.Options.options?.emitRetries ?? 3;
380
+ const timeout = this.Options.receiptTimeout ?? 5000;
381
+ const base = this.Options.retryDelay && this.Options.retryDelay > 0 ? this.Options.retryDelay : 200;
382
+ return new util_1.ResiliencePipelineBuilder()
383
+ .addRetry({ MaxRetryAttempts: attempts, Delay: base, MaxDelay: 30000, BackoffType: util_1.BackoffType.Exponential, UseJitter: true })
384
+ .addTimeout(timeout)
385
+ .build();
386
+ }
387
+ async publishMessage(message) {
388
+ const channels = this.getChannelForMessage(message);
389
+ const buffer = Buffer.from(JSON.stringify(message));
390
+ const publishOptions = {
391
+ persistent: !!message.Persistent,
392
+ contentType: 'application/json',
393
+ };
394
+ if (message.JobId) {
395
+ publishOptions.correlationId = message.JobId;
396
+ }
397
+ if (message.Priority) {
398
+ publishOptions.priority = message.Priority;
399
+ }
400
+ for (const c of channels) {
401
+ await this.EmitPipeline.execute(() => this.publishToChannel(c, buffer, publishOptions));
402
+ this.Log.trace(`Published ${message.Type} Name: ${message.Name} to channel ${c} ( ${this.Options.name} )`);
403
+ }
404
+ }
405
+ /** Asserts the destination ( once ) and publishes a single message on the confirm channel. */
406
+ async publishToChannel(channel, buffer, options) {
407
+ if (this.isTopic(channel)) {
408
+ await this.assertExchange(this.PublishChannel, channel);
409
+ await this.publishWithConfirm(channel, '', buffer, options);
410
+ }
411
+ else {
412
+ await this.assertQueue(this.PublishChannel, channel);
413
+ await this.publishWithConfirm('', channel, buffer, options);
414
+ }
415
+ }
416
+ /**
417
+ * Publishes on the confirm channel and resolves only once the broker acks the message.
418
+ */
419
+ publishWithConfirm(exchange, routingKey, content, options) {
420
+ return new Promise((resolve, reject) => {
421
+ this.PublishChannel.publish(exchange, routingKey, content, options, (err) => {
422
+ if (err) {
423
+ reject(err instanceof Error ? err : new exceptions_1.UnexpectedServerError(`Broker nacked message on ${exchange || routingKey}`, err));
424
+ }
425
+ else {
426
+ resolve();
427
+ }
428
+ });
429
+ });
430
+ }
431
+ async flushPendingEmits() {
432
+ if (this.PendingEmits.length === 0) {
433
+ return;
434
+ }
435
+ const pending = this.PendingEmits;
436
+ this.PendingEmits = [];
437
+ this.Log.info(`Flushing ${pending.length} buffered message(s) for queue ${this.Options.name}`);
438
+ for (const p of pending) {
439
+ this.publishMessage(p.message).then(p.resolve).catch(p.reject);
440
+ }
441
+ }
442
+ /**
443
+ * Declares ( and for topics binds ) the broker queue a subscription should consume from.
444
+ */
445
+ async assertSubscriptionQueue(channel, subscriptionId, durable) {
446
+ if (!this.isTopic(channel)) {
447
+ return this.assertQueue(this.ConsumeChannel, channel);
448
+ }
449
+ await this.assertExchange(this.ConsumeChannel, channel);
450
+ let queueName;
451
+ if (durable) {
452
+ if (!subscriptionId) {
453
+ throw new exceptions_1.InvalidArgument(`subscriptionId cannot be empty if using durable subscriptions`);
454
+ }
455
+ const q = await this.ConsumeChannel.assertQueue(subscriptionId, { durable: true, exclusive: false, autoDelete: false });
456
+ queueName = q.queue;
457
+ }
458
+ else {
459
+ // server-named, exclusive, auto-deleted queue ( unique per subscriber )
460
+ const q = await this.ConsumeChannel.assertQueue(subscriptionId ?? '', { durable: false, exclusive: !subscriptionId, autoDelete: true });
461
+ queueName = q.queue;
462
+ }
463
+ await this.ConsumeChannel.bindQueue(queueName, channel, '');
464
+ return queueName;
465
+ }
466
+ /**
467
+ * Declares a durable work queue, asserting it on the broker only once per connection.
468
+ */
469
+ async assertQueue(channel, name) {
470
+ if (!this.AssertedQueues.has(name)) {
471
+ await channel.assertQueue(name, { durable: true });
472
+ this.AssertedQueues.add(name);
473
+ }
474
+ return name;
475
+ }
476
+ /**
477
+ * Declares a durable fanout exchange, asserting it on the broker only once per connection.
478
+ */
479
+ async assertExchange(channel, name) {
480
+ if (!this.AssertedExchanges.has(name)) {
481
+ await channel.assertExchange(name, 'fanout', { durable: true });
482
+ this.AssertedExchanges.add(name);
483
+ }
484
+ }
485
+ /**
486
+ * Declares a durable TTL retry queue that dead-letters expired messages back to `workQueue`
487
+ * ( via the default exchange, routing key = queue name ). One queue per distinct delay.
488
+ */
489
+ async assertRetryQueue(workQueue, delay) {
490
+ const name = `${workQueue}.retry.${delay}`;
491
+ if (!this.AssertedRetryQueues.has(name)) {
492
+ await this.ConsumeChannel.assertQueue(name, {
493
+ durable: true,
494
+ arguments: {
495
+ 'x-message-ttl': delay,
496
+ 'x-dead-letter-exchange': '',
497
+ 'x-dead-letter-routing-key': workQueue,
498
+ },
499
+ });
500
+ this.AssertedRetryQueues.add(name);
501
+ }
502
+ return name;
503
+ }
504
+ isTopic(channel) {
505
+ return channel.startsWith(this.TopicPrefix);
506
+ }
507
+ async closeChannel(channel) {
508
+ try {
509
+ if (channel) {
510
+ await channel.close();
511
+ }
512
+ }
513
+ catch (err) {
514
+ this.Log.warn(`Error while closing AMQP channel for ${this.Options.name}: ${err?.message}`);
515
+ }
516
+ }
517
+ warnOnUnsupportedScheduling(message) {
518
+ if (message.ScheduleDelay || message.ScheduleCron || message.SchedulePeriod || message.ScheduleRepeat) {
519
+ this.Log.warn(`Message ${message.Name} has scheduling options set, but the AMQP transport does not support delayed/scheduled delivery yet. Message will be delivered immediately.`);
520
+ }
521
+ }
522
+ };
523
+ exports.AmqpQueueClient = AmqpQueueClient;
524
+ exports.AmqpQueueClient = AmqpQueueClient = __decorate([
525
+ (0, di_1.PerInstanceCheck)(),
526
+ (0, di_1.Injectable)(queue_1.QueueClient),
527
+ __metadata("design:paramtypes", [Object])
528
+ ], AmqpQueueClient);
529
+ //# sourceMappingURL=connection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection.js","sourceRoot":"","sources":["../../src/connection.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,oDAA6E;AAC7E,0CAAgI;AAChI,sDAA+F;AAC/F,oDAAuB;AACvB,oCAAwE;AACxE,wCAA2F;AAE3F;;;;;GAKG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E;oBACT,eAAe,EAAE,KAAK;oBACtB,wBAAwB,EAAE,EAAE;oBAC5B,2BAA2B,EAAE,SAAS;iBACvC;aACF,CAAC,CAAC;YACH,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAES,OAAO,CAAC,OAAe;QAC/B,OAAO,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IAC9C,CAAC;IAES,KAAK,CAAC,YAAY,CAAC,OAAkC;QAC7D,IAAI,CAAC;YACH,IAAI,OAAO,EAAE,CAAC;gBACZ,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;YACxB,CAAC;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,wCAAwC,IAAI,CAAC,OAAO,CAAC,IAAI,KAAK,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC;QAC9F,CAAC;IACH,CAAC;IAES,2BAA2B,CAAC,OAAsB;QAC1D,IAAI,OAAO,CAAC,aAAa,IAAI,OAAO,CAAC,YAAY,IAAI,OAAO,CAAC,cAAc,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC;YACtG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,OAAO,CAAC,IAAI,6IAA6I,CAAC,CAAC;QACtL,CAAC;IACH,CAAC;CACF,CAAA;AA/kBY,0CAAe;0BAAf,eAAe;IAF3B,IAAA,qBAAgB,GAAE;IAClB,IAAA,eAAU,EAAC,mBAAW,CAAC;;GACX,eAAe,CA+kB3B"}
@@ -0,0 +1,3 @@
1
+ export * from './connection-factory.js';
2
+ export * from './connection.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,iBAAiB,CAAC"}
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./connection-factory.js"), exports);
18
+ __exportStar(require("./connection.js"), exports);
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,0DAAwC;AACxC,kDAAgC"}
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=connection-factory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-factory.d.ts","sourceRoot":"","sources":["../../src/connection-factory.ts"],"names":[],"mappings":""}
@@ -0,0 +1,22 @@
1
+ import { DI } from '@spinajs/di';
2
+ import { AmqpQueueClient } from './connection.js';
3
+ import { Configuration } from '@spinajs/configuration';
4
+ /**
5
+ * Create factory func that sets client-id to connection by app name.
6
+ * We cannot have two connections with the same ID, so by default we take app-name
7
+ * with NODE_ENV and then name from options.
8
+ *
9
+ * This way we can share the same config/connections across multiple apps.
10
+ */
11
+ DI.register(async (container, options) => {
12
+ const cfg = container.get(Configuration);
13
+ const appName = cfg.get('app.name', 'no-app');
14
+ const env = cfg.get('process.env.APP_ENV', 'development');
15
+ const c = new AmqpQueueClient({
16
+ ...options,
17
+ clientId: `${appName}-${env}-${options.name}`,
18
+ });
19
+ await c.resolve();
20
+ return c;
21
+ }).as(AmqpQueueClient);
22
+ //# sourceMappingURL=connection-factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-factory.js","sourceRoot":"","sources":["../../src/connection-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAEjC,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAEvD;;;;;;GAMG;AACH,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,EAAE,OAAgC,EAAE,EAAE;IAChE,MAAM,GAAG,GAAG,SAAS,CAAC,GAAG,CAAC,aAAa,CAAE,CAAC;IAC1C,MAAM,OAAO,GAAG,GAAG,CAAC,GAAG,CAAS,UAAU,EAAE,QAAQ,CAAC,CAAC;IACtD,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAS,qBAAqB,EAAE,aAAa,CAAC,CAAC;IAElE,MAAM,CAAC,GAAG,IAAI,eAAe,CAAC;QAC5B,GAAG,OAAO;QACV,QAAQ,EAAE,GAAG,OAAO,IAAI,GAAG,IAAI,OAAO,CAAC,IAAI,EAAE;KAC9C,CAAC,CAAC;IACH,MAAM,CAAC,CAAC,OAAO,EAAE,CAAC;IAElB,OAAO,CAAC,CAAC;AACX,CAAC,CAAC,CAAC,EAAE,CAAC,eAAe,CAAC,CAAC"}