@amqp-contract/core 0.3.5 → 0.5.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/README.md +2 -0
- package/dist/index.cjs +144 -28
- package/dist/index.d.cts +58 -7
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +58 -7
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +143 -29
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -5
package/README.md
CHANGED
|
@@ -65,6 +65,8 @@ const amqpClient = new AmqpClient(contract, {
|
|
|
65
65
|
await amqpClient.close();
|
|
66
66
|
```
|
|
67
67
|
|
|
68
|
+
For advanced channel configuration options (custom setup, prefetch, publisher confirms), see the [Channel Configuration Guide](https://btravers.github.io/amqp-contract/guide/channel-configuration).
|
|
69
|
+
|
|
68
70
|
### Logger Interface
|
|
69
71
|
|
|
70
72
|
The core package exports a `Logger` interface that can be used to implement custom logging for AMQP operations:
|
package/dist/index.cjs
CHANGED
|
@@ -28,45 +28,161 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
28
28
|
let amqp_connection_manager = require("amqp-connection-manager");
|
|
29
29
|
amqp_connection_manager = __toESM(amqp_connection_manager);
|
|
30
30
|
|
|
31
|
-
//#region src/
|
|
31
|
+
//#region src/connection-manager.ts
|
|
32
|
+
/**
|
|
33
|
+
* Connection manager singleton for sharing connections across clients
|
|
34
|
+
*/
|
|
35
|
+
var ConnectionManagerSingleton = class ConnectionManagerSingleton {
|
|
36
|
+
static instance;
|
|
37
|
+
connections = /* @__PURE__ */ new Map();
|
|
38
|
+
refCounts = /* @__PURE__ */ new Map();
|
|
39
|
+
constructor() {}
|
|
40
|
+
static getInstance() {
|
|
41
|
+
if (!ConnectionManagerSingleton.instance) ConnectionManagerSingleton.instance = new ConnectionManagerSingleton();
|
|
42
|
+
return ConnectionManagerSingleton.instance;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Get or create a connection for the given URLs and options
|
|
46
|
+
*/
|
|
47
|
+
getConnection(urls, connectionOptions) {
|
|
48
|
+
const key = this.createConnectionKey(urls, connectionOptions);
|
|
49
|
+
if (!this.connections.has(key)) {
|
|
50
|
+
const connection = amqp_connection_manager.default.connect(urls, connectionOptions);
|
|
51
|
+
this.connections.set(key, connection);
|
|
52
|
+
this.refCounts.set(key, 0);
|
|
53
|
+
}
|
|
54
|
+
this.refCounts.set(key, (this.refCounts.get(key) ?? 0) + 1);
|
|
55
|
+
return this.connections.get(key);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Release a connection reference. If no more references exist, close the connection.
|
|
59
|
+
*/
|
|
60
|
+
async releaseConnection(urls, connectionOptions) {
|
|
61
|
+
const key = this.createConnectionKey(urls, connectionOptions);
|
|
62
|
+
const refCount = this.refCounts.get(key) ?? 0;
|
|
63
|
+
if (refCount <= 1) {
|
|
64
|
+
const connection = this.connections.get(key);
|
|
65
|
+
if (connection) {
|
|
66
|
+
await connection.close();
|
|
67
|
+
this.connections.delete(key);
|
|
68
|
+
this.refCounts.delete(key);
|
|
69
|
+
}
|
|
70
|
+
} else this.refCounts.set(key, refCount - 1);
|
|
71
|
+
}
|
|
72
|
+
createConnectionKey(urls, connectionOptions) {
|
|
73
|
+
return `${JSON.stringify(urls)}::${connectionOptions ? this.serializeOptions(connectionOptions) : ""}`;
|
|
74
|
+
}
|
|
75
|
+
serializeOptions(options) {
|
|
76
|
+
const sorted = this.deepSort(options);
|
|
77
|
+
return JSON.stringify(sorted);
|
|
78
|
+
}
|
|
79
|
+
deepSort(value) {
|
|
80
|
+
if (Array.isArray(value)) return value.map((item) => this.deepSort(item));
|
|
81
|
+
if (value !== null && typeof value === "object") {
|
|
82
|
+
const obj = value;
|
|
83
|
+
const sortedKeys = Object.keys(obj).sort();
|
|
84
|
+
const result = {};
|
|
85
|
+
for (const key of sortedKeys) result[key] = this.deepSort(obj[key]);
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Reset all cached connections (for testing purposes)
|
|
92
|
+
* @internal
|
|
93
|
+
*/
|
|
94
|
+
async _resetForTesting() {
|
|
95
|
+
const closePromises = Array.from(this.connections.values()).map((conn) => conn.close());
|
|
96
|
+
await Promise.all(closePromises);
|
|
97
|
+
this.connections.clear();
|
|
98
|
+
this.refCounts.clear();
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
//#endregion
|
|
103
|
+
//#region src/setup.ts
|
|
104
|
+
/**
|
|
105
|
+
* Setup AMQP topology (exchanges, queues, and bindings) from a contract definition
|
|
106
|
+
*/
|
|
107
|
+
async function setupAmqpTopology(channel, contract) {
|
|
108
|
+
const exchangeErrors = (await Promise.allSettled(Object.values(contract.exchanges ?? {}).map((exchange) => channel.assertExchange(exchange.name, exchange.type, {
|
|
109
|
+
durable: exchange.durable,
|
|
110
|
+
autoDelete: exchange.autoDelete,
|
|
111
|
+
internal: exchange.internal,
|
|
112
|
+
arguments: exchange.arguments
|
|
113
|
+
})))).filter((result) => result.status === "rejected");
|
|
114
|
+
if (exchangeErrors.length > 0) throw new AggregateError(exchangeErrors.map(({ reason }) => reason), "Failed to setup exchanges");
|
|
115
|
+
const queueErrors = (await Promise.allSettled(Object.values(contract.queues ?? {}).map((queue) => channel.assertQueue(queue.name, {
|
|
116
|
+
durable: queue.durable,
|
|
117
|
+
exclusive: queue.exclusive,
|
|
118
|
+
autoDelete: queue.autoDelete,
|
|
119
|
+
arguments: queue.arguments
|
|
120
|
+
})))).filter((result) => result.status === "rejected");
|
|
121
|
+
if (queueErrors.length > 0) throw new AggregateError(queueErrors.map(({ reason }) => reason), "Failed to setup queues");
|
|
122
|
+
const bindingErrors = (await Promise.allSettled(Object.values(contract.bindings ?? {}).map((binding) => {
|
|
123
|
+
if (binding.type === "queue") return channel.bindQueue(binding.queue.name, binding.exchange.name, binding.routingKey ?? "", binding.arguments);
|
|
124
|
+
return channel.bindExchange(binding.destination.name, binding.source.name, binding.routingKey ?? "", binding.arguments);
|
|
125
|
+
}))).filter((result) => result.status === "rejected");
|
|
126
|
+
if (bindingErrors.length > 0) throw new AggregateError(bindingErrors.map(({ reason }) => reason), "Failed to setup bindings");
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
//#endregion
|
|
130
|
+
//#region src/amqp-client.ts
|
|
32
131
|
var AmqpClient = class {
|
|
33
132
|
connection;
|
|
34
133
|
channel;
|
|
134
|
+
urls;
|
|
135
|
+
connectionOptions;
|
|
35
136
|
constructor(contract, options) {
|
|
36
137
|
this.contract = contract;
|
|
37
|
-
this.
|
|
38
|
-
|
|
39
|
-
this.
|
|
138
|
+
this.urls = options.urls;
|
|
139
|
+
if (options.connectionOptions !== void 0) this.connectionOptions = options.connectionOptions;
|
|
140
|
+
this.connection = ConnectionManagerSingleton.getInstance().getConnection(options.urls, options.connectionOptions);
|
|
141
|
+
const defaultSetup = (channel) => setupAmqpTopology(channel, this.contract);
|
|
142
|
+
const { setup: userSetup, ...otherChannelOptions } = options.channelOptions ?? {};
|
|
143
|
+
const channelOpts = {
|
|
40
144
|
json: true,
|
|
41
|
-
setup:
|
|
42
|
-
|
|
145
|
+
setup: defaultSetup,
|
|
146
|
+
...otherChannelOptions
|
|
147
|
+
};
|
|
148
|
+
if (userSetup) channelOpts.setup = async (channel) => {
|
|
149
|
+
await defaultSetup(channel);
|
|
150
|
+
if (userSetup.length === 2) await new Promise((resolve, reject) => {
|
|
151
|
+
userSetup(channel, (error) => {
|
|
152
|
+
if (error) reject(error);
|
|
153
|
+
else resolve();
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
else await userSetup(channel);
|
|
157
|
+
};
|
|
158
|
+
this.channel = this.connection.createChannel(channelOpts);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Get the underlying connection manager
|
|
162
|
+
*
|
|
163
|
+
* This method exposes the AmqpConnectionManager instance that this client uses.
|
|
164
|
+
* The connection is automatically shared across all AmqpClient instances that
|
|
165
|
+
* use the same URLs and connection options.
|
|
166
|
+
*
|
|
167
|
+
* @returns The AmqpConnectionManager instance used by this client
|
|
168
|
+
*/
|
|
169
|
+
getConnection() {
|
|
170
|
+
return this.connection;
|
|
43
171
|
}
|
|
44
172
|
async close() {
|
|
45
173
|
await this.channel.close();
|
|
46
|
-
await this.
|
|
174
|
+
await ConnectionManagerSingleton.getInstance().releaseConnection(this.urls, this.connectionOptions);
|
|
47
175
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
})))).filter((result) => result.status === "rejected");
|
|
55
|
-
if (exchangeErrors.length > 0) throw new AggregateError(exchangeErrors.map(({ reason }) => reason), "Failed to setup exchanges");
|
|
56
|
-
const queueErrors = (await Promise.allSettled(Object.values(this.contract.queues ?? {}).map((queue) => channel.assertQueue(queue.name, {
|
|
57
|
-
durable: queue.durable,
|
|
58
|
-
exclusive: queue.exclusive,
|
|
59
|
-
autoDelete: queue.autoDelete,
|
|
60
|
-
arguments: queue.arguments
|
|
61
|
-
})))).filter((result) => result.status === "rejected");
|
|
62
|
-
if (queueErrors.length > 0) throw new AggregateError(queueErrors.map(({ reason }) => reason), "Failed to setup queues");
|
|
63
|
-
const bindingErrors = (await Promise.allSettled(Object.values(this.contract.bindings ?? {}).map((binding) => {
|
|
64
|
-
if (binding.type === "queue") return channel.bindQueue(binding.queue.name, binding.exchange.name, binding.routingKey ?? "", binding.arguments);
|
|
65
|
-
return channel.bindExchange(binding.destination.name, binding.source.name, binding.routingKey ?? "", binding.arguments);
|
|
66
|
-
}))).filter((result) => result.status === "rejected");
|
|
67
|
-
if (bindingErrors.length > 0) throw new AggregateError(bindingErrors.map(({ reason }) => reason), "Failed to setup bindings");
|
|
176
|
+
/**
|
|
177
|
+
* Reset connection singleton cache (for testing only)
|
|
178
|
+
* @internal
|
|
179
|
+
*/
|
|
180
|
+
static async _resetConnectionCacheForTesting() {
|
|
181
|
+
await ConnectionManagerSingleton.getInstance()._resetForTesting();
|
|
68
182
|
}
|
|
69
183
|
};
|
|
70
184
|
|
|
71
185
|
//#endregion
|
|
72
|
-
exports.AmqpClient = AmqpClient;
|
|
186
|
+
exports.AmqpClient = AmqpClient;
|
|
187
|
+
exports.ConnectionManagerSingleton = ConnectionManagerSingleton;
|
|
188
|
+
exports.setupAmqpTopology = setupAmqpTopology;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { AmqpConnectionManager, AmqpConnectionManagerOptions, ChannelWrapper, ConnectionUrl, CreateChannelOpts } from "amqp-connection-manager";
|
|
1
2
|
import { ContractDefinition } from "@amqp-contract/contract";
|
|
2
|
-
import {
|
|
3
|
+
import { Channel } from "amqplib";
|
|
3
4
|
|
|
4
5
|
//#region src/logger.d.ts
|
|
5
6
|
|
|
@@ -31,7 +32,7 @@ type LoggerContext = Record<string, unknown> & {
|
|
|
31
32
|
* };
|
|
32
33
|
* ```
|
|
33
34
|
*/
|
|
34
|
-
|
|
35
|
+
type Logger = {
|
|
35
36
|
/**
|
|
36
37
|
* Log debug level messages
|
|
37
38
|
* @param message - The log message
|
|
@@ -56,22 +57,72 @@ interface Logger {
|
|
|
56
57
|
* @param context - Optional context to include with the log
|
|
57
58
|
*/
|
|
58
59
|
error(message: string, context?: LoggerContext): void;
|
|
59
|
-
}
|
|
60
|
+
};
|
|
60
61
|
//#endregion
|
|
61
|
-
//#region src/
|
|
62
|
+
//#region src/amqp-client.d.ts
|
|
62
63
|
type AmqpClientOptions = {
|
|
63
64
|
urls: ConnectionUrl[];
|
|
64
65
|
connectionOptions?: AmqpConnectionManagerOptions | undefined;
|
|
66
|
+
channelOptions?: Partial<CreateChannelOpts> | undefined;
|
|
65
67
|
};
|
|
66
68
|
declare class AmqpClient {
|
|
67
69
|
private readonly contract;
|
|
68
|
-
private readonly options;
|
|
69
70
|
private readonly connection;
|
|
70
71
|
readonly channel: ChannelWrapper;
|
|
72
|
+
private readonly urls;
|
|
73
|
+
private readonly connectionOptions?;
|
|
71
74
|
constructor(contract: ContractDefinition, options: AmqpClientOptions);
|
|
75
|
+
/**
|
|
76
|
+
* Get the underlying connection manager
|
|
77
|
+
*
|
|
78
|
+
* This method exposes the AmqpConnectionManager instance that this client uses.
|
|
79
|
+
* The connection is automatically shared across all AmqpClient instances that
|
|
80
|
+
* use the same URLs and connection options.
|
|
81
|
+
*
|
|
82
|
+
* @returns The AmqpConnectionManager instance used by this client
|
|
83
|
+
*/
|
|
84
|
+
getConnection(): AmqpConnectionManager;
|
|
72
85
|
close(): Promise<void>;
|
|
73
|
-
|
|
86
|
+
/**
|
|
87
|
+
* Reset connection singleton cache (for testing only)
|
|
88
|
+
* @internal
|
|
89
|
+
*/
|
|
90
|
+
static _resetConnectionCacheForTesting(): Promise<void>;
|
|
74
91
|
}
|
|
75
92
|
//#endregion
|
|
76
|
-
|
|
93
|
+
//#region src/connection-manager.d.ts
|
|
94
|
+
/**
|
|
95
|
+
* Connection manager singleton for sharing connections across clients
|
|
96
|
+
*/
|
|
97
|
+
declare class ConnectionManagerSingleton {
|
|
98
|
+
private static instance;
|
|
99
|
+
private connections;
|
|
100
|
+
private refCounts;
|
|
101
|
+
private constructor();
|
|
102
|
+
static getInstance(): ConnectionManagerSingleton;
|
|
103
|
+
/**
|
|
104
|
+
* Get or create a connection for the given URLs and options
|
|
105
|
+
*/
|
|
106
|
+
getConnection(urls: ConnectionUrl[], connectionOptions?: AmqpConnectionManagerOptions): AmqpConnectionManager;
|
|
107
|
+
/**
|
|
108
|
+
* Release a connection reference. If no more references exist, close the connection.
|
|
109
|
+
*/
|
|
110
|
+
releaseConnection(urls: ConnectionUrl[], connectionOptions?: AmqpConnectionManagerOptions): Promise<void>;
|
|
111
|
+
private createConnectionKey;
|
|
112
|
+
private serializeOptions;
|
|
113
|
+
private deepSort;
|
|
114
|
+
/**
|
|
115
|
+
* Reset all cached connections (for testing purposes)
|
|
116
|
+
* @internal
|
|
117
|
+
*/
|
|
118
|
+
_resetForTesting(): Promise<void>;
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
//#region src/setup.d.ts
|
|
122
|
+
/**
|
|
123
|
+
* Setup AMQP topology (exchanges, queues, and bindings) from a contract definition
|
|
124
|
+
*/
|
|
125
|
+
declare function setupAmqpTopology(channel: Channel, contract: ContractDefinition): Promise<void>;
|
|
126
|
+
//#endregion
|
|
127
|
+
export { AmqpClient, type AmqpClientOptions, ConnectionManagerSingleton, type Logger, type LoggerContext, setupAmqpTopology };
|
|
77
128
|
//# 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/
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/logger.ts","../src/amqp-client.ts","../src/connection-manager.ts","../src/setup.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;AAQA;AAqBA;;AAakC,KAlCtB,aAAA,GAAgB,MAkCM,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA;EAOA,KAAA,CAAA,EAAA,OAAA;CAOC;;;;;AC5CnC;;;;;;AAMA;;;;;;;AAoFyD,KDzE7C,MAAA,GCyE6C;;;;AC7FzD;;EAkBU,KAAA,CAAA,OAAA,EAAA,MAAA,EAAA,OAAA,CAAA,EFQyB,aERzB,CAAA,EAAA,IAAA;EACc;;;;;EAmFI,IAAA,CAAA,OAAA,EAAA,MAAA,EAAA,OAAA,CAAA,EFrEM,aEqEN,CAAA,EAAA,IAAA;EAAO;;;;ACzGnC;EACW,IAAA,CAAA,OAAA,EAAA,MAAA,EAAA,OAAA,CAAA,EH0CuB,aG1CvB,CAAA,EAAA,IAAA;EACC;;;;;mCHgDuB;;;;KC5CvB,iBAAA;QACJ;sBACc;EDNV,cAAA,CAAA,ECOO,ODPM,CCOE,iBDPO,CAAA,GAAA,SAAA;AAqBlC,CAAA;AAMmC,cCjBtB,UAAA,CDiBsB;EAOD,iBAAA,QAAA;EAOA,iBAAA,UAAA;EAOC,SAAA,OAAA,ECpCR,cDoCQ;EAAa,iBAAA,IAAA;;wBC/BjB,6BAClB;;AAdb;;;;;;AAMA;;EAO+B,aAAA,CAAA,CAAA,EA8DZ,qBA9DY;EAClB,KAAA,CAAA,CAAA,EAiEI,OAjEJ,CAAA,IAAA,CAAA;EA6DM;;;;4CAe+B;;;;;;;cC7FrC,0BAAA;EFDD,eAAA,QAAa;EAqBb,QAAA,WAAM;EAMiB,QAAA,SAAA;EAOD,QAAA,WAAA,CAAA;EAOA,OAAA,WAAA,CAAA,CAAA,EEjCV,0BFiCU;EAOC;;;sBE7BzB,qCACc,+BACnB;;ADjBL;;EAEsB,iBAAA,CAAA,IAAA,ECmCZ,aDnCY,EAAA,EAAA,iBAAA,CAAA,ECoCE,4BDpCF,CAAA,ECqCjB,ODrCiB,CAAA,IAAA,CAAA;EACK,QAAA,mBAAA;EAAR,QAAA,gBAAA;EAAO,QAAA,QAAA;EAGb;;;;EAqEM,gBAAA,CAAA,CAAA,ECwBS,ODxBT,CAAA,IAAA,CAAA;;;;;;;AD/EP,iBGFU,iBAAA,CHEY,OAAA,EGDvB,OHCuB,EAAA,QAAA,EGAtB,kBHAsB,CAAA,EGC/B,OHD+B,CAAA,IAAA,CAAA"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { AmqpConnectionManagerOptions, ChannelWrapper, ConnectionUrl } from "amqp-connection-manager";
|
|
1
|
+
import { AmqpConnectionManager, AmqpConnectionManagerOptions, ChannelWrapper, ConnectionUrl, CreateChannelOpts } from "amqp-connection-manager";
|
|
2
2
|
import { ContractDefinition } from "@amqp-contract/contract";
|
|
3
|
+
import { Channel } from "amqplib";
|
|
3
4
|
|
|
4
5
|
//#region src/logger.d.ts
|
|
5
6
|
|
|
@@ -31,7 +32,7 @@ type LoggerContext = Record<string, unknown> & {
|
|
|
31
32
|
* };
|
|
32
33
|
* ```
|
|
33
34
|
*/
|
|
34
|
-
|
|
35
|
+
type Logger = {
|
|
35
36
|
/**
|
|
36
37
|
* Log debug level messages
|
|
37
38
|
* @param message - The log message
|
|
@@ -56,22 +57,72 @@ interface Logger {
|
|
|
56
57
|
* @param context - Optional context to include with the log
|
|
57
58
|
*/
|
|
58
59
|
error(message: string, context?: LoggerContext): void;
|
|
59
|
-
}
|
|
60
|
+
};
|
|
60
61
|
//#endregion
|
|
61
|
-
//#region src/
|
|
62
|
+
//#region src/amqp-client.d.ts
|
|
62
63
|
type AmqpClientOptions = {
|
|
63
64
|
urls: ConnectionUrl[];
|
|
64
65
|
connectionOptions?: AmqpConnectionManagerOptions | undefined;
|
|
66
|
+
channelOptions?: Partial<CreateChannelOpts> | undefined;
|
|
65
67
|
};
|
|
66
68
|
declare class AmqpClient {
|
|
67
69
|
private readonly contract;
|
|
68
|
-
private readonly options;
|
|
69
70
|
private readonly connection;
|
|
70
71
|
readonly channel: ChannelWrapper;
|
|
72
|
+
private readonly urls;
|
|
73
|
+
private readonly connectionOptions?;
|
|
71
74
|
constructor(contract: ContractDefinition, options: AmqpClientOptions);
|
|
75
|
+
/**
|
|
76
|
+
* Get the underlying connection manager
|
|
77
|
+
*
|
|
78
|
+
* This method exposes the AmqpConnectionManager instance that this client uses.
|
|
79
|
+
* The connection is automatically shared across all AmqpClient instances that
|
|
80
|
+
* use the same URLs and connection options.
|
|
81
|
+
*
|
|
82
|
+
* @returns The AmqpConnectionManager instance used by this client
|
|
83
|
+
*/
|
|
84
|
+
getConnection(): AmqpConnectionManager;
|
|
72
85
|
close(): Promise<void>;
|
|
73
|
-
|
|
86
|
+
/**
|
|
87
|
+
* Reset connection singleton cache (for testing only)
|
|
88
|
+
* @internal
|
|
89
|
+
*/
|
|
90
|
+
static _resetConnectionCacheForTesting(): Promise<void>;
|
|
74
91
|
}
|
|
75
92
|
//#endregion
|
|
76
|
-
|
|
93
|
+
//#region src/connection-manager.d.ts
|
|
94
|
+
/**
|
|
95
|
+
* Connection manager singleton for sharing connections across clients
|
|
96
|
+
*/
|
|
97
|
+
declare class ConnectionManagerSingleton {
|
|
98
|
+
private static instance;
|
|
99
|
+
private connections;
|
|
100
|
+
private refCounts;
|
|
101
|
+
private constructor();
|
|
102
|
+
static getInstance(): ConnectionManagerSingleton;
|
|
103
|
+
/**
|
|
104
|
+
* Get or create a connection for the given URLs and options
|
|
105
|
+
*/
|
|
106
|
+
getConnection(urls: ConnectionUrl[], connectionOptions?: AmqpConnectionManagerOptions): AmqpConnectionManager;
|
|
107
|
+
/**
|
|
108
|
+
* Release a connection reference. If no more references exist, close the connection.
|
|
109
|
+
*/
|
|
110
|
+
releaseConnection(urls: ConnectionUrl[], connectionOptions?: AmqpConnectionManagerOptions): Promise<void>;
|
|
111
|
+
private createConnectionKey;
|
|
112
|
+
private serializeOptions;
|
|
113
|
+
private deepSort;
|
|
114
|
+
/**
|
|
115
|
+
* Reset all cached connections (for testing purposes)
|
|
116
|
+
* @internal
|
|
117
|
+
*/
|
|
118
|
+
_resetForTesting(): Promise<void>;
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
//#region src/setup.d.ts
|
|
122
|
+
/**
|
|
123
|
+
* Setup AMQP topology (exchanges, queues, and bindings) from a contract definition
|
|
124
|
+
*/
|
|
125
|
+
declare function setupAmqpTopology(channel: Channel, contract: ContractDefinition): Promise<void>;
|
|
126
|
+
//#endregion
|
|
127
|
+
export { AmqpClient, type AmqpClientOptions, ConnectionManagerSingleton, type Logger, type LoggerContext, setupAmqpTopology };
|
|
77
128
|
//# 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/
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/logger.ts","../src/amqp-client.ts","../src/connection-manager.ts","../src/setup.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IAAA,CAAA;EACK,QAAA,mBAAA;EAAR,QAAA,gBAAA;EAAO,QAAA,QAAA;EAGb;;;;EAqEM,gBAAA,CAAA,CAAA,ECwBS,ODxBT,CAAA,IAAA,CAAA;;;;;;;AD/EP,iBGFU,iBAAA,CHEY,OAAA,EGDvB,OHCuB,EAAA,QAAA,EGAtB,kBHAsB,CAAA,EGC/B,OHD+B,CAAA,IAAA,CAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,45 +1,159 @@
|
|
|
1
1
|
import amqp from "amqp-connection-manager";
|
|
2
2
|
|
|
3
|
-
//#region src/
|
|
3
|
+
//#region src/connection-manager.ts
|
|
4
|
+
/**
|
|
5
|
+
* Connection manager singleton for sharing connections across clients
|
|
6
|
+
*/
|
|
7
|
+
var ConnectionManagerSingleton = class ConnectionManagerSingleton {
|
|
8
|
+
static instance;
|
|
9
|
+
connections = /* @__PURE__ */ new Map();
|
|
10
|
+
refCounts = /* @__PURE__ */ new Map();
|
|
11
|
+
constructor() {}
|
|
12
|
+
static getInstance() {
|
|
13
|
+
if (!ConnectionManagerSingleton.instance) ConnectionManagerSingleton.instance = new ConnectionManagerSingleton();
|
|
14
|
+
return ConnectionManagerSingleton.instance;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Get or create a connection for the given URLs and options
|
|
18
|
+
*/
|
|
19
|
+
getConnection(urls, connectionOptions) {
|
|
20
|
+
const key = this.createConnectionKey(urls, connectionOptions);
|
|
21
|
+
if (!this.connections.has(key)) {
|
|
22
|
+
const connection = amqp.connect(urls, connectionOptions);
|
|
23
|
+
this.connections.set(key, connection);
|
|
24
|
+
this.refCounts.set(key, 0);
|
|
25
|
+
}
|
|
26
|
+
this.refCounts.set(key, (this.refCounts.get(key) ?? 0) + 1);
|
|
27
|
+
return this.connections.get(key);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Release a connection reference. If no more references exist, close the connection.
|
|
31
|
+
*/
|
|
32
|
+
async releaseConnection(urls, connectionOptions) {
|
|
33
|
+
const key = this.createConnectionKey(urls, connectionOptions);
|
|
34
|
+
const refCount = this.refCounts.get(key) ?? 0;
|
|
35
|
+
if (refCount <= 1) {
|
|
36
|
+
const connection = this.connections.get(key);
|
|
37
|
+
if (connection) {
|
|
38
|
+
await connection.close();
|
|
39
|
+
this.connections.delete(key);
|
|
40
|
+
this.refCounts.delete(key);
|
|
41
|
+
}
|
|
42
|
+
} else this.refCounts.set(key, refCount - 1);
|
|
43
|
+
}
|
|
44
|
+
createConnectionKey(urls, connectionOptions) {
|
|
45
|
+
return `${JSON.stringify(urls)}::${connectionOptions ? this.serializeOptions(connectionOptions) : ""}`;
|
|
46
|
+
}
|
|
47
|
+
serializeOptions(options) {
|
|
48
|
+
const sorted = this.deepSort(options);
|
|
49
|
+
return JSON.stringify(sorted);
|
|
50
|
+
}
|
|
51
|
+
deepSort(value) {
|
|
52
|
+
if (Array.isArray(value)) return value.map((item) => this.deepSort(item));
|
|
53
|
+
if (value !== null && typeof value === "object") {
|
|
54
|
+
const obj = value;
|
|
55
|
+
const sortedKeys = Object.keys(obj).sort();
|
|
56
|
+
const result = {};
|
|
57
|
+
for (const key of sortedKeys) result[key] = this.deepSort(obj[key]);
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Reset all cached connections (for testing purposes)
|
|
64
|
+
* @internal
|
|
65
|
+
*/
|
|
66
|
+
async _resetForTesting() {
|
|
67
|
+
const closePromises = Array.from(this.connections.values()).map((conn) => conn.close());
|
|
68
|
+
await Promise.all(closePromises);
|
|
69
|
+
this.connections.clear();
|
|
70
|
+
this.refCounts.clear();
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
//#endregion
|
|
75
|
+
//#region src/setup.ts
|
|
76
|
+
/**
|
|
77
|
+
* Setup AMQP topology (exchanges, queues, and bindings) from a contract definition
|
|
78
|
+
*/
|
|
79
|
+
async function setupAmqpTopology(channel, contract) {
|
|
80
|
+
const exchangeErrors = (await Promise.allSettled(Object.values(contract.exchanges ?? {}).map((exchange) => channel.assertExchange(exchange.name, exchange.type, {
|
|
81
|
+
durable: exchange.durable,
|
|
82
|
+
autoDelete: exchange.autoDelete,
|
|
83
|
+
internal: exchange.internal,
|
|
84
|
+
arguments: exchange.arguments
|
|
85
|
+
})))).filter((result) => result.status === "rejected");
|
|
86
|
+
if (exchangeErrors.length > 0) throw new AggregateError(exchangeErrors.map(({ reason }) => reason), "Failed to setup exchanges");
|
|
87
|
+
const queueErrors = (await Promise.allSettled(Object.values(contract.queues ?? {}).map((queue) => channel.assertQueue(queue.name, {
|
|
88
|
+
durable: queue.durable,
|
|
89
|
+
exclusive: queue.exclusive,
|
|
90
|
+
autoDelete: queue.autoDelete,
|
|
91
|
+
arguments: queue.arguments
|
|
92
|
+
})))).filter((result) => result.status === "rejected");
|
|
93
|
+
if (queueErrors.length > 0) throw new AggregateError(queueErrors.map(({ reason }) => reason), "Failed to setup queues");
|
|
94
|
+
const bindingErrors = (await Promise.allSettled(Object.values(contract.bindings ?? {}).map((binding) => {
|
|
95
|
+
if (binding.type === "queue") return channel.bindQueue(binding.queue.name, binding.exchange.name, binding.routingKey ?? "", binding.arguments);
|
|
96
|
+
return channel.bindExchange(binding.destination.name, binding.source.name, binding.routingKey ?? "", binding.arguments);
|
|
97
|
+
}))).filter((result) => result.status === "rejected");
|
|
98
|
+
if (bindingErrors.length > 0) throw new AggregateError(bindingErrors.map(({ reason }) => reason), "Failed to setup bindings");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
//#endregion
|
|
102
|
+
//#region src/amqp-client.ts
|
|
4
103
|
var AmqpClient = class {
|
|
5
104
|
connection;
|
|
6
105
|
channel;
|
|
106
|
+
urls;
|
|
107
|
+
connectionOptions;
|
|
7
108
|
constructor(contract, options) {
|
|
8
109
|
this.contract = contract;
|
|
9
|
-
this.
|
|
10
|
-
|
|
11
|
-
this.
|
|
110
|
+
this.urls = options.urls;
|
|
111
|
+
if (options.connectionOptions !== void 0) this.connectionOptions = options.connectionOptions;
|
|
112
|
+
this.connection = ConnectionManagerSingleton.getInstance().getConnection(options.urls, options.connectionOptions);
|
|
113
|
+
const defaultSetup = (channel) => setupAmqpTopology(channel, this.contract);
|
|
114
|
+
const { setup: userSetup, ...otherChannelOptions } = options.channelOptions ?? {};
|
|
115
|
+
const channelOpts = {
|
|
12
116
|
json: true,
|
|
13
|
-
setup:
|
|
14
|
-
|
|
117
|
+
setup: defaultSetup,
|
|
118
|
+
...otherChannelOptions
|
|
119
|
+
};
|
|
120
|
+
if (userSetup) channelOpts.setup = async (channel) => {
|
|
121
|
+
await defaultSetup(channel);
|
|
122
|
+
if (userSetup.length === 2) await new Promise((resolve, reject) => {
|
|
123
|
+
userSetup(channel, (error) => {
|
|
124
|
+
if (error) reject(error);
|
|
125
|
+
else resolve();
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
else await userSetup(channel);
|
|
129
|
+
};
|
|
130
|
+
this.channel = this.connection.createChannel(channelOpts);
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Get the underlying connection manager
|
|
134
|
+
*
|
|
135
|
+
* This method exposes the AmqpConnectionManager instance that this client uses.
|
|
136
|
+
* The connection is automatically shared across all AmqpClient instances that
|
|
137
|
+
* use the same URLs and connection options.
|
|
138
|
+
*
|
|
139
|
+
* @returns The AmqpConnectionManager instance used by this client
|
|
140
|
+
*/
|
|
141
|
+
getConnection() {
|
|
142
|
+
return this.connection;
|
|
15
143
|
}
|
|
16
144
|
async close() {
|
|
17
145
|
await this.channel.close();
|
|
18
|
-
await this.
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
})))).filter((result) => result.status === "rejected");
|
|
27
|
-
if (exchangeErrors.length > 0) throw new AggregateError(exchangeErrors.map(({ reason }) => reason), "Failed to setup exchanges");
|
|
28
|
-
const queueErrors = (await Promise.allSettled(Object.values(this.contract.queues ?? {}).map((queue) => channel.assertQueue(queue.name, {
|
|
29
|
-
durable: queue.durable,
|
|
30
|
-
exclusive: queue.exclusive,
|
|
31
|
-
autoDelete: queue.autoDelete,
|
|
32
|
-
arguments: queue.arguments
|
|
33
|
-
})))).filter((result) => result.status === "rejected");
|
|
34
|
-
if (queueErrors.length > 0) throw new AggregateError(queueErrors.map(({ reason }) => reason), "Failed to setup queues");
|
|
35
|
-
const bindingErrors = (await Promise.allSettled(Object.values(this.contract.bindings ?? {}).map((binding) => {
|
|
36
|
-
if (binding.type === "queue") return channel.bindQueue(binding.queue.name, binding.exchange.name, binding.routingKey ?? "", binding.arguments);
|
|
37
|
-
return channel.bindExchange(binding.destination.name, binding.source.name, binding.routingKey ?? "", binding.arguments);
|
|
38
|
-
}))).filter((result) => result.status === "rejected");
|
|
39
|
-
if (bindingErrors.length > 0) throw new AggregateError(bindingErrors.map(({ reason }) => reason), "Failed to setup bindings");
|
|
146
|
+
await ConnectionManagerSingleton.getInstance().releaseConnection(this.urls, this.connectionOptions);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Reset connection singleton cache (for testing only)
|
|
150
|
+
* @internal
|
|
151
|
+
*/
|
|
152
|
+
static async _resetConnectionCacheForTesting() {
|
|
153
|
+
await ConnectionManagerSingleton.getInstance()._resetForTesting();
|
|
40
154
|
}
|
|
41
155
|
};
|
|
42
156
|
|
|
43
157
|
//#endregion
|
|
44
|
-
export { AmqpClient };
|
|
158
|
+
export { AmqpClient, ConnectionManagerSingleton, setupAmqpTopology };
|
|
45
159
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["contract: ContractDefinition","options: AmqpClientOptions"],"sources":["../src/index.ts"],"sourcesContent":["import type { Channel } from \"amqplib\";\nimport type { ContractDefinition } from \"@amqp-contract/contract\";\nimport amqp, {\n AmqpConnectionManager,\n AmqpConnectionManagerOptions,\n ChannelWrapper,\n ConnectionUrl,\n} from \"amqp-connection-manager\";\n\nexport type { Logger, LoggerContext } from \"./logger.js\";\n\nexport type AmqpClientOptions = {\n urls: ConnectionUrl[];\n connectionOptions?: AmqpConnectionManagerOptions | undefined;\n};\n\nexport class AmqpClient {\n private readonly connection: AmqpConnectionManager;\n public readonly channel: ChannelWrapper;\n\n constructor(\n private readonly contract: ContractDefinition,\n private readonly options: AmqpClientOptions,\n ) {\n this.connection = amqp.connect(this.options.urls, this.options.connectionOptions);\n this.channel = this.connection.createChannel({\n json: true,\n setup: (channel: Channel) => this.setup(channel),\n });\n }\n\n async close(): Promise<void> {\n await this.channel.close();\n await this.connection.close();\n }\n\n private async setup(channel: Channel): Promise<void> {\n // Setup exchanges\n const exchangeResults = await Promise.allSettled(\n Object.values(this.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 // Setup queues\n const queueResults = await Promise.allSettled(\n Object.values(this.contract.queues ?? {}).map((queue) =>\n channel.assertQueue(queue.name, {\n durable: queue.durable,\n exclusive: queue.exclusive,\n autoDelete: queue.autoDelete,\n arguments: queue.arguments,\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(this.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}\n"],"mappings":";;;AAgBA,IAAa,aAAb,MAAwB;CACtB,AAAiB;CACjB,AAAgB;CAEhB,YACE,AAAiBA,UACjB,AAAiBC,SACjB;EAFiB;EACA;AAEjB,OAAK,aAAa,KAAK,QAAQ,KAAK,QAAQ,MAAM,KAAK,QAAQ,kBAAkB;AACjF,OAAK,UAAU,KAAK,WAAW,cAAc;GAC3C,MAAM;GACN,QAAQ,YAAqB,KAAK,MAAM,QAAQ;GACjD,CAAC;;CAGJ,MAAM,QAAuB;AAC3B,QAAM,KAAK,QAAQ,OAAO;AAC1B,QAAM,KAAK,WAAW,OAAO;;CAG/B,MAAc,MAAM,SAAiC;EAYnD,MAAM,kBAVkB,MAAM,QAAQ,WACpC,OAAO,OAAO,KAAK,SAAS,aAAa,EAAE,CAAC,CAAC,KAAK,aAChD,QAAQ,eAAe,SAAS,MAAM,SAAS,MAAM;GACnD,SAAS,SAAS;GAClB,YAAY,SAAS;GACrB,UAAU,SAAS;GACnB,WAAW,SAAS;GACrB,CAAC,CACH,CACF,EACsC,QACpC,WAA4C,OAAO,WAAW,WAChE;AACD,MAAI,eAAe,SAAS,EAC1B,OAAM,IAAI,eACR,eAAe,KAAK,EAAE,aAAa,OAAO,EAC1C,4BACD;EAcH,MAAM,eAVe,MAAM,QAAQ,WACjC,OAAO,OAAO,KAAK,SAAS,UAAU,EAAE,CAAC,CAAC,KAAK,UAC7C,QAAQ,YAAY,MAAM,MAAM;GAC9B,SAAS,MAAM;GACf,WAAW,MAAM;GACjB,YAAY,MAAM;GAClB,WAAW,MAAM;GAClB,CAAC,CACH,CACF,EACgC,QAC9B,WAA4C,OAAO,WAAW,WAChE;AACD,MAAI,YAAY,SAAS,EACvB,OAAM,IAAI,eACR,YAAY,KAAK,EAAE,aAAa,OAAO,EACvC,yBACD;EAuBH,MAAM,iBAnBiB,MAAM,QAAQ,WACnC,OAAO,OAAO,KAAK,SAAS,YAAY,EAAE,CAAC,CAAC,KAAK,YAAY;AAC3D,OAAI,QAAQ,SAAS,QACnB,QAAO,QAAQ,UACb,QAAQ,MAAM,MACd,QAAQ,SAAS,MACjB,QAAQ,cAAc,IACtB,QAAQ,UACT;AAGH,UAAO,QAAQ,aACb,QAAQ,YAAY,MACpB,QAAQ,OAAO,MACf,QAAQ,cAAc,IACtB,QAAQ,UACT;IACD,CACH,EACoC,QAClC,WAA4C,OAAO,WAAW,WAChE;AACD,MAAI,cAAc,SAAS,EACzB,OAAM,IAAI,eACR,cAAc,KAAK,EAAE,aAAa,OAAO,EACzC,2BACD"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["result: Record<string, unknown>","contract: ContractDefinition","channelOpts: CreateChannelOpts"],"sources":["../src/connection-manager.ts","../src/setup.ts","../src/amqp-client.ts"],"sourcesContent":["import amqp, {\n AmqpConnectionManager,\n AmqpConnectionManagerOptions,\n ConnectionUrl,\n} from \"amqp-connection-manager\";\n\n/**\n * Connection manager singleton for sharing connections across clients\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 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 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. If no more references exist, close the connection.\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 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 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 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","import type { Channel } from \"amqplib\";\nimport type { ContractDefinition } from \"@amqp-contract/contract\";\n\n/**\n * Setup AMQP topology (exchanges, queues, and bindings) from a contract definition\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 // Setup queues\n const queueResults = await Promise.allSettled(\n Object.values(contract.queues ?? {}).map((queue) =>\n channel.assertQueue(queue.name, {\n durable: queue.durable,\n exclusive: queue.exclusive,\n autoDelete: queue.autoDelete,\n arguments: queue.arguments,\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 } from \"amqplib\";\nimport { ConnectionManagerSingleton } from \"./connection-manager.js\";\nimport type { ContractDefinition } from \"@amqp-contract/contract\";\nimport { setupAmqpTopology } from \"./setup.js\";\n\nexport type AmqpClientOptions = {\n urls: ConnectionUrl[];\n connectionOptions?: AmqpConnectionManagerOptions | undefined;\n channelOptions?: Partial<CreateChannelOpts> | undefined;\n};\n\nexport class AmqpClient {\n private readonly connection: AmqpConnectionManager;\n public readonly channel: ChannelWrapper;\n private readonly urls: ConnectionUrl[];\n private readonly connectionOptions?: AmqpConnectionManagerOptions;\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.channel = 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 async close(): Promise<void> {\n await this.channel.close();\n // Release connection reference - will close connection if this was the last reference\n const singleton = ConnectionManagerSingleton.getInstance();\n await singleton.releaseConnection(this.urls, this.connectionOptions);\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"],"mappings":";;;;;;AASA,IAAa,6BAAb,MAAa,2BAA2B;CACtC,OAAe;CACf,AAAQ,8BAAkD,IAAI,KAAK;CACnE,AAAQ,4BAAiC,IAAI,KAAK;CAElD,AAAQ,cAAc;CAEtB,OAAO,cAA0C;AAC/C,MAAI,CAAC,2BAA2B,SAC9B,4BAA2B,WAAW,IAAI,4BAA4B;AAExE,SAAO,2BAA2B;;;;;CAMpC,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;;;;;CAMlC,MAAM,kBACJ,MACA,mBACe;EACf,MAAM,MAAM,KAAK,oBAAoB,MAAM,kBAAkB;EAC7D,MAAM,WAAW,KAAK,UA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F,MAAM,gBAAgB,YAAqB,kBAAkB,SAAS,KAAK,SAAS;EAGpF,MAAM,EAAE,OAAO,WAAW,GAAG,wBAAwB,QAAQ,kBAAkB,EAAE;EAGjF,MAAMC,cAAiC;GACrC,MAAM;GACN,OAAO;GACP,GAAG;GACJ;AAGD,MAAI,UACF,aAAY,QAAQ,OAAO,YAAqB;AAE9C,SAAM,aAAa,QAAQ;AAE3B,OAAI,UAAU,WAAW,EAEvB,OAAM,IAAI,SAAe,SAAS,WAAW;AAC3C,IAAC,UACC,UACC,UAAkB;AACjB,SAAI,MAAO,QAAO,MAAM;SACnB,UAAS;MAEjB;KACD;OAGF,OAAO,UAAkD,QAAQ;;AAKvE,OAAK,UAAU,KAAK,WAAW,cAAc,YAAY;;;;;;;;;;;CAY3D,gBAAuC;AACrC,SAAO,KAAK;;CAGd,MAAM,QAAuB;AAC3B,QAAM,KAAK,QAAQ,OAAO;AAG1B,QADkB,2BAA2B,aAAa,CAC1C,kBAAkB,KAAK,MAAM,KAAK,kBAAkB;;;;;;CAOtE,aAAa,kCAAiD;AAC5D,QAAM,2BAA2B,aAAa,CAAC,kBAAkB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amqp-contract/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Core utilities for AMQP setup and management in amqp-contract",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"amqp",
|
|
@@ -43,21 +43,23 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"amqp-connection-manager": "5.0.0",
|
|
45
45
|
"amqplib": "0.10.9",
|
|
46
|
-
"@amqp-contract/contract": "0.
|
|
46
|
+
"@amqp-contract/contract": "0.5.0"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
49
|
"@types/amqplib": "0.10.8",
|
|
50
50
|
"@vitest/coverage-v8": "4.0.16",
|
|
51
|
-
"tsdown": "0.18.
|
|
51
|
+
"tsdown": "0.18.3",
|
|
52
52
|
"typescript": "5.9.3",
|
|
53
53
|
"vitest": "4.0.16",
|
|
54
|
+
"@amqp-contract/testing": "0.5.0",
|
|
54
55
|
"@amqp-contract/tsconfig": "0.0.0"
|
|
55
56
|
},
|
|
56
57
|
"scripts": {
|
|
57
58
|
"build": "tsdown src/index.ts --format cjs,esm --dts --clean",
|
|
58
59
|
"dev": "tsdown src/index.ts --format cjs,esm --dts --watch",
|
|
59
|
-
"test": "vitest run",
|
|
60
|
-
"test:
|
|
60
|
+
"test": "vitest run --project unit",
|
|
61
|
+
"test:integration": "vitest run --project integration",
|
|
62
|
+
"test:watch": "vitest --project unit",
|
|
61
63
|
"typecheck": "tsc --noEmit"
|
|
62
64
|
}
|
|
63
65
|
}
|