amqp-extension 4.0.0 → 5.1.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 +328 -40
- package/dist/index.d.mts +356 -0
- package/dist/index.mjs +648 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +53 -39
- package/.editorconfig +0 -13
- package/.eslintrc +0 -27
- package/.husky/commit-msg +0 -4
- package/CHANGELOG.md +0 -149
- package/commitlint.config.js +0 -10
- package/dist/config/index.d.ts +0 -3
- package/dist/config/index.js +0 -25
- package/dist/config/module.d.ts +0 -2
- package/dist/config/module.js +0 -23
- package/dist/config/type.d.ts +0 -13
- package/dist/config/type.js +0 -8
- package/dist/consume/constants.d.ts +0 -1
- package/dist/consume/constants.js +0 -10
- package/dist/consume/index.d.ts +0 -3
- package/dist/consume/index.js +0 -25
- package/dist/consume/type.d.ts +0 -24
- package/dist/consume/type.js +0 -8
- package/dist/consume/utils.d.ts +0 -2
- package/dist/consume/utils.js +0 -16
- package/dist/exchange/constants.d.ts +0 -6
- package/dist/exchange/constants.js +0 -10
- package/dist/exchange/index.d.ts +0 -3
- package/dist/exchange/index.js +0 -19
- package/dist/exchange/type.d.ts +0 -8
- package/dist/exchange/type.js +0 -2
- package/dist/exchange/utils.d.ts +0 -4
- package/dist/exchange/utils.js +0 -13
- package/dist/index.d.ts +0 -6
- package/dist/index.js +0 -28
- package/dist/module.d.ts +0 -18
- package/dist/module.js +0 -187
- package/dist/publish/index.d.ts +0 -1
- package/dist/publish/index.js +0 -23
- package/dist/publish/type.d.ts +0 -7
- package/dist/publish/type.js +0 -8
- package/dist/type.d.ts +0 -14
- package/dist/type.js +0 -2
- package/dist/utils.d.ts +0 -2
- package/dist/utils.js +0 -23
- package/release.config.js +0 -3
- package/tsconfig.eslint.json +0 -12
package/README.MD
CHANGED
|
@@ -1,82 +1,370 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="./.github/assets/logo.svg" alt="amqp-extension" width="128" height="128" />
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
4
|
-
[](https://codecov.io/gh/Tada5hi/amqp-extension)
|
|
5
|
-
[](https://github.com/Tada5hi/amqp-extension)
|
|
6
|
-
[](https://snyk.io/test/github/Tada5hi/amqp-extension?targetFile=package.json)
|
|
7
|
-
[](https://github.com/semantic-release/semantic-release)
|
|
5
|
+
<h1 align="center">amqp-extension</h1>
|
|
8
6
|
|
|
9
|
-
|
|
7
|
+
<p align="center">
|
|
8
|
+
<b>Publish and consume RabbitMQ messages without the amqplib boilerplate.</b><br>
|
|
9
|
+
One <code>Client</code> takes care of reconnecting, declaring exchanges and queues, serializing payloads,<br>
|
|
10
|
+
routing messages to handlers and acknowledging them, so you write a call per operation and nothing else.
|
|
11
|
+
</p>
|
|
10
12
|
|
|
11
|
-
|
|
13
|
+
<p align="center">
|
|
14
|
+
<a href="https://npmjs.com/package/amqp-extension"><img src="https://badge.fury.io/js/amqp-extension.svg" alt="npm version" /></a>
|
|
15
|
+
<a href="https://github.com/Tada5hi/amqp-extension/actions/workflows/main.yml"><img src="https://github.com/Tada5hi/amqp-extension/actions/workflows/main.yml/badge.svg" alt="CI" /></a>
|
|
16
|
+
<a href="https://codecov.io/gh/Tada5hi/amqp-extension"><img src="https://codecov.io/gh/Tada5hi/amqp-extension/branch/master/graph/badge.svg?token=6YELWNP9HG" alt="codecov" /></a>
|
|
17
|
+
<a href="https://snyk.io/test/github/Tada5hi/amqp-extension?targetFile=package.json"><img src="https://snyk.io/test/github/Tada5hi/amqp-extension/badge.svg?targetFile=package.json" alt="Known Vulnerabilities" /></a>
|
|
18
|
+
<a href="https://conventionalcommits.org"><img src="https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white" alt="Conventional Commits" /></a>
|
|
19
|
+
</p>
|
|
20
|
+
|
|
21
|
+
<p align="center">
|
|
22
|
+
<a href="#installation"><b>Installation</b></a>
|
|
23
|
+
·
|
|
24
|
+
<a href="#usage">Usage</a>
|
|
25
|
+
·
|
|
26
|
+
<a href="#options">Options</a>
|
|
27
|
+
·
|
|
28
|
+
<a href="#api">API</a>
|
|
29
|
+
·
|
|
30
|
+
<a href="#notes">Notes</a>
|
|
31
|
+
</p>
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Why amqp-extension?
|
|
36
|
+
|
|
37
|
+
[amqplib](https://www.npmjs.com/package/amqplib) is a faithful, low-level AMQP 0-9-1 client. It gives you a connection and channels and leaves the rest to you. In practice, every service ends up rewriting the same layer on top: open a channel, assert the exchange, create and bind a queue, `JSON.stringify` the payload, `JSON.parse` it back, choose a handler, `ack` on success, `nack` on failure, and redo all of that after the broker restarts.
|
|
38
|
+
|
|
39
|
+
`amqp-extension` is that layer, written once:
|
|
40
|
+
|
|
41
|
+
| Concern | Plain amqplib | amqp-extension |
|
|
42
|
+
|---|---|---|
|
|
43
|
+
| **Reconnects** | A dropped connection stays dropped. You rebuild the connection, channels and topology yourself | Built on [amqp-connection-manager](https://www.npmjs.com/package/amqp-connection-manager): reconnects automatically and **replays exchange/queue setup** on every reconnect |
|
|
44
|
+
| **Topology** | `assertExchange`, `assertQueue` and `bindQueue` before every publish/consume | Asserted for you. Named exchanges get an exclusive, auto-deleted queue bound to your routing key, or a durable named one. The default exchange gets a durable queue |
|
|
45
|
+
| **Payloads** | `Buffer` in, `Buffer` out | Objects are sent as JSON, strings as UTF-8, and `Buffer`s pass through unchanged |
|
|
46
|
+
| **Dispatch** | One callback receives every message | A handler per message `type`, plus an `$any` fallback |
|
|
47
|
+
| **Acknowledgement** | Call `ack`/`nack` manually on every path, including errors | `ack` after the handler resolves, `nack` when it throws or nothing matches, with an optional requeue |
|
|
48
|
+
| **Defaults** | Pass the same options at every call site | Client-wide publish/consume defaults, deep-merged with per-call options |
|
|
49
|
+
| **Several exchanges** | A separate setup for each | `client.of(exchange)` reuses one connection |
|
|
50
|
+
|
|
51
|
+
The same consumer, side by side:
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
// amqplib
|
|
55
|
+
const connection = await amqplib.connect(url);
|
|
56
|
+
const channel = await connection.createChannel();
|
|
57
|
+
await channel.assertExchange('events', 'topic');
|
|
58
|
+
const { queue } = await channel.assertQueue('', { exclusive: true, autoDelete: true });
|
|
59
|
+
await channel.bindQueue(queue, 'events', 'user.*');
|
|
60
|
+
await channel.consume(queue, async (message) => {
|
|
61
|
+
if (!message) return;
|
|
62
|
+
try {
|
|
63
|
+
const payload = JSON.parse(message.content.toString('utf-8'));
|
|
64
|
+
if (message.properties.type === 'userCreated') await onUserCreated(payload);
|
|
65
|
+
channel.ack(message);
|
|
66
|
+
} catch (e) {
|
|
67
|
+
channel.nack(message, false, false);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
// ...and none of this survives a broker restart
|
|
71
|
+
|
|
72
|
+
// amqp-extension
|
|
73
|
+
const client = new Client({ connectionOptions: url, exchange: { name: 'events', type: 'topic' } });
|
|
74
|
+
await client.consume('user.*', {
|
|
75
|
+
userCreated: async (message) => onUserCreated(JSON.parse(message.content.toString('utf-8'))),
|
|
76
|
+
});
|
|
77
|
+
```
|
|
12
78
|
|
|
79
|
+
**Table of Contents**
|
|
13
80
|
- [Installation](#installation)
|
|
14
81
|
- [Usage](#usage)
|
|
82
|
+
- [Client](#client)
|
|
15
83
|
- [Publish](#publish)
|
|
16
84
|
- [Consume](#consume)
|
|
85
|
+
- [Multiple exchanges](#multiple-exchanges)
|
|
86
|
+
- [Errors](#errors)
|
|
87
|
+
- [Options](#options)
|
|
88
|
+
- [Queue options](#queue-options)
|
|
89
|
+
- [API](#api)
|
|
90
|
+
- [Notes](#notes)
|
|
17
91
|
- [License](#license)
|
|
18
92
|
|
|
19
|
-
|
|
20
93
|
## Installation
|
|
21
94
|
|
|
22
95
|
```bash
|
|
23
96
|
npm install amqp-extension --save
|
|
24
97
|
```
|
|
25
98
|
|
|
99
|
+
The package is ESM-only and requires Node.js `>=22`.
|
|
100
|
+
|
|
26
101
|
## Usage
|
|
27
102
|
|
|
28
|
-
###
|
|
103
|
+
### Client
|
|
29
104
|
|
|
30
|
-
|
|
105
|
+
A `Client` owns one connection and is bound to one exchange. Leave out `exchange` to use the **default exchange**, which routes each message straight to the queue named in the call.
|
|
31
106
|
|
|
32
107
|
```typescript
|
|
33
|
-
import { Client } from
|
|
108
|
+
import { Client } from 'amqp-extension';
|
|
34
109
|
|
|
35
110
|
const client = new Client({
|
|
36
111
|
connectionOptions: 'amqp://<user>:<password>@<host>',
|
|
37
112
|
exchange: {
|
|
38
|
-
name: '
|
|
39
|
-
type: 'topic'
|
|
40
|
-
}
|
|
113
|
+
name: 'events',
|
|
114
|
+
type: 'topic',
|
|
115
|
+
},
|
|
41
116
|
});
|
|
117
|
+
```
|
|
42
118
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
119
|
+
You can pass an existing [amqp-connection-manager](https://www.npmjs.com/package/amqp-connection-manager) connection as `connection` instead of `connectionOptions`.
|
|
120
|
+
`connectionManagerOptions` is passed to amqp-connection-manager's `connect()`, e.g. to change the delay between reconnect attempts (default: 5 s):
|
|
121
|
+
|
|
122
|
+
```typescript
|
|
123
|
+
const client = new Client({
|
|
124
|
+
connectionOptions: 'amqp://<user>:<password>@<host>',
|
|
125
|
+
connectionManagerOptions: { reconnectTimeInSeconds: 1 },
|
|
126
|
+
});
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Publish
|
|
130
|
+
|
|
131
|
+
`publish(to, data, options?)` sends `data` with `to` as the routing key, or as the queue name on the default exchange. It resolves to `true` once the message is handed to the broker.
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
await client.publish('user.created', { id: 1, name: 'admin' }, {
|
|
135
|
+
type: 'userCreated',
|
|
136
|
+
persistent: true,
|
|
137
|
+
});
|
|
48
138
|
```
|
|
49
139
|
|
|
50
140
|
### Consume
|
|
51
141
|
|
|
52
|
-
|
|
142
|
+
`consume(from, options?, handlers)` subscribes to messages matching `from` and routes each one to the handler named after its `type` property. A message with no matching handler goes to `$any`.
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
import type { ConsumeMessage } from 'amqp-extension';
|
|
146
|
+
|
|
147
|
+
await client.consume('user.*', {
|
|
148
|
+
userCreated: async (message: ConsumeMessage) => {
|
|
149
|
+
const payload = JSON.parse(message.content.toString('utf-8'));
|
|
150
|
+
// { id: 1, name: 'admin' }
|
|
151
|
+
},
|
|
152
|
+
$any: async (message: ConsumeMessage) => {
|
|
153
|
+
// every other type
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
A handler that resolves acknowledges the message. A handler that throws, or a message with no matching handler, gets a `nack`. Pass `onError` to see these failures: it is called after the `nack` with the handler's error, or with a `ClientError` (`HANDLER_MISSING`) when no handler matched. Its own errors are swallowed.
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
await client.consume('user.*', {
|
|
162
|
+
onError: (error, message) => logger.error(error, { type: message.properties.type }),
|
|
163
|
+
}, {
|
|
164
|
+
userCreated: async (message) => { /* ... */ },
|
|
165
|
+
});
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`consume()` resolves a `Consumer` once the subscription is in place. `cancel()` stops new deliveries, waits for the handlers still running (their messages are acked or nacked as usual), then closes the consumer's channel. It never rejects, and the consumer is not re-registered after a reconnect. `await using` cancels it when the scope ends:
|
|
169
|
+
|
|
170
|
+
```typescript
|
|
171
|
+
const consumer = await client.consume('user.*', { $any: async (message) => { /* ... */ } });
|
|
172
|
+
// ...
|
|
173
|
+
await consumer.cancel();
|
|
174
|
+
|
|
175
|
+
{
|
|
176
|
+
await using scoped = await client.consume('jobs', { $any: async (message) => { /* ... */ } });
|
|
177
|
+
// ...
|
|
178
|
+
} // cancelled here
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
Both methods also accept a single context object: `client.publish({ to, data, options })`, `client.consume({ from, options, handlers })`.
|
|
182
|
+
|
|
183
|
+
### Retry & redelivery
|
|
184
|
+
|
|
185
|
+
By default a failed message is `nack`ed once and dropped (or requeued with `requeueOnFailure`). Pass `retry` to retry it instead:
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
await client.consume('jobs', {
|
|
189
|
+
prefetchCount: 1,
|
|
190
|
+
retry: { maxAttempts: 5, delay: 1_000 },
|
|
191
|
+
onError: (error) => logger.warn(error),
|
|
192
|
+
}, {
|
|
193
|
+
$any: async (message) => { /* ... */ },
|
|
194
|
+
});
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
When a handler throws, the message is re-published to the queue it came from (through the default exchange, by queue name) with its content and properties, and the next attempt in the `x-attempt` header (1-based: a first delivery has none and counts as attempt 1). The original is acked once the broker confirmed the copy. Attempt `n` waits `delay * 2^(n - 2)` ms before it is re-published (1s, 2s, 4s, ... with the defaults), capped at 30s.
|
|
198
|
+
|
|
199
|
+
| Option | Default | Purpose |
|
|
200
|
+
|---|---|---|
|
|
201
|
+
| `retry.maxAttempts` | `5` | Delivery attempts before the message is dropped: it is acked and `onError` receives a `ClientError` (`ATTEMPTS_EXHAUSTED`) with the last handler error as `cause` |
|
|
202
|
+
| `retry.delay` | `1000` | Base of the exponential backoff in ms |
|
|
203
|
+
| `ordered` | `false` | See the redelivery guard below |
|
|
204
|
+
|
|
205
|
+
- **Delivery is at-least-once.** A crash between the re-publish and the ack delivers the message twice; make handlers idempotent.
|
|
206
|
+
- **There is no dead-letter queue.** An exhausted message is dropped, so log it in `onError` if it must be replayed.
|
|
207
|
+
- **The backoff holds the prefetch slot.** With `prefetchCount: 1` the consumer handles nothing else while it waits, so keep `delay` in seconds.
|
|
208
|
+
- **A re-published message goes to the end of the queue**, so a retried message can be handled after a later one.
|
|
209
|
+
- **A missing or invalid `x-attempt` header counts as attempt 1**, so a publisher that counts attempts elsewhere at worst gets more retries, never fewer.
|
|
210
|
+
- A missing handler is not retried, and `retry` has no effect with `noAck`.
|
|
211
|
+
- If the re-publish itself fails, or the broker does not confirm it within 30 s (e.g. it is unreachable), the original is `nack`ed with requeue and comes back as a redelivery. A copy the broker took but confirmed late is then delivered as well (at-least-once).
|
|
212
|
+
- `onError` is called after every failed attempt with the handler's error, and once with `ATTEMPTS_EXHAUSTED` when the message is dropped.
|
|
213
|
+
- The message's `userId` is not copied: the broker rejects one that is not the re-publishing connection's user.
|
|
214
|
+
|
|
215
|
+
With `retry`, messages carrying a `messageId` are also guarded against redeliveries:
|
|
216
|
+
|
|
217
|
+
- A redelivered copy of a message this consumer is **still handling** (its channel was reset, e.g. on a reconnect, while the handler ran) is not run again. It is acked right away, or, with `ordered: true`, only once the original has settled. Acking it early frees the prefetch slot, so on a `singleActiveConsumer` queue the next message would run next to the original.
|
|
218
|
+
- A redelivered message this consumer is **not** handling counts as a failed attempt and is retried without running the handler first. Usually a consumer died while handling it (a crash, the broker's `consumer_timeout`), but it can also be a message whose handler succeeded and whose ack was lost to a channel reset: that message runs again (at-least-once).
|
|
219
|
+
|
|
220
|
+
The guard is per `consume()` call: a redelivery that lands on another consumer or process runs again. Messages without a `messageId` are not guarded.
|
|
221
|
+
|
|
222
|
+
### Multiple exchanges
|
|
223
|
+
|
|
224
|
+
`of(exchange)` returns a client bound to another exchange. It shares the same connection and default options.
|
|
225
|
+
|
|
226
|
+
```typescript
|
|
227
|
+
const notifications = client.of({ name: 'notifications', type: 'fanout' });
|
|
228
|
+
|
|
229
|
+
// fanout ignores the routing key, but publish still requires a non-empty one
|
|
230
|
+
await notifications.publish('deploy', { message: 'deploy finished' });
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
By default, `consume` on a named exchange binds an exclusive, temporary queue that lives only as long as the consumer. Pass `queue` to bind a durable, named queue instead: once a `consume` has declared it, it keeps the messages published while no consumer runs, and consumers sharing it split the messages between them. `publish` declares only the exchange, so messages published before the first `consume` are dropped. Queue options apply to it too.
|
|
234
|
+
|
|
53
235
|
```typescript
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
}
|
|
236
|
+
const events = client.of({ name: 'events', type: 'topic' });
|
|
237
|
+
|
|
238
|
+
await events.consume('user.*', { queue: 'audit', queueType: 'quorum' }, {
|
|
239
|
+
$any: async (message) => { /* ... */ },
|
|
240
|
+
});
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
The binding stays on the broker: consuming the same `queue` with another `from` adds a binding, it does not replace the old one. On the default exchange, `queue` is ignored, because `from` already is the queue name.
|
|
244
|
+
|
|
245
|
+
Pass `queue` per call rather than in the client's `consumeOptions`: a default applies to every `consume` of the client and its `of()` siblings, binding one queue to all of them. Consumers sharing a `queue` should register the same handlers, because a message reaches only one of them, and one without a matching handler nacks it (and drops it, unless `requeueOnFailure`).
|
|
246
|
+
|
|
247
|
+
### Errors
|
|
248
|
+
|
|
249
|
+
`publish()` and `consume()` reject only with subclasses of `AmqpExtensionError` (built on [`@ebec/core`](https://www.npmjs.com/package/@ebec/core)). Check the category with `instanceof` and the specific failure with `code`:
|
|
250
|
+
|
|
251
|
+
| Class | `code` |
|
|
252
|
+
|---|---|
|
|
253
|
+
| `TopologyError` | `QUEUE_NAME_EMPTY`, `EXCHANGE_NAME_MISSING`, `DESTINATION_MISSING` |
|
|
254
|
+
| `ClientError` | `CLIENT_CLOSED`, `CHANNEL_CLOSED`, `PUBLISH_TIMEOUT`, `HANDLER_MISSING` and `ATTEMPTS_EXHAUSTED` (passed to `onError` only) |
|
|
255
|
+
| `BrokerError` | `BROKER_REJECTED`, with the AMQP reply code as `replyCode` |
|
|
256
|
+
| `SerializationError` | `SERIALIZATION_FAILED` |
|
|
257
|
+
|
|
258
|
+
```typescript
|
|
259
|
+
import { BrokerError, ClientError, ErrorCode } from 'amqp-extension';
|
|
260
|
+
|
|
261
|
+
try {
|
|
262
|
+
await client.publish('jobs', payload, { timeout: 5_000 });
|
|
263
|
+
} catch (e) {
|
|
264
|
+
if (e instanceof BrokerError && e.replyCode === 406) {
|
|
265
|
+
// queue re-declared with different arguments
|
|
266
|
+
} else if (e instanceof ClientError && e.code === ErrorCode.PUBLISH_TIMEOUT) {
|
|
267
|
+
// broker unreachable
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
The original amqplib / amqp-connection-manager error is available as `cause`.
|
|
273
|
+
`instanceof` also matches errors from a duplicate copy of the library (e.g. two versions in `node_modules`). Errors that crossed a process boundary as JSON (`toJSON()`) are recognized by the guards `isAmqpExtensionError`, `isTopologyError`, `isClientError`, `isBrokerError` and `isSerializationError`.
|
|
274
|
+
A failure the library does not recognize surfaces as the base `AmqpExtensionError` with code `AMQP_EXTENSION_ERROR`, and the original error as `cause`.
|
|
59
275
|
|
|
276
|
+
Earlier releases rejected invalid input with a plain `SyntaxError` or `Error`. Replace `instanceof SyntaxError` checks with `instanceof TopologyError`; the messages are unchanged.
|
|
277
|
+
|
|
278
|
+
## Options
|
|
279
|
+
|
|
280
|
+
Client-wide defaults go into the constructor. Per-call options are deep-merged on top of them, and the per-call value wins.
|
|
281
|
+
|
|
282
|
+
```typescript
|
|
60
283
|
const client = new Client({
|
|
61
284
|
connectionOptions: 'amqp://<user>:<password>@<host>',
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
type: 'topic'
|
|
65
|
-
}
|
|
285
|
+
publishOptions: { persistent: true },
|
|
286
|
+
consumeOptions: { prefetchCount: 10, requeueOnFailure: true },
|
|
66
287
|
});
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
`publishOptions` and `consumeOptions` accept every amqplib `Options.Publish` / `Options.Consume` field, plus:
|
|
291
|
+
|
|
292
|
+
| Option | Applies to | Default | Purpose |
|
|
293
|
+
|---|---|---|---|
|
|
294
|
+
| `requeueOnFailure` | consume | `false` | Requeue messages that are `nack`ed because a handler threw or none matched |
|
|
295
|
+
| `queue` | consume | none | Named exchanges only: consume through this durable, named queue instead of a temporary one (see [Multiple exchanges](#multiple-exchanges)) |
|
|
296
|
+
| `prefetchCount` | consume | none | Maximum number of unacknowledged messages per consumer (`channel.prefetch`) |
|
|
297
|
+
| `noAck` | consume | `false` | amqplib option. When `true`, no `ack`/`nack` is sent at all |
|
|
298
|
+
| `retry` | consume | none | `{ maxAttempts?, delay? }`: retry messages whose handler threw (see [Retry & redelivery](#retry--redelivery)) |
|
|
299
|
+
| `ordered` | consume | `false` | With `retry`: hold a redelivered copy of a message still being handled until the original settles |
|
|
300
|
+
| `onError` | consume | none | `(error, message) => void \| Promise<void>`, called when a handler threw or none matched (also with `noAck`). A call-site `onError` replaces the client default |
|
|
301
|
+
| Queue options | both | none | `queueType`, `deliveryLimit`, `deadLetterExchange`, `deadLetterRoutingKey`, `messageTtl`, `maxLength`, `singleActiveConsumer` (see below) |
|
|
302
|
+
| `timeout` | publish | none | Milliseconds to wait for the broker to take the message before rejecting with a `ClientError` (`PUBLISH_TIMEOUT`), e.g. while it is unreachable. Without it the call waits for the reconnect |
|
|
303
|
+
|
|
304
|
+
### Queue options
|
|
305
|
+
|
|
306
|
+
On the default exchange, `consume` and `publish` assert a named, durable queue. Queue options are set flat on the publish/consume options and map to queue arguments. They also apply to the named queue of a `consume` with `queue` on a named exchange; otherwise named exchanges ignore them.
|
|
307
|
+
|
|
308
|
+
| Option | Queue argument | Purpose |
|
|
309
|
+
|---|---|---|
|
|
310
|
+
| `queueType` | `x-queue-type` | `'classic'` or `'quorum'` |
|
|
311
|
+
| `deliveryLimit` | `x-delivery-limit` | Drop or dead-letter a message after this many failed deliveries (quorum queues only). Counts only requeued messages: needs `requeueOnFailure: true`, otherwise a failed message is dropped or dead-lettered on its first failure |
|
|
312
|
+
| `deadLetterExchange` | `x-dead-letter-exchange` | Exchange that rejected or expired messages are republished to |
|
|
313
|
+
| `deadLetterRoutingKey` | `x-dead-letter-routing-key` | Routing key for dead-lettered messages |
|
|
314
|
+
| `messageTtl` | `x-message-ttl` | Expire messages after this many milliseconds in the queue |
|
|
315
|
+
| `maxLength` | `x-max-length` | Maximum number of ready messages, the oldest are dropped or dead-lettered beyond it |
|
|
316
|
+
| `singleActiveConsumer` | `x-single-active-consumer` | Deliver to one consumer at a time, in publish order, and fail over to another when it goes away |
|
|
317
|
+
|
|
318
|
+
They are not validated client-side: the broker rejects an invalid combination with a `BrokerError`. It also rejects re-declaring a queue with different arguments, so publisher and consumer must pass the same options.
|
|
319
|
+
|
|
320
|
+
Await the first `consume` (or `publish`) of a new quorum queue before running publisher and consumer concurrently: RabbitMQ 3.13 can crash the channel when a quorum queue is consumed while another channel is still creating it, which drops the connection until it reconnects. Concurrent first publishes to it can also be rejected (`message nacked`) and need a retry.
|
|
67
321
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
322
|
+
```typescript
|
|
323
|
+
import { Client } from 'amqp-extension';
|
|
324
|
+
|
|
325
|
+
// no exchange: the default exchange routes to the queue named in each call
|
|
326
|
+
const client = new Client({
|
|
327
|
+
connectionOptions: 'amqp://<user>:<password>@<host>',
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
const queueOptions = { queueType: 'quorum', singleActiveConsumer: true } as const;
|
|
331
|
+
|
|
332
|
+
await client.consume('<queue>', { ...queueOptions, prefetchCount: 1 }, {
|
|
333
|
+
$any: async (message) => { /* ... */ },
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
await client.publish('<queue>', { foo: 'bar' }, queueOptions);
|
|
78
337
|
```
|
|
79
338
|
|
|
339
|
+
## API
|
|
340
|
+
|
|
341
|
+
| Export | Kind | Purpose |
|
|
342
|
+
|---|---|---|
|
|
343
|
+
| `Client` | class | `publish()`, `consume()`, `of()`, `close()`, `[Symbol.asyncDispose]()`, plus the underlying `connection` |
|
|
344
|
+
| `ClientContext` | type | Constructor input: `connection` / `connectionOptions`, `connectionManagerOptions`, `exchange`, `publishOptions`, `consumeOptions` |
|
|
345
|
+
| `ExchangeType` | enum | `direct` (default exchange), `topic`, `fanout`, `headers` |
|
|
346
|
+
| `ConsumeHandlers` | type | Map from message `type` to handler, with the `$any` fallback key |
|
|
347
|
+
| `Consumer` | type | Resolved by `consume()`: `cancel()` and `[Symbol.asyncDispose]()` |
|
|
348
|
+
| `ConsumeOptions` / `PublishOptions` | type | amqplib options plus the extensions listed above |
|
|
349
|
+
| `QueueOptions` | type | Queue arguments (`queueType`, `deliveryLimit`, `deadLetterExchange`, `deadLetterRoutingKey`, `messageTtl`, `maxLength`, `singleActiveConsumer`), part of both `ConsumeOptions` and `PublishOptions` |
|
|
350
|
+
| `ConsumeRetryOptions` | type | `retry` consume option: `maxAttempts`, `delay` |
|
|
351
|
+
| `ATTEMPT_HEADER`, `resolveAttempt` | constant / function | The `x-attempt` header name, and reading the attempt from message properties |
|
|
352
|
+
| `ConsumeMessage` | type | Re-export of amqplib's message type |
|
|
353
|
+
| `AmqpExtensionError`, `TopologyError`, `ClientError`, `BrokerError`, `SerializationError` | class | Error tree, see [Errors](#errors) |
|
|
354
|
+
| `ErrorCode` | enum | Stable error codes |
|
|
355
|
+
| `isAmqpExtensionError`, `isTopologyError`, `isClientError`, `isBrokerError`, `isSerializationError` | function | Error guards that also match duplicate library copies and JSON round-trips |
|
|
356
|
+
|
|
357
|
+
## Notes
|
|
358
|
+
|
|
359
|
+
- **Close the client when you are done:** `await client.close()`. It closes the shared connection, so every `of()` sibling stops too. Nothing is closed automatically on `SIGINT`; hook it into your app's shutdown, e.g. `process.once('SIGTERM', () => client.close())`. For scoped code (scripts, jobs, tests) use `await using client = new Client(...)`: the client closes when the scope ends, also on a throw. Disposal runs at scope exit, not on a signal, and like `close()` it closes the shared connection, so use it on the root client rather than on `of()` siblings.
|
|
360
|
+
- **Broker errors reject the call.** If the broker rejects the setup, e.g. `PRECONDITION_FAILED` for a queue re-declared with different queue options or `ACCESS_REFUSED` for a queue that is already consumed exclusively, `publish()` / `consume()` reject with a `BrokerError` (the amqplib error is its `cause`). Only that channel closes; the connection stays up. A connection that merely drops during the call is not an error: the call completes after the reconnect (`publish` is bounded by its `timeout` option).
|
|
361
|
+
- **Calls after `close()` reject** with a `ClientError` (`CLIENT_CLOSED`), also on `of()` siblings.
|
|
362
|
+
- **A consumer cancelled by the broker stays cancelled**, e.g. when its queue is deleted. Call `consume()` again after re-creating the queue.
|
|
363
|
+
- **Invalid input rejects before anything touches the broker:** an empty queue name on the default exchange, a named exchange type without a `name`, or an empty routing key when publishing to a named exchange, with a `TopologyError`.
|
|
364
|
+
- **Unconsumed fanout/topic messages are dropped**, unless `consume` passes `queue` and has declared it at least once. Without it, named exchanges bind an exclusive, auto-deleted queue per `consume` call, which lives only as long as that consumer.
|
|
365
|
+
- **Handler errors are not rethrown.** They are passed to the `onError` consume option, if set.
|
|
366
|
+
- **`cancel()` waits for a retry in its backoff** (up to 30s), because the message is settled only after it was re-published.
|
|
367
|
+
|
|
80
368
|
## License
|
|
81
369
|
|
|
82
370
|
Made with 💚
|