@amqp-contract/core 0.17.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +41 -15
- package/dist/index.d.cts +18 -6
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +18 -6
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +41 -16
- package/dist/index.mjs.map +1 -1
- package/docs/index.md +231 -71
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -173,6 +173,25 @@ var TechnicalError = class extends Error {
|
|
|
173
173
|
if (typeof ErrorConstructor.captureStackTrace === "function") ErrorConstructor.captureStackTrace(this, this.constructor);
|
|
174
174
|
}
|
|
175
175
|
};
|
|
176
|
+
/**
|
|
177
|
+
* Error thrown when message validation fails (payload or headers).
|
|
178
|
+
*
|
|
179
|
+
* Used by both the client (publish-time payload validation) and the worker
|
|
180
|
+
* (consume-time payload and headers validation).
|
|
181
|
+
*
|
|
182
|
+
* @param source - The name of the publisher or consumer that triggered the validation
|
|
183
|
+
* @param issues - The validation issues from the Standard Schema validation
|
|
184
|
+
*/
|
|
185
|
+
var MessageValidationError = class extends Error {
|
|
186
|
+
constructor(source, issues) {
|
|
187
|
+
super(`Message validation failed for "${source}"`);
|
|
188
|
+
this.source = source;
|
|
189
|
+
this.issues = issues;
|
|
190
|
+
this.name = "MessageValidationError";
|
|
191
|
+
const ErrorConstructor = Error;
|
|
192
|
+
if (typeof ErrorConstructor.captureStackTrace === "function") ErrorConstructor.captureStackTrace(this, this.constructor);
|
|
193
|
+
}
|
|
194
|
+
};
|
|
176
195
|
|
|
177
196
|
//#endregion
|
|
178
197
|
//#region src/setup.ts
|
|
@@ -188,7 +207,7 @@ var TechnicalError = class extends Error {
|
|
|
188
207
|
* @param channel - The AMQP channel to use for topology setup
|
|
189
208
|
* @param contract - The contract definition containing the topology specification
|
|
190
209
|
* @throws {AggregateError} If any exchanges, queues, or bindings fail to be created
|
|
191
|
-
* @throws {
|
|
210
|
+
* @throws {TechnicalError} If a queue references a dead letter exchange not declared in the contract
|
|
192
211
|
*
|
|
193
212
|
* @example
|
|
194
213
|
* ```typescript
|
|
@@ -208,7 +227,7 @@ async function setupAmqpTopology(channel, contract) {
|
|
|
208
227
|
const queue = (0, _amqp_contract_contract.extractQueue)(queueEntry);
|
|
209
228
|
if (queue.deadLetter) {
|
|
210
229
|
const dlxName = queue.deadLetter.exchange.name;
|
|
211
|
-
if (!Object.values(contract.exchanges ?? {}).some((exchange) => exchange.name === dlxName)) throw new
|
|
230
|
+
if (!Object.values(contract.exchanges ?? {}).some((exchange) => exchange.name === dlxName)) throw new TechnicalError(`Queue "${queue.name}" references dead letter exchange "${dlxName}" which is not declared in the contract. Add the exchange to contract.exchanges to ensure it is created before the queue.`);
|
|
212
231
|
}
|
|
213
232
|
}
|
|
214
233
|
const queueErrors = (await Promise.allSettled(Object.values(contract.queues ?? {}).map((queueEntry) => {
|
|
@@ -245,6 +264,20 @@ async function setupAmqpTopology(channel, contract) {
|
|
|
245
264
|
//#endregion
|
|
246
265
|
//#region src/amqp-client.ts
|
|
247
266
|
/**
|
|
267
|
+
* Invoke a SetupFunc, handling both callback-based and promise-based signatures.
|
|
268
|
+
* Uses Function.length to distinguish (same approach as promise-breaker).
|
|
269
|
+
* @internal
|
|
270
|
+
*/
|
|
271
|
+
function callSetupFunc(setup, channel) {
|
|
272
|
+
if (setup.length >= 2) return new Promise((resolve, reject) => {
|
|
273
|
+
setup(channel, (error) => {
|
|
274
|
+
if (error) reject(error);
|
|
275
|
+
else resolve();
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
return setup(channel);
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
248
281
|
* AMQP client that manages connections and channels with automatic topology setup.
|
|
249
282
|
*
|
|
250
283
|
* This class handles:
|
|
@@ -302,13 +335,7 @@ var AmqpClient = class {
|
|
|
302
335
|
};
|
|
303
336
|
if (userSetup) channelOpts.setup = async (channel) => {
|
|
304
337
|
await defaultSetup(channel);
|
|
305
|
-
|
|
306
|
-
userSetup(channel, (error) => {
|
|
307
|
-
if (error) reject(error);
|
|
308
|
-
else resolve();
|
|
309
|
-
});
|
|
310
|
-
});
|
|
311
|
-
else await userSetup(channel);
|
|
338
|
+
await callSetupFunc(userSetup, channel);
|
|
312
339
|
};
|
|
313
340
|
this.channelWrapper = this.connection.createChannel(channelOpts);
|
|
314
341
|
}
|
|
@@ -449,17 +476,15 @@ const MessagingSemanticConventions = {
|
|
|
449
476
|
MESSAGING_DESTINATION: "messaging.destination.name",
|
|
450
477
|
MESSAGING_DESTINATION_KIND: "messaging.destination.kind",
|
|
451
478
|
MESSAGING_OPERATION: "messaging.operation",
|
|
452
|
-
MESSAGING_MESSAGE_ID: "messaging.message.id",
|
|
453
|
-
MESSAGING_MESSAGE_PAYLOAD_SIZE: "messaging.message.body.size",
|
|
454
|
-
MESSAGING_MESSAGE_CONVERSATION_ID: "messaging.message.conversation_id",
|
|
455
479
|
MESSAGING_RABBITMQ_ROUTING_KEY: "messaging.rabbitmq.destination.routing_key",
|
|
456
480
|
MESSAGING_RABBITMQ_MESSAGE_DELIVERY_TAG: "messaging.rabbitmq.message.delivery_tag",
|
|
481
|
+
AMQP_PUBLISHER_NAME: "amqp.publisher.name",
|
|
482
|
+
AMQP_CONSUMER_NAME: "amqp.consumer.name",
|
|
457
483
|
ERROR_TYPE: "error.type",
|
|
458
484
|
MESSAGING_SYSTEM_RABBITMQ: "rabbitmq",
|
|
459
485
|
MESSAGING_DESTINATION_KIND_EXCHANGE: "exchange",
|
|
460
486
|
MESSAGING_DESTINATION_KIND_QUEUE: "queue",
|
|
461
487
|
MESSAGING_OPERATION_PUBLISH: "publish",
|
|
462
|
-
MESSAGING_OPERATION_RECEIVE: "receive",
|
|
463
488
|
MESSAGING_OPERATION_PROCESS: "process"
|
|
464
489
|
};
|
|
465
490
|
/**
|
|
@@ -581,7 +606,7 @@ function startConsumeSpan(provider, queueName, consumerName, attributes) {
|
|
|
581
606
|
[MessagingSemanticConventions.MESSAGING_DESTINATION]: queueName,
|
|
582
607
|
[MessagingSemanticConventions.MESSAGING_DESTINATION_KIND]: MessagingSemanticConventions.MESSAGING_DESTINATION_KIND_QUEUE,
|
|
583
608
|
[MessagingSemanticConventions.MESSAGING_OPERATION]: MessagingSemanticConventions.MESSAGING_OPERATION_PROCESS,
|
|
584
|
-
|
|
609
|
+
[MessagingSemanticConventions.AMQP_CONSUMER_NAME]: consumerName,
|
|
585
610
|
...attributes
|
|
586
611
|
}
|
|
587
612
|
});
|
|
@@ -635,7 +660,7 @@ function recordConsumeMetric(provider, queueName, consumerName, success, duratio
|
|
|
635
660
|
const attributes = {
|
|
636
661
|
[MessagingSemanticConventions.MESSAGING_SYSTEM]: MessagingSemanticConventions.MESSAGING_SYSTEM_RABBITMQ,
|
|
637
662
|
[MessagingSemanticConventions.MESSAGING_DESTINATION]: queueName,
|
|
638
|
-
|
|
663
|
+
[MessagingSemanticConventions.AMQP_CONSUMER_NAME]: consumerName,
|
|
639
664
|
success
|
|
640
665
|
};
|
|
641
666
|
consumeCounter?.add(1, attributes);
|
|
@@ -658,6 +683,7 @@ function _resetTelemetryCacheForTesting() {
|
|
|
658
683
|
//#endregion
|
|
659
684
|
exports.AmqpClient = AmqpClient;
|
|
660
685
|
exports.ConnectionManagerSingleton = ConnectionManagerSingleton;
|
|
686
|
+
exports.MessageValidationError = MessageValidationError;
|
|
661
687
|
exports.MessagingSemanticConventions = MessagingSemanticConventions;
|
|
662
688
|
exports.TechnicalError = TechnicalError;
|
|
663
689
|
exports._resetTelemetryCacheForTesting = _resetTelemetryCacheForTesting;
|
package/dist/index.d.cts
CHANGED
|
@@ -71,6 +71,20 @@ declare class TechnicalError extends Error {
|
|
|
71
71
|
readonly cause?: unknown | undefined;
|
|
72
72
|
constructor(message: string, cause?: unknown | undefined);
|
|
73
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Error thrown when message validation fails (payload or headers).
|
|
76
|
+
*
|
|
77
|
+
* Used by both the client (publish-time payload validation) and the worker
|
|
78
|
+
* (consume-time payload and headers validation).
|
|
79
|
+
*
|
|
80
|
+
* @param source - The name of the publisher or consumer that triggered the validation
|
|
81
|
+
* @param issues - The validation issues from the Standard Schema validation
|
|
82
|
+
*/
|
|
83
|
+
declare class MessageValidationError extends Error {
|
|
84
|
+
readonly source: string;
|
|
85
|
+
readonly issues: unknown;
|
|
86
|
+
constructor(source: string, issues: unknown);
|
|
87
|
+
}
|
|
74
88
|
//#endregion
|
|
75
89
|
//#region src/amqp-client.d.ts
|
|
76
90
|
/**
|
|
@@ -325,7 +339,7 @@ declare class ConnectionManagerSingleton {
|
|
|
325
339
|
* @param channel - The AMQP channel to use for topology setup
|
|
326
340
|
* @param contract - The contract definition containing the topology specification
|
|
327
341
|
* @throws {AggregateError} If any exchanges, queues, or bindings fail to be created
|
|
328
|
-
* @throws {
|
|
342
|
+
* @throws {TechnicalError} If a queue references a dead letter exchange not declared in the contract
|
|
329
343
|
*
|
|
330
344
|
* @example
|
|
331
345
|
* ```typescript
|
|
@@ -345,17 +359,15 @@ declare const MessagingSemanticConventions: {
|
|
|
345
359
|
readonly MESSAGING_DESTINATION: "messaging.destination.name";
|
|
346
360
|
readonly MESSAGING_DESTINATION_KIND: "messaging.destination.kind";
|
|
347
361
|
readonly MESSAGING_OPERATION: "messaging.operation";
|
|
348
|
-
readonly MESSAGING_MESSAGE_ID: "messaging.message.id";
|
|
349
|
-
readonly MESSAGING_MESSAGE_PAYLOAD_SIZE: "messaging.message.body.size";
|
|
350
|
-
readonly MESSAGING_MESSAGE_CONVERSATION_ID: "messaging.message.conversation_id";
|
|
351
362
|
readonly MESSAGING_RABBITMQ_ROUTING_KEY: "messaging.rabbitmq.destination.routing_key";
|
|
352
363
|
readonly MESSAGING_RABBITMQ_MESSAGE_DELIVERY_TAG: "messaging.rabbitmq.message.delivery_tag";
|
|
364
|
+
readonly AMQP_PUBLISHER_NAME: "amqp.publisher.name";
|
|
365
|
+
readonly AMQP_CONSUMER_NAME: "amqp.consumer.name";
|
|
353
366
|
readonly ERROR_TYPE: "error.type";
|
|
354
367
|
readonly MESSAGING_SYSTEM_RABBITMQ: "rabbitmq";
|
|
355
368
|
readonly MESSAGING_DESTINATION_KIND_EXCHANGE: "exchange";
|
|
356
369
|
readonly MESSAGING_DESTINATION_KIND_QUEUE: "queue";
|
|
357
370
|
readonly MESSAGING_OPERATION_PUBLISH: "publish";
|
|
358
|
-
readonly MESSAGING_OPERATION_RECEIVE: "receive";
|
|
359
371
|
readonly MESSAGING_OPERATION_PROCESS: "process";
|
|
360
372
|
};
|
|
361
373
|
/**
|
|
@@ -426,5 +438,5 @@ declare function recordConsumeMetric(provider: TelemetryProvider, queueName: str
|
|
|
426
438
|
*/
|
|
427
439
|
declare function _resetTelemetryCacheForTesting(): void;
|
|
428
440
|
//#endregion
|
|
429
|
-
export { AmqpClient, type AmqpClientOptions, ConnectionManagerSingleton, type ConsumeCallback, type Logger, type LoggerContext, MessagingSemanticConventions, TechnicalError, type TelemetryProvider, _resetTelemetryCacheForTesting, defaultTelemetryProvider, endSpanError, endSpanSuccess, recordConsumeMetric, recordPublishMetric, setupAmqpTopology, startConsumeSpan, startPublishSpan };
|
|
441
|
+
export { AmqpClient, type AmqpClientOptions, ConnectionManagerSingleton, type ConsumeCallback, type Logger, type LoggerContext, MessageValidationError, MessagingSemanticConventions, TechnicalError, type TelemetryProvider, _resetTelemetryCacheForTesting, defaultTelemetryProvider, endSpanError, endSpanSuccess, recordConsumeMetric, recordPublishMetric, setupAmqpTopology, startConsumeSpan, startPublishSpan };
|
|
430
442
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/logger.ts","../src/errors.ts","../src/amqp-client.ts","../src/connection-manager.ts","../src/setup.ts","../src/telemetry.ts"],"mappings":";;;;;;;;;;;;;;AAQA;KAAY,aAAA,GAAgB,MAAA;EAC1B,KAAA;AAAA;;AAoBF;;;;;;;;;;;;;;;;KAAY,MAAA;EAoBV;;;;;EAdA,KAAA,CAAM,OAAA,UAAiB,OAAA,GAAU,aAAA;EAqBA;;;;;EAdjC,IAAA,CAAK,OAAA,UAAiB,OAAA,GAAU,aAAA;;ACpClC;;;;ED2CE,IAAA,CAAK,OAAA,UAAiB,OAAA,GAAU,aAAA;ECxCL;;;;;ED+C3B,KAAA,CAAM,OAAA,UAAiB,OAAA,GAAU,aAAA;AAAA;;;;;;;;;cClDtB,cAAA,SAAuB,KAAA;EAAA,SAGP,KAAA;cADzB,OAAA,UACyB,KAAA;AAAA;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/logger.ts","../src/errors.ts","../src/amqp-client.ts","../src/connection-manager.ts","../src/setup.ts","../src/telemetry.ts"],"mappings":";;;;;;;;;;;;;;AAQA;KAAY,aAAA,GAAgB,MAAA;EAC1B,KAAA;AAAA;;AAoBF;;;;;;;;;;;;;;;;KAAY,MAAA;EAoBV;;;;;EAdA,KAAA,CAAM,OAAA,UAAiB,OAAA,GAAU,aAAA;EAqBA;;;;;EAdjC,IAAA,CAAK,OAAA,UAAiB,OAAA,GAAU,aAAA;;ACpClC;;;;ED2CE,IAAA,CAAK,OAAA,UAAiB,OAAA,GAAU,aAAA;ECxCL;;;;;ED+C3B,KAAA,CAAM,OAAA,UAAiB,OAAA,GAAU,aAAA;AAAA;;;;;;;;;cClDtB,cAAA,SAAuB,KAAA;EAAA,SAGP,KAAA;cADzB,OAAA,UACyB,KAAA;AAAA;;;ADoB7B;;;;;;;cCGa,sBAAA,SAA+B,KAAA;EAAA,SAExB,MAAA;EAAA,SACA,MAAA;cADA,MAAA,UACA,MAAA;AAAA;;;;;AD3BpB;;;;;KEoCY,iBAAA;EACV,IAAA,EAAM,aAAA;EACN,iBAAA,GAAoB,4BAAA;EACpB,cAAA,GAAiB,OAAA,CAAQ,iBAAA;AAAA;;;;K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QAAA,EAAU,iBAAA,EACV,YAAA,UACA,UAAA,sBACA,OAAA,WACA,UAAA;;;;iBAsBc,mBAAA,CACd,QAAA,EAAU,iBAAA,EACV,SAAA,UACA,YAAA,UACA,OAAA,WACA,UAAA;;;;;AH3RF;iBGiTgB,8BAAA,CAAA"}
|
package/dist/index.d.mts
CHANGED
|
@@ -71,6 +71,20 @@ declare class TechnicalError extends Error {
|
|
|
71
71
|
readonly cause?: unknown | undefined;
|
|
72
72
|
constructor(message: string, cause?: unknown | undefined);
|
|
73
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Error thrown when message validation fails (payload or headers).
|
|
76
|
+
*
|
|
77
|
+
* Used by both the client (publish-time payload validation) and the worker
|
|
78
|
+
* (consume-time payload and headers validation).
|
|
79
|
+
*
|
|
80
|
+
* @param source - The name of the publisher or consumer that triggered the validation
|
|
81
|
+
* @param issues - The validation issues from the Standard Schema validation
|
|
82
|
+
*/
|
|
83
|
+
declare class MessageValidationError extends Error {
|
|
84
|
+
readonly source: string;
|
|
85
|
+
readonly issues: unknown;
|
|
86
|
+
constructor(source: string, issues: unknown);
|
|
87
|
+
}
|
|
74
88
|
//#endregion
|
|
75
89
|
//#region src/amqp-client.d.ts
|
|
76
90
|
/**
|
|
@@ -325,7 +339,7 @@ declare class ConnectionManagerSingleton {
|
|
|
325
339
|
* @param channel - The AMQP channel to use for topology setup
|
|
326
340
|
* @param contract - The contract definition containing the topology specification
|
|
327
341
|
* @throws {AggregateError} If any exchanges, queues, or bindings fail to be created
|
|
328
|
-
* @throws {
|
|
342
|
+
* @throws {TechnicalError} If a queue references a dead letter exchange not declared in the contract
|
|
329
343
|
*
|
|
330
344
|
* @example
|
|
331
345
|
* ```typescript
|
|
@@ -345,17 +359,15 @@ declare const MessagingSemanticConventions: {
|
|
|
345
359
|
readonly MESSAGING_DESTINATION: "messaging.destination.name";
|
|
346
360
|
readonly MESSAGING_DESTINATION_KIND: "messaging.destination.kind";
|
|
347
361
|
readonly MESSAGING_OPERATION: "messaging.operation";
|
|
348
|
-
readonly MESSAGING_MESSAGE_ID: "messaging.message.id";
|
|
349
|
-
readonly MESSAGING_MESSAGE_PAYLOAD_SIZE: "messaging.message.body.size";
|
|
350
|
-
readonly MESSAGING_MESSAGE_CONVERSATION_ID: "messaging.message.conversation_id";
|
|
351
362
|
readonly MESSAGING_RABBITMQ_ROUTING_KEY: "messaging.rabbitmq.destination.routing_key";
|
|
352
363
|
readonly MESSAGING_RABBITMQ_MESSAGE_DELIVERY_TAG: "messaging.rabbitmq.message.delivery_tag";
|
|
364
|
+
readonly AMQP_PUBLISHER_NAME: "amqp.publisher.name";
|
|
365
|
+
readonly AMQP_CONSUMER_NAME: "amqp.consumer.name";
|
|
353
366
|
readonly ERROR_TYPE: "error.type";
|
|
354
367
|
readonly MESSAGING_SYSTEM_RABBITMQ: "rabbitmq";
|
|
355
368
|
readonly MESSAGING_DESTINATION_KIND_EXCHANGE: "exchange";
|
|
356
369
|
readonly MESSAGING_DESTINATION_KIND_QUEUE: "queue";
|
|
357
370
|
readonly MESSAGING_OPERATION_PUBLISH: "publish";
|
|
358
|
-
readonly MESSAGING_OPERATION_RECEIVE: "receive";
|
|
359
371
|
readonly MESSAGING_OPERATION_PROCESS: "process";
|
|
360
372
|
};
|
|
361
373
|
/**
|
|
@@ -426,5 +438,5 @@ declare function recordConsumeMetric(provider: TelemetryProvider, queueName: str
|
|
|
426
438
|
*/
|
|
427
439
|
declare function _resetTelemetryCacheForTesting(): void;
|
|
428
440
|
//#endregion
|
|
429
|
-
export { AmqpClient, type AmqpClientOptions, ConnectionManagerSingleton, type ConsumeCallback, type Logger, type LoggerContext, MessagingSemanticConventions, TechnicalError, type TelemetryProvider, _resetTelemetryCacheForTesting, defaultTelemetryProvider, endSpanError, endSpanSuccess, recordConsumeMetric, recordPublishMetric, setupAmqpTopology, startConsumeSpan, startPublishSpan };
|
|
441
|
+
export { AmqpClient, type AmqpClientOptions, ConnectionManagerSingleton, type ConsumeCallback, type Logger, type LoggerContext, MessageValidationError, MessagingSemanticConventions, TechnicalError, type TelemetryProvider, _resetTelemetryCacheForTesting, defaultTelemetryProvider, endSpanError, endSpanSuccess, recordConsumeMetric, recordPublishMetric, setupAmqpTopology, startConsumeSpan, startPublishSpan };
|
|
430
442
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/logger.ts","../src/errors.ts","../src/amqp-client.ts","../src/connection-manager.ts","../src/setup.ts","../src/telemetry.ts"],"mappings":";;;;;;;;;;;;;;AAQA;KAAY,aAAA,GAAgB,MAAA;EAC1B,KAAA;AAAA;;AAoBF;;;;;;;;;;;;;;;;KAAY,MAAA;EAoBV;;;;;EAdA,KAAA,CAAM,OAAA,UAAiB,OAAA,GAAU,aAAA;EAqBA;;;;;EAdjC,IAAA,CAAK,OAAA,UAAiB,OAAA,GAAU,aAAA;;ACpClC;;;;ED2CE,IAAA,CAAK,OAAA,UAAiB,OAAA,GAAU,aAAA;ECxCL;;;;;ED+C3B,KAAA,CAAM,OAAA,UAAiB,OAAA,GAAU,aAAA;AAAA;;;;;;;;;cClDtB,cAAA,SAAuB,KAAA;EAAA,SAGP,KAAA;cADzB,OAAA,UACyB,KAAA;AAAA;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/logger.ts","../src/errors.ts","../src/amqp-client.ts","../src/connection-manager.ts","../src/setup.ts","../src/telemetry.ts"],"mappings":";;;;;;;;;;;;;;AAQA;KAAY,aAAA,GAAgB,MAAA;EAC1B,KAAA;AAAA;;AAoBF;;;;;;;;;;;;;;;;KAAY,MAAA;EAoBV;;;;;EAdA,KAAA,CAAM,OAAA,UAAiB,OAAA,GAAU,aAAA;EAqBA;;;;;EAdjC,IAAA,CAAK,OAAA,UAAiB,OAAA,GAAU,aAAA;;ACpClC;;;;ED2CE,IAAA,CAAK,OAAA,UAAiB,OAAA,GAAU,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C,SAAA;AAAA;;AJjDpC;;cIiKa,wBAAA,EAA0B,iBAAA;;;;;iBAYvB,gBAAA,CACd,QAAA,EAAU,iBAAA,EACV,YAAA,UACA,UAAA,sBACA,UAAA,GAAa,UAAA,GACZ,IAAA;;;;;iBA8Ba,gBAAA,CACd,QAAA,EAAU,iBAAA,EACV,SAAA,UACA,YAAA,UACA,UAAA,GAAa,UAAA,GACZ,IAAA;;;AHzMH;iBGoOgB,cAAA,CAAe,IAAA,EAAM,IAAA;;;;iBAerB,YAAA,CAAa,IAAA,EAAM,IAAA,cAAkB,KAAA,EAAO,KAAA;;;;iBAiB5C,mBAAA,CACd,QAAA,EAAU,iBAAA,EACV,YAAA,UACA,UAAA,sBACA,OAAA,WACA,UAAA;;;;iBAsBc,mBAAA,CACd,QAAA,EAAU,iBAAA,EACV,SAAA,UACA,YAAA,UACA,OAAA,WACA,UAAA;;;;;AH3RF;iBGiTgB,8BAAA,CAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -149,6 +149,25 @@ var TechnicalError = class extends Error {
|
|
|
149
149
|
if (typeof ErrorConstructor.captureStackTrace === "function") ErrorConstructor.captureStackTrace(this, this.constructor);
|
|
150
150
|
}
|
|
151
151
|
};
|
|
152
|
+
/**
|
|
153
|
+
* Error thrown when message validation fails (payload or headers).
|
|
154
|
+
*
|
|
155
|
+
* Used by both the client (publish-time payload validation) and the worker
|
|
156
|
+
* (consume-time payload and headers validation).
|
|
157
|
+
*
|
|
158
|
+
* @param source - The name of the publisher or consumer that triggered the validation
|
|
159
|
+
* @param issues - The validation issues from the Standard Schema validation
|
|
160
|
+
*/
|
|
161
|
+
var MessageValidationError = class extends Error {
|
|
162
|
+
constructor(source, issues) {
|
|
163
|
+
super(`Message validation failed for "${source}"`);
|
|
164
|
+
this.source = source;
|
|
165
|
+
this.issues = issues;
|
|
166
|
+
this.name = "MessageValidationError";
|
|
167
|
+
const ErrorConstructor = Error;
|
|
168
|
+
if (typeof ErrorConstructor.captureStackTrace === "function") ErrorConstructor.captureStackTrace(this, this.constructor);
|
|
169
|
+
}
|
|
170
|
+
};
|
|
152
171
|
|
|
153
172
|
//#endregion
|
|
154
173
|
//#region src/setup.ts
|
|
@@ -164,7 +183,7 @@ var TechnicalError = class extends Error {
|
|
|
164
183
|
* @param channel - The AMQP channel to use for topology setup
|
|
165
184
|
* @param contract - The contract definition containing the topology specification
|
|
166
185
|
* @throws {AggregateError} If any exchanges, queues, or bindings fail to be created
|
|
167
|
-
* @throws {
|
|
186
|
+
* @throws {TechnicalError} If a queue references a dead letter exchange not declared in the contract
|
|
168
187
|
*
|
|
169
188
|
* @example
|
|
170
189
|
* ```typescript
|
|
@@ -184,7 +203,7 @@ async function setupAmqpTopology(channel, contract) {
|
|
|
184
203
|
const queue = extractQueue(queueEntry);
|
|
185
204
|
if (queue.deadLetter) {
|
|
186
205
|
const dlxName = queue.deadLetter.exchange.name;
|
|
187
|
-
if (!Object.values(contract.exchanges ?? {}).some((exchange) => exchange.name === dlxName)) throw new
|
|
206
|
+
if (!Object.values(contract.exchanges ?? {}).some((exchange) => exchange.name === dlxName)) throw new TechnicalError(`Queue "${queue.name}" references dead letter exchange "${dlxName}" which is not declared in the contract. Add the exchange to contract.exchanges to ensure it is created before the queue.`);
|
|
188
207
|
}
|
|
189
208
|
}
|
|
190
209
|
const queueErrors = (await Promise.allSettled(Object.values(contract.queues ?? {}).map((queueEntry) => {
|
|
@@ -221,6 +240,20 @@ async function setupAmqpTopology(channel, contract) {
|
|
|
221
240
|
//#endregion
|
|
222
241
|
//#region src/amqp-client.ts
|
|
223
242
|
/**
|
|
243
|
+
* Invoke a SetupFunc, handling both callback-based and promise-based signatures.
|
|
244
|
+
* Uses Function.length to distinguish (same approach as promise-breaker).
|
|
245
|
+
* @internal
|
|
246
|
+
*/
|
|
247
|
+
function callSetupFunc(setup, channel) {
|
|
248
|
+
if (setup.length >= 2) return new Promise((resolve, reject) => {
|
|
249
|
+
setup(channel, (error) => {
|
|
250
|
+
if (error) reject(error);
|
|
251
|
+
else resolve();
|
|
252
|
+
});
|
|
253
|
+
});
|
|
254
|
+
return setup(channel);
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
224
257
|
* AMQP client that manages connections and channels with automatic topology setup.
|
|
225
258
|
*
|
|
226
259
|
* This class handles:
|
|
@@ -278,13 +311,7 @@ var AmqpClient = class {
|
|
|
278
311
|
};
|
|
279
312
|
if (userSetup) channelOpts.setup = async (channel) => {
|
|
280
313
|
await defaultSetup(channel);
|
|
281
|
-
|
|
282
|
-
userSetup(channel, (error) => {
|
|
283
|
-
if (error) reject(error);
|
|
284
|
-
else resolve();
|
|
285
|
-
});
|
|
286
|
-
});
|
|
287
|
-
else await userSetup(channel);
|
|
314
|
+
await callSetupFunc(userSetup, channel);
|
|
288
315
|
};
|
|
289
316
|
this.channelWrapper = this.connection.createChannel(channelOpts);
|
|
290
317
|
}
|
|
@@ -425,17 +452,15 @@ const MessagingSemanticConventions = {
|
|
|
425
452
|
MESSAGING_DESTINATION: "messaging.destination.name",
|
|
426
453
|
MESSAGING_DESTINATION_KIND: "messaging.destination.kind",
|
|
427
454
|
MESSAGING_OPERATION: "messaging.operation",
|
|
428
|
-
MESSAGING_MESSAGE_ID: "messaging.message.id",
|
|
429
|
-
MESSAGING_MESSAGE_PAYLOAD_SIZE: "messaging.message.body.size",
|
|
430
|
-
MESSAGING_MESSAGE_CONVERSATION_ID: "messaging.message.conversation_id",
|
|
431
455
|
MESSAGING_RABBITMQ_ROUTING_KEY: "messaging.rabbitmq.destination.routing_key",
|
|
432
456
|
MESSAGING_RABBITMQ_MESSAGE_DELIVERY_TAG: "messaging.rabbitmq.message.delivery_tag",
|
|
457
|
+
AMQP_PUBLISHER_NAME: "amqp.publisher.name",
|
|
458
|
+
AMQP_CONSUMER_NAME: "amqp.consumer.name",
|
|
433
459
|
ERROR_TYPE: "error.type",
|
|
434
460
|
MESSAGING_SYSTEM_RABBITMQ: "rabbitmq",
|
|
435
461
|
MESSAGING_DESTINATION_KIND_EXCHANGE: "exchange",
|
|
436
462
|
MESSAGING_DESTINATION_KIND_QUEUE: "queue",
|
|
437
463
|
MESSAGING_OPERATION_PUBLISH: "publish",
|
|
438
|
-
MESSAGING_OPERATION_RECEIVE: "receive",
|
|
439
464
|
MESSAGING_OPERATION_PROCESS: "process"
|
|
440
465
|
};
|
|
441
466
|
/**
|
|
@@ -557,7 +582,7 @@ function startConsumeSpan(provider, queueName, consumerName, attributes) {
|
|
|
557
582
|
[MessagingSemanticConventions.MESSAGING_DESTINATION]: queueName,
|
|
558
583
|
[MessagingSemanticConventions.MESSAGING_DESTINATION_KIND]: MessagingSemanticConventions.MESSAGING_DESTINATION_KIND_QUEUE,
|
|
559
584
|
[MessagingSemanticConventions.MESSAGING_OPERATION]: MessagingSemanticConventions.MESSAGING_OPERATION_PROCESS,
|
|
560
|
-
|
|
585
|
+
[MessagingSemanticConventions.AMQP_CONSUMER_NAME]: consumerName,
|
|
561
586
|
...attributes
|
|
562
587
|
}
|
|
563
588
|
});
|
|
@@ -611,7 +636,7 @@ function recordConsumeMetric(provider, queueName, consumerName, success, duratio
|
|
|
611
636
|
const attributes = {
|
|
612
637
|
[MessagingSemanticConventions.MESSAGING_SYSTEM]: MessagingSemanticConventions.MESSAGING_SYSTEM_RABBITMQ,
|
|
613
638
|
[MessagingSemanticConventions.MESSAGING_DESTINATION]: queueName,
|
|
614
|
-
|
|
639
|
+
[MessagingSemanticConventions.AMQP_CONSUMER_NAME]: consumerName,
|
|
615
640
|
success
|
|
616
641
|
};
|
|
617
642
|
consumeCounter?.add(1, attributes);
|
|
@@ -632,5 +657,5 @@ function _resetTelemetryCacheForTesting() {
|
|
|
632
657
|
}
|
|
633
658
|
|
|
634
659
|
//#endregion
|
|
635
|
-
export { AmqpClient, ConnectionManagerSingleton, MessagingSemanticConventions, TechnicalError, _resetTelemetryCacheForTesting, defaultTelemetryProvider, endSpanError, endSpanSuccess, recordConsumeMetric, recordPublishMetric, setupAmqpTopology, startConsumeSpan, startPublishSpan };
|
|
660
|
+
export { AmqpClient, ConnectionManagerSingleton, MessageValidationError, MessagingSemanticConventions, TechnicalError, _resetTelemetryCacheForTesting, defaultTelemetryProvider, endSpanError, endSpanSuccess, recordConsumeMetric, recordPublishMetric, setupAmqpTopology, startConsumeSpan, startPublishSpan };
|
|
636
661
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/connection-manager.ts","../src/errors.ts","../src/setup.ts","../src/amqp-client.ts","../src/telemetry.ts"],"sourcesContent":["import amqp, {\n AmqpConnectionManager,\n AmqpConnectionManagerOptions,\n ConnectionUrl,\n} from \"amqp-connection-manager\";\n\n/**\n * Connection manager singleton for sharing AMQP connections across clients.\n *\n * This singleton implements connection pooling to avoid creating multiple connections\n * to the same broker, which is a RabbitMQ best practice. Connections are identified\n * by their URLs and connection options, and reference counting ensures connections\n * are only closed when all clients have released them.\n *\n * @example\n * ```typescript\n * const manager = ConnectionManagerSingleton.getInstance();\n * const connection = manager.getConnection(['amqp://localhost']);\n * // ... use connection ...\n * await manager.releaseConnection(['amqp://localhost']);\n * ```\n */\nexport class ConnectionManagerSingleton {\n private static instance: ConnectionManagerSingleton;\n private connections: Map<string, AmqpConnectionManager> = new Map();\n private refCounts: Map<string, number> = new Map();\n\n private constructor() {}\n\n /**\n * Get the singleton instance of the connection manager.\n *\n * @returns The singleton instance\n */\n static getInstance(): ConnectionManagerSingleton {\n if (!ConnectionManagerSingleton.instance) {\n ConnectionManagerSingleton.instance = new ConnectionManagerSingleton();\n }\n return ConnectionManagerSingleton.instance;\n }\n\n /**\n * Get or create a connection for the given URLs and options.\n *\n * If a connection already exists with the same URLs and options, it is reused\n * and its reference count is incremented. Otherwise, a new connection is created.\n *\n * @param urls - AMQP broker URL(s)\n * @param connectionOptions - Optional connection configuration\n * @returns The AMQP connection manager instance\n */\n getConnection(\n urls: ConnectionUrl[],\n connectionOptions?: AmqpConnectionManagerOptions,\n ): AmqpConnectionManager {\n // Create a key based on URLs and connection options\n const key = this.createConnectionKey(urls, connectionOptions);\n\n if (!this.connections.has(key)) {\n const connection = amqp.connect(urls, connectionOptions);\n this.connections.set(key, connection);\n this.refCounts.set(key, 0);\n }\n\n // Increment reference count\n this.refCounts.set(key, (this.refCounts.get(key) ?? 0) + 1);\n\n return this.connections.get(key)!;\n }\n\n /**\n * Release a connection reference.\n *\n * Decrements the reference count for the connection. If the count reaches zero,\n * the connection is closed and removed from the pool.\n *\n * @param urls - AMQP broker URL(s) used to identify the connection\n * @param connectionOptions - Optional connection configuration used to identify the connection\n * @returns A promise that resolves when the connection is released (and closed if necessary)\n */\n async releaseConnection(\n urls: ConnectionUrl[],\n connectionOptions?: AmqpConnectionManagerOptions,\n ): Promise<void> {\n const key = this.createConnectionKey(urls, connectionOptions);\n const refCount = this.refCounts.get(key) ?? 0;\n\n if (refCount <= 1) {\n // Last reference - close and remove connection\n const connection = this.connections.get(key);\n if (connection) {\n await connection.close();\n this.connections.delete(key);\n this.refCounts.delete(key);\n }\n } else {\n // Decrement reference count\n this.refCounts.set(key, refCount - 1);\n }\n }\n\n /**\n * Create a unique key for a connection based on URLs and options.\n *\n * The key is deterministic: same URLs and options always produce the same key,\n * enabling connection reuse.\n *\n * @param urls - AMQP broker URL(s)\n * @param connectionOptions - Optional connection configuration\n * @returns A unique string key identifying the connection\n */\n private createConnectionKey(\n urls: ConnectionUrl[],\n connectionOptions?: AmqpConnectionManagerOptions,\n ): string {\n // Create a deterministic key from URLs and options\n // Use JSON.stringify for URLs to avoid ambiguity (e.g., ['a,b'] vs ['a', 'b'])\n const urlsStr = JSON.stringify(urls);\n // Sort object keys for deterministic serialization of connection options\n const optsStr = connectionOptions ? this.serializeOptions(connectionOptions) : \"\";\n return `${urlsStr}::${optsStr}`;\n }\n\n /**\n * Serialize connection options to a deterministic string.\n *\n * @param options - Connection options to serialize\n * @returns A JSON string with sorted keys for deterministic comparison\n */\n private serializeOptions(options: AmqpConnectionManagerOptions): string {\n // Create a deterministic string representation by deeply sorting all object keys\n const sorted = this.deepSort(options);\n return JSON.stringify(sorted);\n }\n\n /**\n * Deep sort an object's keys for deterministic serialization.\n *\n * @param value - The value to deep sort (can be object, array, or primitive)\n * @returns The value with all object keys sorted alphabetically\n */\n private deepSort(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => this.deepSort(item));\n }\n\n if (value !== null && typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n const sortedKeys = Object.keys(obj).sort();\n const result: Record<string, unknown> = {};\n\n for (const key of sortedKeys) {\n result[key] = this.deepSort(obj[key]);\n }\n\n return result;\n }\n\n return value;\n }\n\n /**\n * Reset all cached connections (for testing purposes)\n * @internal\n */\n async _resetForTesting(): Promise<void> {\n // Close all connections before clearing\n const closePromises = Array.from(this.connections.values()).map((conn) => conn.close());\n await Promise.all(closePromises);\n this.connections.clear();\n this.refCounts.clear();\n }\n}\n","/**\n * Error for technical/runtime failures that cannot be prevented by TypeScript.\n *\n * This includes AMQP connection failures, channel issues, validation failures,\n * and other runtime errors. This error is shared across core, worker, and client packages.\n */\nexport class TechnicalError extends Error {\n constructor(\n message: string,\n public override readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"TechnicalError\";\n // Node.js specific stack trace capture\n const ErrorConstructor = Error as unknown as {\n captureStackTrace?: (target: object, constructor: Function) => void;\n };\n if (typeof ErrorConstructor.captureStackTrace === \"function\") {\n ErrorConstructor.captureStackTrace(this, this.constructor);\n }\n }\n}\n","import type { Channel } from \"amqplib\";\nimport type { ContractDefinition } from \"@amqp-contract/contract\";\nimport { extractQueue } from \"@amqp-contract/contract\";\n\n/**\n * Setup AMQP topology (exchanges, queues, and bindings) from a contract definition.\n *\n * This function sets up the complete AMQP topology in the correct order:\n * 1. Assert all exchanges defined in the contract\n * 2. Validate dead letter exchanges are declared before referencing them\n * 3. Assert all queues with their configurations (including dead letter settings)\n * 4. Create all bindings (queue-to-exchange and exchange-to-exchange)\n *\n * @param channel - The AMQP channel to use for topology setup\n * @param contract - The contract definition containing the topology specification\n * @throws {AggregateError} If any exchanges, queues, or bindings fail to be created\n * @throws {Error} If a queue references a dead letter exchange not declared in the contract\n *\n * @example\n * ```typescript\n * const channel = await connection.createChannel();\n * await setupAmqpTopology(channel, contract);\n * ```\n */\nexport async function setupAmqpTopology(\n channel: Channel,\n contract: ContractDefinition,\n): Promise<void> {\n // Setup exchanges\n const exchangeResults = await Promise.allSettled(\n Object.values(contract.exchanges ?? {}).map((exchange) =>\n channel.assertExchange(exchange.name, exchange.type, {\n durable: exchange.durable,\n autoDelete: exchange.autoDelete,\n internal: exchange.internal,\n arguments: exchange.arguments,\n }),\n ),\n );\n const exchangeErrors = exchangeResults.filter(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (exchangeErrors.length > 0) {\n throw new AggregateError(\n exchangeErrors.map(({ reason }) => reason),\n \"Failed to setup exchanges\",\n );\n }\n\n // Validate dead letter exchanges before setting up queues\n for (const queueEntry of Object.values(contract.queues ?? {})) {\n const queue = extractQueue(queueEntry);\n if (queue.deadLetter) {\n const dlxName = queue.deadLetter.exchange.name;\n const exchangeExists = Object.values(contract.exchanges ?? {}).some(\n (exchange) => exchange.name === dlxName,\n );\n\n if (!exchangeExists) {\n throw new Error(\n `Queue \"${queue.name}\" references dead letter exchange \"${dlxName}\" which is not declared in the contract. ` +\n `Add the exchange to contract.exchanges to ensure it is created before the queue.`,\n );\n }\n }\n }\n\n // Setup queues\n const queueResults = await Promise.allSettled(\n Object.values(contract.queues ?? {}).map((queueEntry) => {\n const queue = extractQueue(queueEntry);\n // Build queue arguments, merging dead letter configuration and queue type\n const queueArguments: Record<string, unknown> = { ...queue.arguments };\n\n // Set queue type\n queueArguments[\"x-queue-type\"] = queue.type;\n\n if (queue.deadLetter) {\n queueArguments[\"x-dead-letter-exchange\"] = queue.deadLetter.exchange.name;\n if (queue.deadLetter.routingKey) {\n queueArguments[\"x-dead-letter-routing-key\"] = queue.deadLetter.routingKey;\n }\n }\n\n // Handle type-specific properties using discriminated union\n if (queue.type === \"quorum\") {\n // Set delivery limit for quorum queues (native retry support)\n if (queue.deliveryLimit !== undefined) {\n queueArguments[\"x-delivery-limit\"] = queue.deliveryLimit;\n }\n\n // Quorum queues are always durable\n return channel.assertQueue(queue.name, {\n durable: true,\n autoDelete: queue.autoDelete,\n arguments: queueArguments,\n });\n }\n\n // Classic queue\n return channel.assertQueue(queue.name, {\n durable: queue.durable,\n exclusive: queue.exclusive,\n autoDelete: queue.autoDelete,\n arguments: queueArguments,\n });\n }),\n );\n const queueErrors = queueResults.filter(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (queueErrors.length > 0) {\n throw new AggregateError(\n queueErrors.map(({ reason }) => reason),\n \"Failed to setup queues\",\n );\n }\n\n // Setup bindings\n const bindingResults = await Promise.allSettled(\n Object.values(contract.bindings ?? {}).map((binding) => {\n if (binding.type === \"queue\") {\n return channel.bindQueue(\n binding.queue.name,\n binding.exchange.name,\n binding.routingKey ?? \"\",\n binding.arguments,\n );\n }\n\n return channel.bindExchange(\n binding.destination.name,\n binding.source.name,\n binding.routingKey ?? \"\",\n binding.arguments,\n );\n }),\n );\n const bindingErrors = bindingResults.filter(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (bindingErrors.length > 0) {\n throw new AggregateError(\n bindingErrors.map(({ reason }) => reason),\n \"Failed to setup bindings\",\n );\n }\n}\n","import type {\n AmqpConnectionManager,\n AmqpConnectionManagerOptions,\n ChannelWrapper,\n ConnectionUrl,\n CreateChannelOpts,\n} from \"amqp-connection-manager\";\nimport type { Channel, ConsumeMessage, Options } from \"amqplib\";\nimport { Future, Result } from \"@swan-io/boxed\";\nimport { ConnectionManagerSingleton } from \"./connection-manager.js\";\nimport type { ContractDefinition } from \"@amqp-contract/contract\";\nimport { TechnicalError } from \"./errors.js\";\nimport { setupAmqpTopology } from \"./setup.js\";\n\n/**\n * Options for creating an AMQP client.\n *\n * @property urls - AMQP broker URL(s). Multiple URLs provide failover support.\n * @property connectionOptions - Optional connection configuration (heartbeat, reconnect settings, etc.).\n * @property channelOptions - Optional channel configuration options.\n */\nexport type AmqpClientOptions = {\n urls: ConnectionUrl[];\n connectionOptions?: AmqpConnectionManagerOptions | undefined;\n channelOptions?: Partial<CreateChannelOpts> | undefined;\n};\n\n/**\n * Callback type for consuming messages.\n */\nexport type ConsumeCallback = (msg: ConsumeMessage | null) => void | Promise<void>;\n\n/**\n * AMQP client that manages connections and channels with automatic topology setup.\n *\n * This class handles:\n * - Connection management with automatic reconnection via amqp-connection-manager\n * - Connection pooling and sharing across instances with the same URLs\n * - Automatic AMQP topology setup (exchanges, queues, bindings) from contract\n * - Channel creation with JSON serialization enabled by default\n *\n * All operations return `Future<Result<T, TechnicalError>>` for consistent error handling.\n *\n * @example\n * ```typescript\n * const client = new AmqpClient(contract, {\n * urls: ['amqp://localhost'],\n * connectionOptions: { heartbeatIntervalInSeconds: 30 }\n * });\n *\n * // Wait for connection\n * await client.waitForConnect().resultToPromise();\n *\n * // Publish a message\n * const result = await client.publish('exchange', 'routingKey', { data: 'value' }).resultToPromise();\n *\n * // Close when done\n * await client.close().resultToPromise();\n * ```\n */\nexport class AmqpClient {\n private readonly connection: AmqpConnectionManager;\n private readonly channelWrapper: ChannelWrapper;\n private readonly urls: ConnectionUrl[];\n private readonly connectionOptions?: AmqpConnectionManagerOptions;\n\n /**\n * Create a new AMQP client instance.\n *\n * The client will automatically:\n * - Get or create a shared connection using the singleton pattern\n * - Set up AMQP topology (exchanges, queues, bindings) from the contract\n * - Create a channel with JSON serialization enabled\n *\n * @param contract - The contract definition specifying the AMQP topology\n * @param options - Client configuration options\n */\n constructor(\n private readonly contract: ContractDefinition,\n options: AmqpClientOptions,\n ) {\n // Store for cleanup\n this.urls = options.urls;\n if (options.connectionOptions !== undefined) {\n this.connectionOptions = options.connectionOptions;\n }\n\n // Always use singleton to get/create connection\n const singleton = ConnectionManagerSingleton.getInstance();\n this.connection = singleton.getConnection(options.urls, options.connectionOptions);\n\n // Create default setup function that calls setupAmqpTopology\n const defaultSetup = (channel: Channel) => setupAmqpTopology(channel, this.contract);\n\n // Destructure setup from channelOptions to handle it separately\n const { setup: userSetup, ...otherChannelOptions } = options.channelOptions ?? {};\n\n // Merge user-provided channel options with defaults\n const channelOpts: CreateChannelOpts = {\n json: true,\n setup: defaultSetup,\n ...otherChannelOptions,\n };\n\n // If user provided a custom setup, wrap it to call both\n if (userSetup) {\n channelOpts.setup = async (channel: Channel) => {\n // First run the topology setup\n await defaultSetup(channel);\n // Then run user's setup - check arity to determine if it expects a callback\n if (userSetup.length === 2) {\n // Callback-based setup function\n await new Promise<void>((resolve, reject) => {\n (userSetup as (channel: Channel, callback: (error?: Error) => void) => void)(\n channel,\n (error?: Error) => {\n if (error) reject(error);\n else resolve();\n },\n );\n });\n } else {\n // Promise-based setup function\n await (userSetup as (channel: Channel) => Promise<void>)(channel);\n }\n };\n }\n\n this.channelWrapper = this.connection.createChannel(channelOpts);\n }\n\n /**\n * Get the underlying connection manager\n *\n * This method exposes the AmqpConnectionManager instance that this client uses.\n * The connection is automatically shared across all AmqpClient instances that\n * use the same URLs and connection options.\n *\n * @returns The AmqpConnectionManager instance used by this client\n */\n getConnection(): AmqpConnectionManager {\n return this.connection;\n }\n\n /**\n * Wait for the channel to be connected and ready.\n *\n * @returns A Future that resolves when the channel is connected\n */\n waitForConnect(): Future<Result<void, TechnicalError>> {\n return Future.fromPromise(this.channelWrapper.waitForConnect()).mapError(\n (error: unknown) => new TechnicalError(\"Failed to connect to AMQP broker\", error),\n );\n }\n\n /**\n * Publish a message to an exchange.\n *\n * @param exchange - The exchange name\n * @param routingKey - The routing key\n * @param content - The message content (will be JSON serialized if json: true)\n * @param options - Optional publish options\n * @returns A Future with `Result<boolean>` - true if message was sent, false if channel buffer is full\n */\n publish(\n exchange: string,\n routingKey: string,\n content: Buffer | unknown,\n options?: Options.Publish,\n ): Future<Result<boolean, TechnicalError>> {\n return Future.fromPromise(\n this.channelWrapper.publish(exchange, routingKey, content, options),\n ).mapError((error: unknown) => new TechnicalError(\"Failed to publish message\", error));\n }\n\n /**\n * Start consuming messages from a queue.\n *\n * @param queue - The queue name\n * @param callback - The callback to invoke for each message\n * @param options - Optional consume options\n * @returns A Future with `Result<string>` - the consumer tag\n */\n consume(\n queue: string,\n callback: ConsumeCallback,\n options?: Options.Consume,\n ): Future<Result<string, TechnicalError>> {\n return Future.fromPromise(this.channelWrapper.consume(queue, callback, options))\n .mapError((error: unknown) => new TechnicalError(\"Failed to start consuming messages\", error))\n .mapOk((reply: { consumerTag: string }) => reply.consumerTag);\n }\n\n /**\n * Cancel a consumer by its consumer tag.\n *\n * @param consumerTag - The consumer tag to cancel\n * @returns A Future that resolves when the consumer is cancelled\n */\n cancel(consumerTag: string): Future<Result<void, TechnicalError>> {\n return Future.fromPromise(this.channelWrapper.cancel(consumerTag))\n .mapError((error: unknown) => new TechnicalError(\"Failed to cancel consumer\", error))\n .mapOk(() => undefined);\n }\n\n /**\n * Acknowledge a message.\n *\n * @param msg - The message to acknowledge\n * @param allUpTo - If true, acknowledge all messages up to and including this one\n */\n ack(msg: ConsumeMessage, allUpTo = false): void {\n this.channelWrapper.ack(msg, allUpTo);\n }\n\n /**\n * Negative acknowledge a message.\n *\n * @param msg - The message to nack\n * @param allUpTo - If true, nack all messages up to and including this one\n * @param requeue - If true, requeue the message(s)\n */\n nack(msg: ConsumeMessage, allUpTo = false, requeue = true): void {\n this.channelWrapper.nack(msg, allUpTo, requeue);\n }\n\n /**\n * Add a setup function to be called when the channel is created or reconnected.\n *\n * This is useful for setting up channel-level configuration like prefetch.\n *\n * @param setup - The setup function to add\n */\n addSetup(setup: (channel: Channel) => void | Promise<void>): void {\n this.channelWrapper.addSetup(setup);\n }\n\n /**\n * Register an event listener on the channel wrapper.\n *\n * Available events:\n * - 'connect': Emitted when the channel is (re)connected\n * - 'close': Emitted when the channel is closed\n * - 'error': Emitted when an error occurs\n *\n * @param event - The event name\n * @param listener - The event listener\n */\n on(event: string, listener: (...args: unknown[]) => void): void {\n this.channelWrapper.on(event, listener);\n }\n\n /**\n * Close the channel and release the connection reference.\n *\n * This will:\n * - Close the channel wrapper\n * - Decrease the reference count on the shared connection\n * - Close the connection if this was the last client using it\n *\n * @returns A Future that resolves when the channel and connection are closed\n */\n close(): Future<Result<void, TechnicalError>> {\n return Future.fromPromise(this.channelWrapper.close())\n .mapError((error: unknown) => new TechnicalError(\"Failed to close channel\", error))\n .flatMapOk(() =>\n Future.fromPromise(\n ConnectionManagerSingleton.getInstance().releaseConnection(\n this.urls,\n this.connectionOptions,\n ),\n ).mapError((error: unknown) => new TechnicalError(\"Failed to release connection\", error)),\n )\n .mapOk(() => undefined);\n }\n\n /**\n * Reset connection singleton cache (for testing only)\n * @internal\n */\n static async _resetConnectionCacheForTesting(): Promise<void> {\n await ConnectionManagerSingleton.getInstance()._resetForTesting();\n }\n}\n","import {\n type Attributes,\n type Counter,\n type Histogram,\n type Span,\n type Tracer,\n} from \"@opentelemetry/api\";\n\n/**\n * SpanKind values from OpenTelemetry.\n * Defined as constants to avoid runtime dependency when types are used.\n * @see https://opentelemetry.io/docs/specs/otel/trace/api/#spankind\n */\nconst SpanKind = {\n /** Producer span represents a message producer */\n PRODUCER: 3,\n /** Consumer span represents a message consumer */\n CONSUMER: 4,\n} as const;\n\n/**\n * Semantic conventions for AMQP messaging following OpenTelemetry standards.\n * @see https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/\n */\nexport const MessagingSemanticConventions = {\n // Messaging attributes\n MESSAGING_SYSTEM: \"messaging.system\",\n MESSAGING_DESTINATION: \"messaging.destination.name\",\n MESSAGING_DESTINATION_KIND: \"messaging.destination.kind\",\n MESSAGING_OPERATION: \"messaging.operation\",\n MESSAGING_MESSAGE_ID: \"messaging.message.id\",\n MESSAGING_MESSAGE_PAYLOAD_SIZE: \"messaging.message.body.size\",\n MESSAGING_MESSAGE_CONVERSATION_ID: \"messaging.message.conversation_id\",\n\n // AMQP specific attributes\n MESSAGING_RABBITMQ_ROUTING_KEY: \"messaging.rabbitmq.destination.routing_key\",\n MESSAGING_RABBITMQ_MESSAGE_DELIVERY_TAG: \"messaging.rabbitmq.message.delivery_tag\",\n\n // Error attributes\n ERROR_TYPE: \"error.type\",\n\n // Values\n MESSAGING_SYSTEM_RABBITMQ: \"rabbitmq\",\n MESSAGING_DESTINATION_KIND_EXCHANGE: \"exchange\",\n MESSAGING_DESTINATION_KIND_QUEUE: \"queue\",\n MESSAGING_OPERATION_PUBLISH: \"publish\",\n MESSAGING_OPERATION_RECEIVE: \"receive\",\n MESSAGING_OPERATION_PROCESS: \"process\",\n} as const;\n\n/**\n * Telemetry provider for AMQP operations.\n * Uses lazy loading to gracefully handle cases where OpenTelemetry is not installed.\n */\nexport type TelemetryProvider = {\n /**\n * Get a tracer instance for creating spans.\n * Returns undefined if OpenTelemetry is not available.\n */\n getTracer: () => Tracer | undefined;\n\n /**\n * Get a counter for messages published.\n * Returns undefined if OpenTelemetry is not available.\n */\n getPublishCounter: () => Counter | undefined;\n\n /**\n * Get a counter for messages consumed.\n * Returns undefined if OpenTelemetry is not available.\n */\n getConsumeCounter: () => Counter | undefined;\n\n /**\n * Get a histogram for publish latency.\n * Returns undefined if OpenTelemetry is not available.\n */\n getPublishLatencyHistogram: () => Histogram | undefined;\n\n /**\n * Get a histogram for consume/process latency.\n * Returns undefined if OpenTelemetry is not available.\n */\n getConsumeLatencyHistogram: () => Histogram | undefined;\n};\n\n/**\n * Instrumentation scope name for amqp-contract.\n */\nconst INSTRUMENTATION_SCOPE_NAME = \"@amqp-contract\";\nconst INSTRUMENTATION_SCOPE_VERSION = \"0.1.0\";\n\n// Cache for OpenTelemetry API module and instruments\nlet otelApi: typeof import(\"@opentelemetry/api\") | null | undefined;\nlet cachedTracer: Tracer | undefined;\nlet cachedPublishCounter: Counter | undefined;\nlet cachedConsumeCounter: Counter | undefined;\nlet cachedPublishLatencyHistogram: Histogram | undefined;\nlet cachedConsumeLatencyHistogram: Histogram | undefined;\n\n/**\n * Try to load the OpenTelemetry API module.\n * Returns null if the module is not available.\n */\nfunction tryLoadOpenTelemetryApi(): typeof import(\"@opentelemetry/api\") | null {\n if (otelApi === undefined) {\n try {\n // Dynamic import using require to avoid bundler issues\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n otelApi = require(\"@opentelemetry/api\") as typeof import(\"@opentelemetry/api\");\n } catch {\n otelApi = null;\n }\n }\n return otelApi;\n}\n\n/**\n * Get or create a tracer instance.\n */\nfunction getTracer(): Tracer | undefined {\n if (cachedTracer !== undefined) {\n return cachedTracer;\n }\n\n const api = tryLoadOpenTelemetryApi();\n if (!api) {\n return undefined;\n }\n\n cachedTracer = api.trace.getTracer(INSTRUMENTATION_SCOPE_NAME, INSTRUMENTATION_SCOPE_VERSION);\n return cachedTracer;\n}\n\n/**\n * Get or create a meter and its instruments.\n */\nfunction getMeterInstruments(): {\n publishCounter: Counter | undefined;\n consumeCounter: Counter | undefined;\n publishLatencyHistogram: Histogram | undefined;\n consumeLatencyHistogram: Histogram | undefined;\n} {\n if (cachedPublishCounter !== undefined) {\n return {\n publishCounter: cachedPublishCounter,\n consumeCounter: cachedConsumeCounter,\n publishLatencyHistogram: cachedPublishLatencyHistogram,\n consumeLatencyHistogram: cachedConsumeLatencyHistogram,\n };\n }\n\n const api = tryLoadOpenTelemetryApi();\n if (!api) {\n return {\n publishCounter: undefined,\n consumeCounter: undefined,\n publishLatencyHistogram: undefined,\n consumeLatencyHistogram: undefined,\n };\n }\n\n const meter = api.metrics.getMeter(INSTRUMENTATION_SCOPE_NAME, INSTRUMENTATION_SCOPE_VERSION);\n\n cachedPublishCounter = meter.createCounter(\"amqp.client.messages.published\", {\n description: \"Number of messages published to AMQP broker\",\n unit: \"{message}\",\n });\n\n cachedConsumeCounter = meter.createCounter(\"amqp.worker.messages.consumed\", {\n description: \"Number of messages consumed from AMQP broker\",\n unit: \"{message}\",\n });\n\n cachedPublishLatencyHistogram = meter.createHistogram(\"amqp.client.publish.duration\", {\n description: \"Duration of message publish operations\",\n unit: \"ms\",\n });\n\n cachedConsumeLatencyHistogram = meter.createHistogram(\"amqp.worker.process.duration\", {\n description: \"Duration of message processing operations\",\n unit: \"ms\",\n });\n\n return {\n publishCounter: cachedPublishCounter,\n consumeCounter: cachedConsumeCounter,\n publishLatencyHistogram: cachedPublishLatencyHistogram,\n consumeLatencyHistogram: cachedConsumeLatencyHistogram,\n };\n}\n\n/**\n * Default telemetry provider that uses OpenTelemetry API if available.\n */\nexport const defaultTelemetryProvider: TelemetryProvider = {\n getTracer,\n getPublishCounter: () => getMeterInstruments().publishCounter,\n getConsumeCounter: () => getMeterInstruments().consumeCounter,\n getPublishLatencyHistogram: () => getMeterInstruments().publishLatencyHistogram,\n getConsumeLatencyHistogram: () => getMeterInstruments().consumeLatencyHistogram,\n};\n\n/**\n * Create a span for a publish operation.\n * Returns undefined if OpenTelemetry is not available.\n */\nexport function startPublishSpan(\n provider: TelemetryProvider,\n exchangeName: string,\n routingKey: string | undefined,\n attributes?: Attributes,\n): Span | undefined {\n const tracer = provider.getTracer();\n if (!tracer) {\n return undefined;\n }\n\n const spanName = `${exchangeName} publish`;\n\n return tracer.startSpan(spanName, {\n kind: SpanKind.PRODUCER,\n attributes: {\n [MessagingSemanticConventions.MESSAGING_SYSTEM]:\n MessagingSemanticConventions.MESSAGING_SYSTEM_RABBITMQ,\n [MessagingSemanticConventions.MESSAGING_DESTINATION]: exchangeName,\n [MessagingSemanticConventions.MESSAGING_DESTINATION_KIND]:\n MessagingSemanticConventions.MESSAGING_DESTINATION_KIND_EXCHANGE,\n [MessagingSemanticConventions.MESSAGING_OPERATION]:\n MessagingSemanticConventions.MESSAGING_OPERATION_PUBLISH,\n ...(routingKey\n ? { [MessagingSemanticConventions.MESSAGING_RABBITMQ_ROUTING_KEY]: routingKey }\n : {}),\n ...attributes,\n },\n });\n}\n\n/**\n * Create a span for a consume/process operation.\n * Returns undefined if OpenTelemetry is not available.\n */\nexport function startConsumeSpan(\n provider: TelemetryProvider,\n queueName: string,\n consumerName: string,\n attributes?: Attributes,\n): Span | undefined {\n const tracer = provider.getTracer();\n if (!tracer) {\n return undefined;\n }\n\n const spanName = `${queueName} process`;\n\n return tracer.startSpan(spanName, {\n kind: SpanKind.CONSUMER,\n attributes: {\n [MessagingSemanticConventions.MESSAGING_SYSTEM]:\n MessagingSemanticConventions.MESSAGING_SYSTEM_RABBITMQ,\n [MessagingSemanticConventions.MESSAGING_DESTINATION]: queueName,\n [MessagingSemanticConventions.MESSAGING_DESTINATION_KIND]:\n MessagingSemanticConventions.MESSAGING_DESTINATION_KIND_QUEUE,\n [MessagingSemanticConventions.MESSAGING_OPERATION]:\n MessagingSemanticConventions.MESSAGING_OPERATION_PROCESS,\n \"amqp.consumer.name\": consumerName,\n ...attributes,\n },\n });\n}\n\n/**\n * End a span with success status.\n */\nexport function endSpanSuccess(span: Span | undefined): void {\n if (!span) {\n return;\n }\n\n const api = tryLoadOpenTelemetryApi();\n if (api) {\n span.setStatus({ code: api.SpanStatusCode.OK });\n }\n span.end();\n}\n\n/**\n * End a span with error status.\n */\nexport function endSpanError(span: Span | undefined, error: Error): void {\n if (!span) {\n return;\n }\n\n const api = tryLoadOpenTelemetryApi();\n if (api) {\n span.setStatus({ code: api.SpanStatusCode.ERROR, message: error.message });\n span.recordException(error);\n span.setAttribute(MessagingSemanticConventions.ERROR_TYPE, error.name);\n }\n span.end();\n}\n\n/**\n * Record a publish metric.\n */\nexport function recordPublishMetric(\n provider: TelemetryProvider,\n exchangeName: string,\n routingKey: string | undefined,\n success: boolean,\n durationMs: number,\n): void {\n const publishCounter = provider.getPublishCounter();\n const publishLatencyHistogram = provider.getPublishLatencyHistogram();\n\n const attributes: Attributes = {\n [MessagingSemanticConventions.MESSAGING_SYSTEM]:\n MessagingSemanticConventions.MESSAGING_SYSTEM_RABBITMQ,\n [MessagingSemanticConventions.MESSAGING_DESTINATION]: exchangeName,\n ...(routingKey\n ? { [MessagingSemanticConventions.MESSAGING_RABBITMQ_ROUTING_KEY]: routingKey }\n : {}),\n success: success,\n };\n\n publishCounter?.add(1, attributes);\n publishLatencyHistogram?.record(durationMs, attributes);\n}\n\n/**\n * Record a consume metric.\n */\nexport function recordConsumeMetric(\n provider: TelemetryProvider,\n queueName: string,\n consumerName: string,\n success: boolean,\n durationMs: number,\n): void {\n const consumeCounter = provider.getConsumeCounter();\n const consumeLatencyHistogram = provider.getConsumeLatencyHistogram();\n\n const attributes: Attributes = {\n [MessagingSemanticConventions.MESSAGING_SYSTEM]:\n MessagingSemanticConventions.MESSAGING_SYSTEM_RABBITMQ,\n [MessagingSemanticConventions.MESSAGING_DESTINATION]: queueName,\n \"amqp.consumer.name\": consumerName,\n success: success,\n };\n\n consumeCounter?.add(1, attributes);\n consumeLatencyHistogram?.record(durationMs, attributes);\n}\n\n/**\n * Reset the cached OpenTelemetry API module and instruments.\n * For testing purposes only.\n * @internal\n */\nexport function _resetTelemetryCacheForTesting(): void {\n otelApi = undefined;\n cachedTracer = undefined;\n cachedPublishCounter = undefined;\n cachedConsumeCounter = undefined;\n cachedPublishLatencyHistogram = undefined;\n cachedConsumeLatencyHistogram = undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,6BAAb,MAAa,2BAA2B;CACtC,OAAe;CACf,AAAQ,8BAAkD,IAAI,KAAK;CACnE,AAAQ,4BAAiC,IAAI,KAAK;CAElD,AAAQ,cAAc;;;;;;CAOtB,OAAO,cAA0C;AAC/C,MAAI,CAAC,2BAA2B,SAC9B,4BAA2B,WAAW,IAAI,4BAA4B;AAExE,SAAO,2BAA2B;;;;;;;;;;;;CAapC,cACE,MACA,mBACuB;EAEvB,MAAM,MAAM,KAAK,oBAAoB,MAAM,kBAAkB;AAE7D,MAAI,CAAC,KAAK,YAAY,IAAI,IAAI,EAAE;GAC9B,MAAM,aAAa,KAAK,QAAQ,MAAM,kBAAkB;AACxD,QAA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AAG,WAAW;AAClC,0BAAyB,OAAO,YAAY,WAAW;;;;;AAMzD,SAAgB,oBACd,UACA,WACA,cACA,SACA,YACM;CACN,MAAM,iBAAiB,SAAS,mBAAmB;CACnD,MAAM,0BAA0B,SAAS,4BAA4B;CAErE,MAAM,aAAyB;GAC5B,6BAA6B,mBAC5B,6BAA6B;GAC9B,6BAA6B,wBAAwB;EACtD,sBAAsB;EACb;EACV;AAED,iBAAgB,IAAI,GAAG,WAAW;AAClC,0BAAyB,OAAO,YAAY,WAAW;;;;;;;AAQzD,SAAgB,iCAAuC;AACrD,WAAU;AACV,gBAAe;AACf,wBAAuB;AACvB,wBAAuB;AACvB,iCAAgC;AAChC,iCAAgC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/connection-manager.ts","../src/errors.ts","../src/setup.ts","../src/amqp-client.ts","../src/telemetry.ts"],"sourcesContent":["import amqp, {\n AmqpConnectionManager,\n AmqpConnectionManagerOptions,\n ConnectionUrl,\n} from \"amqp-connection-manager\";\n\n/**\n * Connection manager singleton for sharing AMQP connections across clients.\n *\n * This singleton implements connection pooling to avoid creating multiple connections\n * to the same broker, which is a RabbitMQ best practice. Connections are identified\n * by their URLs and connection options, and reference counting ensures connections\n * are only closed when all clients have released them.\n *\n * @example\n * ```typescript\n * const manager = ConnectionManagerSingleton.getInstance();\n * const connection = manager.getConnection(['amqp://localhost']);\n * // ... use connection ...\n * await manager.releaseConnection(['amqp://localhost']);\n * ```\n */\nexport class ConnectionManagerSingleton {\n private static instance: ConnectionManagerSingleton;\n private connections: Map<string, AmqpConnectionManager> = new Map();\n private refCounts: Map<string, number> = new Map();\n\n private constructor() {}\n\n /**\n * Get the singleton instance of the connection manager.\n *\n * @returns The singleton instance\n */\n static getInstance(): ConnectionManagerSingleton {\n if (!ConnectionManagerSingleton.instance) {\n ConnectionManagerSingleton.instance = new ConnectionManagerSingleton();\n }\n return ConnectionManagerSingleton.instance;\n }\n\n /**\n * Get or create a connection for the given URLs and options.\n *\n * If a connection already exists with the same URLs and options, it is reused\n * and its reference count is incremented. Otherwise, a new connection is created.\n *\n * @param urls - AMQP broker URL(s)\n * @param connectionOptions - Optional connection configuration\n * @returns The AMQP connection manager instance\n */\n getConnection(\n urls: ConnectionUrl[],\n connectionOptions?: AmqpConnectionManagerOptions,\n ): AmqpConnectionManager {\n // Create a key based on URLs and connection options\n const key = this.createConnectionKey(urls, connectionOptions);\n\n if (!this.connections.has(key)) {\n const connection = amqp.connect(urls, connectionOptions);\n this.connections.set(key, connection);\n this.refCounts.set(key, 0);\n }\n\n // Increment reference count\n this.refCounts.set(key, (this.refCounts.get(key) ?? 0) + 1);\n\n return this.connections.get(key)!;\n }\n\n /**\n * Release a connection reference.\n *\n * Decrements the reference count for the connection. If the count reaches zero,\n * the connection is closed and removed from the pool.\n *\n * @param urls - AMQP broker URL(s) used to identify the connection\n * @param connectionOptions - Optional connection configuration used to identify the connection\n * @returns A promise that resolves when the connection is released (and closed if necessary)\n */\n async releaseConnection(\n urls: ConnectionUrl[],\n connectionOptions?: AmqpConnectionManagerOptions,\n ): Promise<void> {\n const key = this.createConnectionKey(urls, connectionOptions);\n const refCount = this.refCounts.get(key) ?? 0;\n\n if (refCount <= 1) {\n // Last reference - close and remove connection\n const connection = this.connections.get(key);\n if (connection) {\n await connection.close();\n this.connections.delete(key);\n this.refCounts.delete(key);\n }\n } else {\n // Decrement reference count\n this.refCounts.set(key, refCount - 1);\n }\n }\n\n /**\n * Create a unique key for a connection based on URLs and options.\n *\n * The key is deterministic: same URLs and options always produce the same key,\n * enabling connection reuse.\n *\n * @param urls - AMQP broker URL(s)\n * @param connectionOptions - Optional connection configuration\n * @returns A unique string key identifying the connection\n */\n private createConnectionKey(\n urls: ConnectionUrl[],\n connectionOptions?: AmqpConnectionManagerOptions,\n ): string {\n // Create a deterministic key from URLs and options\n // Use JSON.stringify for URLs to avoid ambiguity (e.g., ['a,b'] vs ['a', 'b'])\n const urlsStr = JSON.stringify(urls);\n // Sort object keys for deterministic serialization of connection options\n const optsStr = connectionOptions ? this.serializeOptions(connectionOptions) : \"\";\n return `${urlsStr}::${optsStr}`;\n }\n\n /**\n * Serialize connection options to a deterministic string.\n *\n * @param options - Connection options to serialize\n * @returns A JSON string with sorted keys for deterministic comparison\n */\n private serializeOptions(options: AmqpConnectionManagerOptions): string {\n // Create a deterministic string representation by deeply sorting all object keys\n const sorted = this.deepSort(options);\n return JSON.stringify(sorted);\n }\n\n /**\n * Deep sort an object's keys for deterministic serialization.\n *\n * @param value - The value to deep sort (can be object, array, or primitive)\n * @returns The value with all object keys sorted alphabetically\n */\n private deepSort(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => this.deepSort(item));\n }\n\n if (value !== null && typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n const sortedKeys = Object.keys(obj).sort();\n const result: Record<string, unknown> = {};\n\n for (const key of sortedKeys) {\n result[key] = this.deepSort(obj[key]);\n }\n\n return result;\n }\n\n return value;\n }\n\n /**\n * Reset all cached connections (for testing purposes)\n * @internal\n */\n async _resetForTesting(): Promise<void> {\n // Close all connections before clearing\n const closePromises = Array.from(this.connections.values()).map((conn) => conn.close());\n await Promise.all(closePromises);\n this.connections.clear();\n this.refCounts.clear();\n }\n}\n","/**\n * Error for technical/runtime failures that cannot be prevented by TypeScript.\n *\n * This includes AMQP connection failures, channel issues, validation failures,\n * and other runtime errors. This error is shared across core, worker, and client packages.\n */\nexport class TechnicalError extends Error {\n constructor(\n message: string,\n public override readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"TechnicalError\";\n // Node.js specific stack trace capture\n const ErrorConstructor = Error as unknown as {\n captureStackTrace?: (target: object, constructor: Function) => void;\n };\n if (typeof ErrorConstructor.captureStackTrace === \"function\") {\n ErrorConstructor.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error thrown when message validation fails (payload or headers).\n *\n * Used by both the client (publish-time payload validation) and the worker\n * (consume-time payload and headers validation).\n *\n * @param source - The name of the publisher or consumer that triggered the validation\n * @param issues - The validation issues from the Standard Schema validation\n */\nexport class MessageValidationError extends Error {\n constructor(\n public readonly source: string,\n public readonly issues: unknown,\n ) {\n super(`Message validation failed for \"${source}\"`);\n this.name = \"MessageValidationError\";\n // Node.js specific stack trace capture\n const ErrorConstructor = Error as unknown as {\n captureStackTrace?: (target: object, constructor: Function) => void;\n };\n if (typeof ErrorConstructor.captureStackTrace === \"function\") {\n ErrorConstructor.captureStackTrace(this, this.constructor);\n }\n }\n}\n","import type { Channel } from \"amqplib\";\nimport type { ContractDefinition } from \"@amqp-contract/contract\";\nimport { extractQueue } from \"@amqp-contract/contract\";\nimport { TechnicalError } from \"./errors.js\";\n\n/**\n * Setup AMQP topology (exchanges, queues, and bindings) from a contract definition.\n *\n * This function sets up the complete AMQP topology in the correct order:\n * 1. Assert all exchanges defined in the contract\n * 2. Validate dead letter exchanges are declared before referencing them\n * 3. Assert all queues with their configurations (including dead letter settings)\n * 4. Create all bindings (queue-to-exchange and exchange-to-exchange)\n *\n * @param channel - The AMQP channel to use for topology setup\n * @param contract - The contract definition containing the topology specification\n * @throws {AggregateError} If any exchanges, queues, or bindings fail to be created\n * @throws {TechnicalError} If a queue references a dead letter exchange not declared in the contract\n *\n * @example\n * ```typescript\n * const channel = await connection.createChannel();\n * await setupAmqpTopology(channel, contract);\n * ```\n */\nexport async function setupAmqpTopology(\n channel: Channel,\n contract: ContractDefinition,\n): Promise<void> {\n // Setup exchanges\n const exchangeResults = await Promise.allSettled(\n Object.values(contract.exchanges ?? {}).map((exchange) =>\n channel.assertExchange(exchange.name, exchange.type, {\n durable: exchange.durable,\n autoDelete: exchange.autoDelete,\n internal: exchange.internal,\n arguments: exchange.arguments,\n }),\n ),\n );\n const exchangeErrors = exchangeResults.filter(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (exchangeErrors.length > 0) {\n throw new AggregateError(\n exchangeErrors.map(({ reason }) => reason),\n \"Failed to setup exchanges\",\n );\n }\n\n // Validate dead letter exchanges before setting up queues\n for (const queueEntry of Object.values(contract.queues ?? {})) {\n const queue = extractQueue(queueEntry);\n if (queue.deadLetter) {\n const dlxName = queue.deadLetter.exchange.name;\n const exchangeExists = Object.values(contract.exchanges ?? {}).some(\n (exchange) => exchange.name === dlxName,\n );\n\n if (!exchangeExists) {\n throw new TechnicalError(\n `Queue \"${queue.name}\" references dead letter exchange \"${dlxName}\" which is not declared in the contract. ` +\n `Add the exchange to contract.exchanges to ensure it is created before the queue.`,\n );\n }\n }\n }\n\n // Setup queues\n const queueResults = await Promise.allSettled(\n Object.values(contract.queues ?? {}).map((queueEntry) => {\n const queue = extractQueue(queueEntry);\n // Build queue arguments, merging dead letter configuration and queue type\n const queueArguments: Record<string, unknown> = { ...queue.arguments };\n\n // Set queue type\n queueArguments[\"x-queue-type\"] = queue.type;\n\n if (queue.deadLetter) {\n queueArguments[\"x-dead-letter-exchange\"] = queue.deadLetter.exchange.name;\n if (queue.deadLetter.routingKey) {\n queueArguments[\"x-dead-letter-routing-key\"] = queue.deadLetter.routingKey;\n }\n }\n\n // Handle type-specific properties using discriminated union\n if (queue.type === \"quorum\") {\n // Set delivery limit for quorum queues (native retry support)\n if (queue.deliveryLimit !== undefined) {\n queueArguments[\"x-delivery-limit\"] = queue.deliveryLimit;\n }\n\n // Quorum queues are always durable\n return channel.assertQueue(queue.name, {\n durable: true,\n autoDelete: queue.autoDelete,\n arguments: queueArguments,\n });\n }\n\n // Classic queue\n return channel.assertQueue(queue.name, {\n durable: queue.durable,\n exclusive: queue.exclusive,\n autoDelete: queue.autoDelete,\n arguments: queueArguments,\n });\n }),\n );\n const queueErrors = queueResults.filter(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (queueErrors.length > 0) {\n throw new AggregateError(\n queueErrors.map(({ reason }) => reason),\n \"Failed to setup queues\",\n );\n }\n\n // Setup bindings\n const bindingResults = await Promise.allSettled(\n Object.values(contract.bindings ?? {}).map((binding) => {\n if (binding.type === \"queue\") {\n return channel.bindQueue(\n binding.queue.name,\n binding.exchange.name,\n binding.routingKey ?? \"\",\n binding.arguments,\n );\n }\n\n return channel.bindExchange(\n binding.destination.name,\n binding.source.name,\n binding.routingKey ?? \"\",\n binding.arguments,\n );\n }),\n );\n const bindingErrors = bindingResults.filter(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (bindingErrors.length > 0) {\n throw new AggregateError(\n bindingErrors.map(({ reason }) => reason),\n \"Failed to setup bindings\",\n );\n }\n}\n","import type {\n AmqpConnectionManager,\n AmqpConnectionManagerOptions,\n ChannelWrapper,\n ConnectionUrl,\n CreateChannelOpts,\n} from \"amqp-connection-manager\";\nimport type { Channel, ConsumeMessage, Options } from \"amqplib\";\nimport { Future, Result } from \"@swan-io/boxed\";\nimport { ConnectionManagerSingleton } from \"./connection-manager.js\";\nimport type { ContractDefinition } from \"@amqp-contract/contract\";\nimport { TechnicalError } from \"./errors.js\";\nimport { setupAmqpTopology } from \"./setup.js\";\n\n/**\n * Invoke a SetupFunc, handling both callback-based and promise-based signatures.\n * Uses Function.length to distinguish (same approach as promise-breaker).\n * @internal\n */\nfunction callSetupFunc(\n setup: NonNullable<CreateChannelOpts[\"setup\"]>,\n channel: Channel,\n): Promise<void> {\n if (setup.length >= 2) {\n return new Promise<void>((resolve, reject) => {\n (setup as (channel: Channel, callback: (error?: Error) => void) => void)(\n channel,\n (error?: Error) => {\n if (error) reject(error);\n else resolve();\n },\n );\n });\n }\n return (setup as (channel: Channel) => Promise<void>)(channel);\n}\n\n/**\n * Options for creating an AMQP client.\n *\n * @property urls - AMQP broker URL(s). Multiple URLs provide failover support.\n * @property connectionOptions - Optional connection configuration (heartbeat, reconnect settings, etc.).\n * @property channelOptions - Optional channel configuration options.\n */\nexport type AmqpClientOptions = {\n urls: ConnectionUrl[];\n connectionOptions?: AmqpConnectionManagerOptions | undefined;\n channelOptions?: Partial<CreateChannelOpts> | undefined;\n};\n\n/**\n * Callback type for consuming messages.\n */\nexport type ConsumeCallback = (msg: ConsumeMessage | null) => void | Promise<void>;\n\n/**\n * AMQP client that manages connections and channels with automatic topology setup.\n *\n * This class handles:\n * - Connection management with automatic reconnection via amqp-connection-manager\n * - Connection pooling and sharing across instances with the same URLs\n * - Automatic AMQP topology setup (exchanges, queues, bindings) from contract\n * - Channel creation with JSON serialization enabled by default\n *\n * All operations return `Future<Result<T, TechnicalError>>` for consistent error handling.\n *\n * @example\n * ```typescript\n * const client = new AmqpClient(contract, {\n * urls: ['amqp://localhost'],\n * connectionOptions: { heartbeatIntervalInSeconds: 30 }\n * });\n *\n * // Wait for connection\n * await client.waitForConnect().resultToPromise();\n *\n * // Publish a message\n * const result = await client.publish('exchange', 'routingKey', { data: 'value' }).resultToPromise();\n *\n * // Close when done\n * await client.close().resultToPromise();\n * ```\n */\nexport class AmqpClient {\n private readonly connection: AmqpConnectionManager;\n private readonly channelWrapper: ChannelWrapper;\n private readonly urls: ConnectionUrl[];\n private readonly connectionOptions?: AmqpConnectionManagerOptions;\n\n /**\n * Create a new AMQP client instance.\n *\n * The client will automatically:\n * - Get or create a shared connection using the singleton pattern\n * - Set up AMQP topology (exchanges, queues, bindings) from the contract\n * - Create a channel with JSON serialization enabled\n *\n * @param contract - The contract definition specifying the AMQP topology\n * @param options - Client configuration options\n */\n constructor(\n private readonly contract: ContractDefinition,\n options: AmqpClientOptions,\n ) {\n // Store for cleanup\n this.urls = options.urls;\n if (options.connectionOptions !== undefined) {\n this.connectionOptions = options.connectionOptions;\n }\n\n // Always use singleton to get/create connection\n const singleton = ConnectionManagerSingleton.getInstance();\n this.connection = singleton.getConnection(options.urls, options.connectionOptions);\n\n // Create default setup function that calls setupAmqpTopology\n const defaultSetup = (channel: Channel) => setupAmqpTopology(channel, this.contract);\n\n // Destructure setup from channelOptions to handle it separately\n const { setup: userSetup, ...otherChannelOptions } = options.channelOptions ?? {};\n\n // Merge user-provided channel options with defaults\n const channelOpts: CreateChannelOpts = {\n json: true,\n setup: defaultSetup,\n ...otherChannelOptions,\n };\n\n // If user provided a custom setup, wrap it to call both\n if (userSetup) {\n channelOpts.setup = async (channel: Channel) => {\n await defaultSetup(channel);\n await callSetupFunc(userSetup, channel);\n };\n }\n\n this.channelWrapper = this.connection.createChannel(channelOpts);\n }\n\n /**\n * Get the underlying connection manager\n *\n * This method exposes the AmqpConnectionManager instance that this client uses.\n * The connection is automatically shared across all AmqpClient instances that\n * use the same URLs and connection options.\n *\n * @returns The AmqpConnectionManager instance used by this client\n */\n getConnection(): AmqpConnectionManager {\n return this.connection;\n }\n\n /**\n * Wait for the channel to be connected and ready.\n *\n * @returns A Future that resolves when the channel is connected\n */\n waitForConnect(): Future<Result<void, TechnicalError>> {\n return Future.fromPromise(this.channelWrapper.waitForConnect()).mapError(\n (error: unknown) => new TechnicalError(\"Failed to connect to AMQP broker\", error),\n );\n }\n\n /**\n * Publish a message to an exchange.\n *\n * @param exchange - The exchange name\n * @param routingKey - The routing key\n * @param content - The message content (will be JSON serialized if json: true)\n * @param options - Optional publish options\n * @returns A Future with `Result<boolean>` - true if message was sent, false if channel buffer is full\n */\n publish(\n exchange: string,\n routingKey: string,\n content: Buffer | unknown,\n options?: Options.Publish,\n ): Future<Result<boolean, TechnicalError>> {\n return Future.fromPromise(\n this.channelWrapper.publish(exchange, routingKey, content, options),\n ).mapError((error: unknown) => new TechnicalError(\"Failed to publish message\", error));\n }\n\n /**\n * Start consuming messages from a queue.\n *\n * @param queue - The queue name\n * @param callback - The callback to invoke for each message\n * @param options - Optional consume options\n * @returns A Future with `Result<string>` - the consumer tag\n */\n consume(\n queue: string,\n callback: ConsumeCallback,\n options?: Options.Consume,\n ): Future<Result<string, TechnicalError>> {\n return Future.fromPromise(this.channelWrapper.consume(queue, callback, options))\n .mapError((error: unknown) => new TechnicalError(\"Failed to start consuming messages\", error))\n .mapOk((reply: { consumerTag: string }) => reply.consumerTag);\n }\n\n /**\n * Cancel a consumer by its consumer tag.\n *\n * @param consumerTag - The consumer tag to cancel\n * @returns A Future that resolves when the consumer is cancelled\n */\n cancel(consumerTag: string): Future<Result<void, TechnicalError>> {\n return Future.fromPromise(this.channelWrapper.cancel(consumerTag))\n .mapError((error: unknown) => new TechnicalError(\"Failed to cancel consumer\", error))\n .mapOk(() => undefined);\n }\n\n /**\n * Acknowledge a message.\n *\n * @param msg - The message to acknowledge\n * @param allUpTo - If true, acknowledge all messages up to and including this one\n */\n ack(msg: ConsumeMessage, allUpTo = false): void {\n this.channelWrapper.ack(msg, allUpTo);\n }\n\n /**\n * Negative acknowledge a message.\n *\n * @param msg - The message to nack\n * @param allUpTo - If true, nack all messages up to and including this one\n * @param requeue - If true, requeue the message(s)\n */\n nack(msg: ConsumeMessage, allUpTo = false, requeue = true): void {\n this.channelWrapper.nack(msg, allUpTo, requeue);\n }\n\n /**\n * Add a setup function to be called when the channel is created or reconnected.\n *\n * This is useful for setting up channel-level configuration like prefetch.\n *\n * @param setup - The setup function to add\n */\n addSetup(setup: (channel: Channel) => void | Promise<void>): void {\n this.channelWrapper.addSetup(setup);\n }\n\n /**\n * Register an event listener on the channel wrapper.\n *\n * Available events:\n * - 'connect': Emitted when the channel is (re)connected\n * - 'close': Emitted when the channel is closed\n * - 'error': Emitted when an error occurs\n *\n * @param event - The event name\n * @param listener - The event listener\n */\n on(event: string, listener: (...args: unknown[]) => void): void {\n this.channelWrapper.on(event, listener);\n }\n\n /**\n * Close the channel and release the connection reference.\n *\n * This will:\n * - Close the channel wrapper\n * - Decrease the reference count on the shared connection\n * - Close the connection if this was the last client using it\n *\n * @returns A Future that resolves when the channel and connection are closed\n */\n close(): Future<Result<void, TechnicalError>> {\n return Future.fromPromise(this.channelWrapper.close())\n .mapError((error: unknown) => new TechnicalError(\"Failed to close channel\", error))\n .flatMapOk(() =>\n Future.fromPromise(\n ConnectionManagerSingleton.getInstance().releaseConnection(\n this.urls,\n this.connectionOptions,\n ),\n ).mapError((error: unknown) => new TechnicalError(\"Failed to release connection\", error)),\n )\n .mapOk(() => undefined);\n }\n\n /**\n * Reset connection singleton cache (for testing only)\n * @internal\n */\n static async _resetConnectionCacheForTesting(): Promise<void> {\n await ConnectionManagerSingleton.getInstance()._resetForTesting();\n }\n}\n","import {\n type Attributes,\n type Counter,\n type Histogram,\n type Span,\n type Tracer,\n} from \"@opentelemetry/api\";\n\n/**\n * SpanKind values from OpenTelemetry.\n * Defined as constants to avoid runtime dependency when types are used.\n * @see https://opentelemetry.io/docs/specs/otel/trace/api/#spankind\n */\nconst SpanKind = {\n /** Producer span represents a message producer */\n PRODUCER: 3,\n /** Consumer span represents a message consumer */\n CONSUMER: 4,\n} as const;\n\n/**\n * Semantic conventions for AMQP messaging following OpenTelemetry standards.\n * @see https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/\n */\nexport const MessagingSemanticConventions = {\n // Messaging attributes\n MESSAGING_SYSTEM: \"messaging.system\",\n MESSAGING_DESTINATION: \"messaging.destination.name\",\n MESSAGING_DESTINATION_KIND: \"messaging.destination.kind\",\n MESSAGING_OPERATION: \"messaging.operation\",\n\n // AMQP/RabbitMQ specific attributes\n MESSAGING_RABBITMQ_ROUTING_KEY: \"messaging.rabbitmq.destination.routing_key\",\n MESSAGING_RABBITMQ_MESSAGE_DELIVERY_TAG: \"messaging.rabbitmq.message.delivery_tag\",\n AMQP_PUBLISHER_NAME: \"amqp.publisher.name\",\n AMQP_CONSUMER_NAME: \"amqp.consumer.name\",\n\n // Error attributes\n ERROR_TYPE: \"error.type\",\n\n // Values\n MESSAGING_SYSTEM_RABBITMQ: \"rabbitmq\",\n MESSAGING_DESTINATION_KIND_EXCHANGE: \"exchange\",\n MESSAGING_DESTINATION_KIND_QUEUE: \"queue\",\n MESSAGING_OPERATION_PUBLISH: \"publish\",\n MESSAGING_OPERATION_PROCESS: \"process\",\n} as const;\n\n/**\n * Telemetry provider for AMQP operations.\n * Uses lazy loading to gracefully handle cases where OpenTelemetry is not installed.\n */\nexport type TelemetryProvider = {\n /**\n * Get a tracer instance for creating spans.\n * Returns undefined if OpenTelemetry is not available.\n */\n getTracer: () => Tracer | undefined;\n\n /**\n * Get a counter for messages published.\n * Returns undefined if OpenTelemetry is not available.\n */\n getPublishCounter: () => Counter | undefined;\n\n /**\n * Get a counter for messages consumed.\n * Returns undefined if OpenTelemetry is not available.\n */\n getConsumeCounter: () => Counter | undefined;\n\n /**\n * Get a histogram for publish latency.\n * Returns undefined if OpenTelemetry is not available.\n */\n getPublishLatencyHistogram: () => Histogram | undefined;\n\n /**\n * Get a histogram for consume/process latency.\n * Returns undefined if OpenTelemetry is not available.\n */\n getConsumeLatencyHistogram: () => Histogram | undefined;\n};\n\n/**\n * Instrumentation scope name for amqp-contract.\n */\nconst INSTRUMENTATION_SCOPE_NAME = \"@amqp-contract\";\nconst INSTRUMENTATION_SCOPE_VERSION = \"0.1.0\";\n\n// Cache for OpenTelemetry API module and instruments\nlet otelApi: typeof import(\"@opentelemetry/api\") | null | undefined;\nlet cachedTracer: Tracer | undefined;\nlet cachedPublishCounter: Counter | undefined;\nlet cachedConsumeCounter: Counter | undefined;\nlet cachedPublishLatencyHistogram: Histogram | undefined;\nlet cachedConsumeLatencyHistogram: Histogram | undefined;\n\n/**\n * Try to load the OpenTelemetry API module.\n * Returns null if the module is not available.\n */\nfunction tryLoadOpenTelemetryApi(): typeof import(\"@opentelemetry/api\") | null {\n if (otelApi === undefined) {\n try {\n // Dynamic import using require to avoid bundler issues\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n otelApi = require(\"@opentelemetry/api\") as typeof import(\"@opentelemetry/api\");\n } catch {\n otelApi = null;\n }\n }\n return otelApi;\n}\n\n/**\n * Get or create a tracer instance.\n */\nfunction getTracer(): Tracer | undefined {\n if (cachedTracer !== undefined) {\n return cachedTracer;\n }\n\n const api = tryLoadOpenTelemetryApi();\n if (!api) {\n return undefined;\n }\n\n cachedTracer = api.trace.getTracer(INSTRUMENTATION_SCOPE_NAME, INSTRUMENTATION_SCOPE_VERSION);\n return cachedTracer;\n}\n\n/**\n * Get or create a meter and its instruments.\n */\nfunction getMeterInstruments(): {\n publishCounter: Counter | undefined;\n consumeCounter: Counter | undefined;\n publishLatencyHistogram: Histogram | undefined;\n consumeLatencyHistogram: Histogram | undefined;\n} {\n if (cachedPublishCounter !== undefined) {\n return {\n publishCounter: cachedPublishCounter,\n consumeCounter: cachedConsumeCounter,\n publishLatencyHistogram: cachedPublishLatencyHistogram,\n consumeLatencyHistogram: cachedConsumeLatencyHistogram,\n };\n }\n\n const api = tryLoadOpenTelemetryApi();\n if (!api) {\n return {\n publishCounter: undefined,\n consumeCounter: undefined,\n publishLatencyHistogram: undefined,\n consumeLatencyHistogram: undefined,\n };\n }\n\n const meter = api.metrics.getMeter(INSTRUMENTATION_SCOPE_NAME, INSTRUMENTATION_SCOPE_VERSION);\n\n cachedPublishCounter = meter.createCounter(\"amqp.client.messages.published\", {\n description: \"Number of messages published to AMQP broker\",\n unit: \"{message}\",\n });\n\n cachedConsumeCounter = meter.createCounter(\"amqp.worker.messages.consumed\", {\n description: \"Number of messages consumed from AMQP broker\",\n unit: \"{message}\",\n });\n\n cachedPublishLatencyHistogram = meter.createHistogram(\"amqp.client.publish.duration\", {\n description: \"Duration of message publish operations\",\n unit: \"ms\",\n });\n\n cachedConsumeLatencyHistogram = meter.createHistogram(\"amqp.worker.process.duration\", {\n description: \"Duration of message processing operations\",\n unit: \"ms\",\n });\n\n return {\n publishCounter: cachedPublishCounter,\n consumeCounter: cachedConsumeCounter,\n publishLatencyHistogram: cachedPublishLatencyHistogram,\n consumeLatencyHistogram: cachedConsumeLatencyHistogram,\n };\n}\n\n/**\n * Default telemetry provider that uses OpenTelemetry API if available.\n */\nexport const defaultTelemetryProvider: TelemetryProvider = {\n getTracer,\n getPublishCounter: () => getMeterInstruments().publishCounter,\n getConsumeCounter: () => getMeterInstruments().consumeCounter,\n getPublishLatencyHistogram: () => getMeterInstruments().publishLatencyHistogram,\n getConsumeLatencyHistogram: () => getMeterInstruments().consumeLatencyHistogram,\n};\n\n/**\n * Create a span for a publish operation.\n * Returns undefined if OpenTelemetry is not available.\n */\nexport function startPublishSpan(\n provider: TelemetryProvider,\n exchangeName: string,\n routingKey: string | undefined,\n attributes?: Attributes,\n): Span | undefined {\n const tracer = provider.getTracer();\n if (!tracer) {\n return undefined;\n }\n\n const spanName = `${exchangeName} publish`;\n\n return tracer.startSpan(spanName, {\n kind: SpanKind.PRODUCER,\n attributes: {\n [MessagingSemanticConventions.MESSAGING_SYSTEM]:\n MessagingSemanticConventions.MESSAGING_SYSTEM_RABBITMQ,\n [MessagingSemanticConventions.MESSAGING_DESTINATION]: exchangeName,\n [MessagingSemanticConventions.MESSAGING_DESTINATION_KIND]:\n MessagingSemanticConventions.MESSAGING_DESTINATION_KIND_EXCHANGE,\n [MessagingSemanticConventions.MESSAGING_OPERATION]:\n MessagingSemanticConventions.MESSAGING_OPERATION_PUBLISH,\n ...(routingKey\n ? { [MessagingSemanticConventions.MESSAGING_RABBITMQ_ROUTING_KEY]: routingKey }\n : {}),\n ...attributes,\n },\n });\n}\n\n/**\n * Create a span for a consume/process operation.\n * Returns undefined if OpenTelemetry is not available.\n */\nexport function startConsumeSpan(\n provider: TelemetryProvider,\n queueName: string,\n consumerName: string,\n attributes?: Attributes,\n): Span | undefined {\n const tracer = provider.getTracer();\n if (!tracer) {\n return undefined;\n }\n\n const spanName = `${queueName} process`;\n\n return tracer.startSpan(spanName, {\n kind: SpanKind.CONSUMER,\n attributes: {\n [MessagingSemanticConventions.MESSAGING_SYSTEM]:\n MessagingSemanticConventions.MESSAGING_SYSTEM_RABBITMQ,\n [MessagingSemanticConventions.MESSAGING_DESTINATION]: queueName,\n [MessagingSemanticConventions.MESSAGING_DESTINATION_KIND]:\n MessagingSemanticConventions.MESSAGING_DESTINATION_KIND_QUEUE,\n [MessagingSemanticConventions.MESSAGING_OPERATION]:\n MessagingSemanticConventions.MESSAGING_OPERATION_PROCESS,\n [MessagingSemanticConventions.AMQP_CONSUMER_NAME]: consumerName,\n ...attributes,\n },\n });\n}\n\n/**\n * End a span with success status.\n */\nexport function endSpanSuccess(span: Span | undefined): void {\n if (!span) {\n return;\n }\n\n const api = tryLoadOpenTelemetryApi();\n if (api) {\n span.setStatus({ code: api.SpanStatusCode.OK });\n }\n span.end();\n}\n\n/**\n * End a span with error status.\n */\nexport function endSpanError(span: Span | undefined, error: Error): void {\n if (!span) {\n return;\n }\n\n const api = tryLoadOpenTelemetryApi();\n if (api) {\n span.setStatus({ code: api.SpanStatusCode.ERROR, message: error.message });\n span.recordException(error);\n span.setAttribute(MessagingSemanticConventions.ERROR_TYPE, error.name);\n }\n span.end();\n}\n\n/**\n * Record a publish metric.\n */\nexport function recordPublishMetric(\n provider: TelemetryProvider,\n exchangeName: string,\n routingKey: string | undefined,\n success: boolean,\n durationMs: number,\n): void {\n const publishCounter = provider.getPublishCounter();\n const publishLatencyHistogram = provider.getPublishLatencyHistogram();\n\n const attributes: Attributes = {\n [MessagingSemanticConventions.MESSAGING_SYSTEM]:\n MessagingSemanticConventions.MESSAGING_SYSTEM_RABBITMQ,\n [MessagingSemanticConventions.MESSAGING_DESTINATION]: exchangeName,\n ...(routingKey\n ? { [MessagingSemanticConventions.MESSAGING_RABBITMQ_ROUTING_KEY]: routingKey }\n : {}),\n success: success,\n };\n\n publishCounter?.add(1, attributes);\n publishLatencyHistogram?.record(durationMs, attributes);\n}\n\n/**\n * Record a consume metric.\n */\nexport function recordConsumeMetric(\n provider: TelemetryProvider,\n queueName: string,\n consumerName: string,\n success: boolean,\n durationMs: number,\n): void {\n const consumeCounter = provider.getConsumeCounter();\n const consumeLatencyHistogram = provider.getConsumeLatencyHistogram();\n\n const attributes: Attributes = {\n [MessagingSemanticConventions.MESSAGING_SYSTEM]:\n MessagingSemanticConventions.MESSAGING_SYSTEM_RABBITMQ,\n [MessagingSemanticConventions.MESSAGING_DESTINATION]: queueName,\n [MessagingSemanticConventions.AMQP_CONSUMER_NAME]: consumerName,\n success: success,\n };\n\n consumeCounter?.add(1, attributes);\n consumeLatencyHistogram?.record(durationMs, attributes);\n}\n\n/**\n * Reset the cached OpenTelemetry API module and instruments.\n * For testing purposes only.\n * @internal\n */\nexport function _resetTelemetryCacheForTesting(): void {\n otelApi = undefined;\n cachedTracer = undefined;\n cachedPublishCounter = undefined;\n cachedConsumeCounter = undefined;\n cachedPublishLatencyHistogram = undefined;\n cachedConsumeLatencyHistogram = undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,6BAAb,MAAa,2BAA2B;CACtC,OAAe;CACf,AAAQ,8BAAkD,IAAI,KAAK;CACnE,AAAQ,4BAAiC,IAAI,KAAK;CAElD,AAAQ,cAAc;;;;;;CAOtB,OAAO,cAA0C;AAC/C,MAAI,CAAC,2BAA2B,SAC9B,4BAA2B,WAAW,IAAI,4BAA4B;AAExE,SAAO,2BAA2B;;;;;;;;;;;;CAapC,cACE,MACA,mBACuB;EAEvB,MAAM,MAAM,KAAK,oBAAoB,MAAM,kBAAkB;AAE7D,MAAI,CAAC,KAAK,YAAY,IAAI,IAAI,EAAE;GAC9B,MAAM,aAAa,KAAK,QAAQ,MAAM,kBAAkB;AACxD,QAAK,YAAY,IAAI,KAAK,WAAW;AACrC,QAAK,UAAU,IAAI,KAAK,EAAE;;AAI5B,OAAK,UAAU,IAAI,MAAM,KAAK,UAAU,IAAI,IAAI,IAAI,KAAK,EAAE;AAE3D,SAAO,KAAK,YAAY,IAAI,IAAI;;;;;;;;;;;;CAalC,MAAM,kBACJ,MACA,mBACe;EACf,MAAM,MAAM,KAAK,oBAAoB,MAAM,kBAAkB;EAC7D,MAAM,WAAW,KAAK,UAAU,IAAI,IAAI,IAAI;AAE5C,MAAI,YAAY,GAAG;GAEjB,MAAM,aAAa,KAAK,YAAY,IAAI,IAAI;AAC5C,OAAI,YAAY;AACd,UAAM,WAAW,OAAO;AACxB,SAAK,YAAY,OAAO,IAAI;AAC5B,SAAK,UAAU,OAAO,IAAI;;QAI5B,MAAK,UAAU,IAAI,KAAK,WAAW,EAAE;;;;;;;;;;;;CA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