amqp-extension 5.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 +45 -1
- package/dist/index.d.mts +88 -19
- package/dist/index.mjs +164 -18
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.MD
CHANGED
|
@@ -180,6 +180,45 @@ await consumer.cancel();
|
|
|
180
180
|
|
|
181
181
|
Both methods also accept a single context object: `client.publish({ to, data, options })`, `client.consume({ from, options, handlers })`.
|
|
182
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
|
+
|
|
183
222
|
### Multiple exchanges
|
|
184
223
|
|
|
185
224
|
`of(exchange)` returns a client bound to another exchange. It shares the same connection and default options.
|
|
@@ -212,7 +251,7 @@ Pass `queue` per call rather than in the client's `consumeOptions`: a default ap
|
|
|
212
251
|
| Class | `code` |
|
|
213
252
|
|---|---|
|
|
214
253
|
| `TopologyError` | `QUEUE_NAME_EMPTY`, `EXCHANGE_NAME_MISSING`, `DESTINATION_MISSING` |
|
|
215
|
-
| `ClientError` | `CLIENT_CLOSED`, `CHANNEL_CLOSED`, `PUBLISH_TIMEOUT`, `HANDLER_MISSING` (passed to `onError` only) |
|
|
254
|
+
| `ClientError` | `CLIENT_CLOSED`, `CHANNEL_CLOSED`, `PUBLISH_TIMEOUT`, `HANDLER_MISSING` and `ATTEMPTS_EXHAUSTED` (passed to `onError` only) |
|
|
216
255
|
| `BrokerError` | `BROKER_REJECTED`, with the AMQP reply code as `replyCode` |
|
|
217
256
|
| `SerializationError` | `SERIALIZATION_FAILED` |
|
|
218
257
|
|
|
@@ -256,6 +295,8 @@ const client = new Client({
|
|
|
256
295
|
| `queue` | consume | none | Named exchanges only: consume through this durable, named queue instead of a temporary one (see [Multiple exchanges](#multiple-exchanges)) |
|
|
257
296
|
| `prefetchCount` | consume | none | Maximum number of unacknowledged messages per consumer (`channel.prefetch`) |
|
|
258
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 |
|
|
259
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 |
|
|
260
301
|
| Queue options | both | none | `queueType`, `deliveryLimit`, `deadLetterExchange`, `deadLetterRoutingKey`, `messageTtl`, `maxLength`, `singleActiveConsumer` (see below) |
|
|
261
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 |
|
|
@@ -306,6 +347,8 @@ await client.publish('<queue>', { foo: 'bar' }, queueOptions);
|
|
|
306
347
|
| `Consumer` | type | Resolved by `consume()`: `cancel()` and `[Symbol.asyncDispose]()` |
|
|
307
348
|
| `ConsumeOptions` / `PublishOptions` | type | amqplib options plus the extensions listed above |
|
|
308
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 |
|
|
309
352
|
| `ConsumeMessage` | type | Re-export of amqplib's message type |
|
|
310
353
|
| `AmqpExtensionError`, `TopologyError`, `ClientError`, `BrokerError`, `SerializationError` | class | Error tree, see [Errors](#errors) |
|
|
311
354
|
| `ErrorCode` | enum | Stable error codes |
|
|
@@ -320,6 +363,7 @@ await client.publish('<queue>', { foo: 'bar' }, queueOptions);
|
|
|
320
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`.
|
|
321
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.
|
|
322
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.
|
|
323
367
|
|
|
324
368
|
## License
|
|
325
369
|
|
package/dist/index.d.mts
CHANGED
|
@@ -52,6 +52,31 @@ export type QueueOptions = {
|
|
|
52
52
|
singleActiveConsumer?: boolean;
|
|
53
53
|
};
|
|
54
54
|
//#endregion
|
|
55
|
+
//#region src/publish/types.d.ts
|
|
56
|
+
/**
|
|
57
|
+
* The AMQP properties of a published message (type, messageId, headers, persistent, …).
|
|
58
|
+
*/
|
|
59
|
+
type PublishProperties = Options.Publish;
|
|
60
|
+
/**
|
|
61
|
+
* The properties a message is re-published with for a retry.
|
|
62
|
+
*/
|
|
63
|
+
export type RepublishOptions = PublishProperties;
|
|
64
|
+
export type PublishOptions = PublishProperties & QueueOptions & {
|
|
65
|
+
/**
|
|
66
|
+
* Reject with ClientError (PUBLISH_TIMEOUT) when the message is not
|
|
67
|
+
* handed to the broker within this many milliseconds, e.g. while the
|
|
68
|
+
* broker is unreachable and the connection manager is reconnecting.
|
|
69
|
+
*
|
|
70
|
+
* Default: undefined (wait for the reconnect)
|
|
71
|
+
*/
|
|
72
|
+
timeout?: number;
|
|
73
|
+
};
|
|
74
|
+
export type PublishContext = {
|
|
75
|
+
to: string;
|
|
76
|
+
data: any;
|
|
77
|
+
options?: PublishOptions;
|
|
78
|
+
};
|
|
79
|
+
//#endregion
|
|
55
80
|
//#region src/consume/types.d.ts
|
|
56
81
|
export type ConsumeMessageHandler = (message: ConsumeMessage, channel: Channel) => Promise<void> | void;
|
|
57
82
|
export type ConsumeHandlers = {
|
|
@@ -59,6 +84,20 @@ export type ConsumeHandlers = {
|
|
|
59
84
|
} & {
|
|
60
85
|
[key: string]: ConsumeMessageHandler;
|
|
61
86
|
};
|
|
87
|
+
export type ConsumeRetryOptions = {
|
|
88
|
+
/**
|
|
89
|
+
* Delivery attempts before a failing message is dropped (acked, onError gets ATTEMPTS_EXHAUSTED).
|
|
90
|
+
*
|
|
91
|
+
* Default: 5
|
|
92
|
+
*/
|
|
93
|
+
maxAttempts?: number;
|
|
94
|
+
/**
|
|
95
|
+
* Base of the exponential backoff in ms, capped at 30s.
|
|
96
|
+
*
|
|
97
|
+
* Default: 1000
|
|
98
|
+
*/
|
|
99
|
+
delay?: number;
|
|
100
|
+
};
|
|
62
101
|
export type ConsumeOptions = Options.Consume & QueueOptions & {
|
|
63
102
|
/**
|
|
64
103
|
* Default: false
|
|
@@ -78,8 +117,29 @@ export type ConsumeOptions = Options.Consume & QueueOptions & {
|
|
|
78
117
|
*/
|
|
79
118
|
queue?: string;
|
|
80
119
|
/**
|
|
81
|
-
*
|
|
82
|
-
*
|
|
120
|
+
* Retry a message whose handler threw: re-publish it to the queue it came from with
|
|
121
|
+
* the next attempt in its x-attempt header (after a backoff), then ack the original.
|
|
122
|
+
* Also guards against redeliveries of messages with a messageId: a copy of a message
|
|
123
|
+
* still being handled in this consumer is not run again, and a redelivery of one that
|
|
124
|
+
* is not (the consumer died mid-handling) counts as a failed attempt.
|
|
125
|
+
* Ignored with noAck. A missing handler is not retried.
|
|
126
|
+
*
|
|
127
|
+
* Default: undefined (no retry)
|
|
128
|
+
*/
|
|
129
|
+
retry?: ConsumeRetryOptions;
|
|
130
|
+
/**
|
|
131
|
+
* With retry: hold a redelivered copy of a message still being handled until the
|
|
132
|
+
* original settles, instead of acking it right away. Acking it would free the
|
|
133
|
+
* prefetch slot and let the next message of an ordered stream run next to the original.
|
|
134
|
+
*
|
|
135
|
+
* Default: false
|
|
136
|
+
*/
|
|
137
|
+
ordered?: boolean;
|
|
138
|
+
/**
|
|
139
|
+
* Called after a message was nacked, retried (or not settled, with noAck) because its handler threw
|
|
140
|
+
* (with that error) or no handler matched (with a ClientError, code HANDLER_MISSING), and after
|
|
141
|
+
* a message was dropped because its retry attempts were exhausted (with a ClientError, code
|
|
142
|
+
* ATTEMPTS_EXHAUSTED, the last handler error as cause).
|
|
83
143
|
* Its own errors are swallowed.
|
|
84
144
|
*/
|
|
85
145
|
onError?: (error: unknown, message: ConsumeMessage) => Promise<void> | void;
|
|
@@ -101,6 +161,20 @@ export type ConsumeContext = {
|
|
|
101
161
|
handlers: ConsumeHandlers;
|
|
102
162
|
};
|
|
103
163
|
//#endregion
|
|
164
|
+
//#region src/consume/retry.d.ts
|
|
165
|
+
/**
|
|
166
|
+
* The 1-based delivery attempt of a re-published message.
|
|
167
|
+
*/
|
|
168
|
+
export declare const ATTEMPT_HEADER = "x-attempt";
|
|
169
|
+
/**
|
|
170
|
+
* The attempt a message is on. A missing or invalid header (a first delivery, an
|
|
171
|
+
* older publisher counting elsewhere) is attempt 1: at worst a message is retried
|
|
172
|
+
* more often, never dropped early.
|
|
173
|
+
*/
|
|
174
|
+
export declare function resolveAttempt(properties: {
|
|
175
|
+
headers?: Record<string, unknown>;
|
|
176
|
+
}): number;
|
|
177
|
+
//#endregion
|
|
104
178
|
//#region src/errors/base.d.ts
|
|
105
179
|
/**
|
|
106
180
|
* Root of every error thrown by amqp-extension.
|
|
@@ -161,6 +235,7 @@ export declare class ClientError extends AmqpExtensionError {
|
|
|
161
235
|
static closed(): ClientError;
|
|
162
236
|
static channelClosed(cause?: unknown): ClientError;
|
|
163
237
|
static handlerMissing(type?: string): ClientError;
|
|
238
|
+
static attemptsExhausted(type?: string, cause?: unknown): ClientError;
|
|
164
239
|
static timeout(cause?: unknown): ClientError;
|
|
165
240
|
}
|
|
166
241
|
//#endregion
|
|
@@ -196,6 +271,7 @@ export declare enum ErrorCode {
|
|
|
196
271
|
CHANNEL_CLOSED = "CHANNEL_CLOSED",
|
|
197
272
|
PUBLISH_TIMEOUT = "PUBLISH_TIMEOUT",
|
|
198
273
|
HANDLER_MISSING = "HANDLER_MISSING",
|
|
274
|
+
ATTEMPTS_EXHAUSTED = "ATTEMPTS_EXHAUSTED",
|
|
199
275
|
BROKER_REJECTED = "BROKER_REJECTED",
|
|
200
276
|
SERIALIZATION_FAILED = "SERIALIZATION_FAILED"
|
|
201
277
|
}
|
|
@@ -224,23 +300,6 @@ export type Exchange = {
|
|
|
224
300
|
//#region src/exchange/utils.d.ts
|
|
225
301
|
export declare function isDefaultExchange(input?: `${ExchangeType}`): input is ExchangeType.DIRECT;
|
|
226
302
|
//#endregion
|
|
227
|
-
//#region src/publish/types.d.ts
|
|
228
|
-
export type PublishOptions = Options.Publish & QueueOptions & {
|
|
229
|
-
/**
|
|
230
|
-
* Reject with ClientError (PUBLISH_TIMEOUT) when the message is not
|
|
231
|
-
* handed to the broker within this many milliseconds, e.g. while the
|
|
232
|
-
* broker is unreachable and the connection manager is reconnecting.
|
|
233
|
-
*
|
|
234
|
-
* Default: undefined (wait for the reconnect)
|
|
235
|
-
*/
|
|
236
|
-
timeout?: number;
|
|
237
|
-
};
|
|
238
|
-
export type PublishContext = {
|
|
239
|
-
to: string;
|
|
240
|
-
data: any;
|
|
241
|
-
options?: PublishOptions;
|
|
242
|
-
};
|
|
243
|
-
//#endregion
|
|
244
303
|
//#region src/types.d.ts
|
|
245
304
|
export type Connection = ReturnType<typeof connect>;
|
|
246
305
|
export type ConnectionOptions = Options.Connect | string;
|
|
@@ -278,6 +337,16 @@ export declare class Client {
|
|
|
278
337
|
consume(ctx: ConsumeContext): Promise<Consumer>;
|
|
279
338
|
consume(from: string, handlers: ConsumeHandlers): Promise<Consumer>;
|
|
280
339
|
consume(from: string, options: ConsumeOptions, handlers: ConsumeHandlers): Promise<Consumer>;
|
|
340
|
+
/**
|
|
341
|
+
* Re-publish a message for a retry, through the default exchange by queue name:
|
|
342
|
+
* that reaches the queue whatever exchange delivered it, without re-declaring it.
|
|
343
|
+
* Its own channel, not the consume channel: that one may have been reset while
|
|
344
|
+
* the handler ran, and this one waits for the broker's confirm.
|
|
345
|
+
*
|
|
346
|
+
* ponytail: a server-named queue is gone after a reconnect, so a retry of a
|
|
347
|
+
* message from before it is unroutable and dropped by the broker.
|
|
348
|
+
*/
|
|
349
|
+
protected republish(queue: string, content: Buffer, options: RepublishOptions): Promise<void>;
|
|
281
350
|
publish(ctx: PublishContext): Promise<boolean>;
|
|
282
351
|
publish(to: string, data: any): Promise<boolean>;
|
|
283
352
|
publish(to: string, data: any, options: PublishOptions): Promise<boolean>;
|
package/dist/index.mjs
CHANGED
|
@@ -4,6 +4,52 @@ import { createMerger } from "smob";
|
|
|
4
4
|
//#region src/consume/constants.ts
|
|
5
5
|
const ConsumeHandlerAnyKey = "$any";
|
|
6
6
|
//#endregion
|
|
7
|
+
//#region src/consume/retry.ts
|
|
8
|
+
/**
|
|
9
|
+
* The 1-based delivery attempt of a re-published message.
|
|
10
|
+
*/
|
|
11
|
+
const ATTEMPT_HEADER = "x-attempt";
|
|
12
|
+
/**
|
|
13
|
+
* The attempt a message is on. A missing or invalid header (a first delivery, an
|
|
14
|
+
* older publisher counting elsewhere) is attempt 1: at worst a message is retried
|
|
15
|
+
* more often, never dropped early.
|
|
16
|
+
*/
|
|
17
|
+
function resolveAttempt(properties) {
|
|
18
|
+
const value = properties.headers?.[ATTEMPT_HEADER];
|
|
19
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 1 ? value : 1;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Delay before the given attempt: base, doubled per attempt, capped at 30s.
|
|
23
|
+
*/
|
|
24
|
+
function resolveRetryDelay(attempt, base) {
|
|
25
|
+
return Math.min(base * 2 ** (attempt - 2), 3e4);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Re-publish a message with the next attempt in its x-attempt header, after the backoff.
|
|
29
|
+
* Resolves false (without re-publishing) once the attempts are exhausted.
|
|
30
|
+
* Rejects when the re-publish fails.
|
|
31
|
+
*
|
|
32
|
+
* ponytail: the backoff holds the prefetch slot, fine for seconds;
|
|
33
|
+
* move to TTL + dead-letter-exchange delay queues for longer delays.
|
|
34
|
+
*/
|
|
35
|
+
async function retryMessage(message, publish, options) {
|
|
36
|
+
const attempt = resolveAttempt(message.properties) + 1;
|
|
37
|
+
if (attempt > (options.maxAttempts ?? 5)) return false;
|
|
38
|
+
await new Promise((resolve) => {
|
|
39
|
+
setTimeout(resolve, resolveRetryDelay(attempt, options.delay ?? 1e3));
|
|
40
|
+
});
|
|
41
|
+
const properties = {
|
|
42
|
+
...message.properties,
|
|
43
|
+
headers: {
|
|
44
|
+
...message.properties.headers,
|
|
45
|
+
[ATTEMPT_HEADER]: attempt
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
delete properties.userId;
|
|
49
|
+
await publish(message.content, properties);
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
7
53
|
//#region src/errors/constants.ts
|
|
8
54
|
let ErrorCode = /* @__PURE__ */ function(ErrorCode) {
|
|
9
55
|
ErrorCode["QUEUE_NAME_EMPTY"] = "QUEUE_NAME_EMPTY";
|
|
@@ -13,6 +59,7 @@ let ErrorCode = /* @__PURE__ */ function(ErrorCode) {
|
|
|
13
59
|
ErrorCode["CHANNEL_CLOSED"] = "CHANNEL_CLOSED";
|
|
14
60
|
ErrorCode["PUBLISH_TIMEOUT"] = "PUBLISH_TIMEOUT";
|
|
15
61
|
ErrorCode["HANDLER_MISSING"] = "HANDLER_MISSING";
|
|
62
|
+
ErrorCode["ATTEMPTS_EXHAUSTED"] = "ATTEMPTS_EXHAUSTED";
|
|
16
63
|
ErrorCode["BROKER_REJECTED"] = "BROKER_REJECTED";
|
|
17
64
|
ErrorCode["SERIALIZATION_FAILED"] = "SERIALIZATION_FAILED";
|
|
18
65
|
return ErrorCode;
|
|
@@ -125,6 +172,13 @@ var ClientError = class ClientError extends AmqpExtensionError {
|
|
|
125
172
|
message: typeof type === "string" ? `No handler for the message type "${type}".` : "No handler for a message without type."
|
|
126
173
|
});
|
|
127
174
|
}
|
|
175
|
+
static attemptsExhausted(type, cause) {
|
|
176
|
+
return new ClientError({
|
|
177
|
+
code: "ATTEMPTS_EXHAUSTED",
|
|
178
|
+
message: typeof type === "string" ? `The retry attempts for the message type "${type}" are exhausted.` : "The retry attempts for a message without type are exhausted.",
|
|
179
|
+
cause
|
|
180
|
+
});
|
|
181
|
+
}
|
|
128
182
|
static timeout(cause) {
|
|
129
183
|
return new ClientError({
|
|
130
184
|
code: "PUBLISH_TIMEOUT",
|
|
@@ -196,31 +250,95 @@ function isDefaultExchange(input) {
|
|
|
196
250
|
}
|
|
197
251
|
//#endregion
|
|
198
252
|
//#region src/consume/utils.ts
|
|
253
|
+
function settle(fn) {
|
|
254
|
+
try {
|
|
255
|
+
fn();
|
|
256
|
+
} catch {}
|
|
257
|
+
}
|
|
258
|
+
async function report(options, error, message) {
|
|
259
|
+
if (!options.onError) return;
|
|
260
|
+
try {
|
|
261
|
+
await options.onError(error, message);
|
|
262
|
+
} catch {}
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Track a run by message id until it settles, so redelivered copies can find it.
|
|
266
|
+
*/
|
|
267
|
+
async function track(inFlight, id, run) {
|
|
268
|
+
inFlight.set(id, run);
|
|
269
|
+
try {
|
|
270
|
+
await run;
|
|
271
|
+
} finally {
|
|
272
|
+
if (inFlight.get(id) === run) inFlight.delete(id);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
199
275
|
/**
|
|
200
276
|
* Dispatch a delivery to the handler for its type (or $any) and settle it:
|
|
201
277
|
* ack on success, nack (requeue = requeueOnFailure) on failure or without handler, nothing with noAck.
|
|
278
|
+
* With retry, a handler failure is re-published with the next attempt and the original acked instead,
|
|
279
|
+
* and redeliveries of messages with a messageId are guarded (see ConsumeOptions.retry).
|
|
202
280
|
* A failure is then reported to onError.
|
|
203
281
|
*/
|
|
204
|
-
async function handleMessage(message, channel, handlers, options) {
|
|
282
|
+
async function handleMessage(message, channel, handlers, options, context) {
|
|
205
283
|
if (!message) return;
|
|
284
|
+
const id = message.properties.messageId;
|
|
285
|
+
if (!options.retry || options.noAck || !context || typeof id !== "string") {
|
|
286
|
+
await dispatch(message, channel, handlers, options, context);
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
if (message.fields.redelivered) {
|
|
290
|
+
const running = context.inFlight.get(id);
|
|
291
|
+
if (running) {
|
|
292
|
+
if (options.ordered) await running;
|
|
293
|
+
settle(() => channel.ack(message));
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
await track(context.inFlight, id, fail(message, channel, options, context));
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
await track(context.inFlight, id, dispatch(message, channel, handlers, options, context));
|
|
300
|
+
}
|
|
301
|
+
async function dispatch(message, channel, handlers, options, context) {
|
|
206
302
|
const { type } = message.properties;
|
|
207
303
|
const handler = (typeof type === "string" && Object.hasOwn(handlers, type) ? handlers[type] : void 0) || handlers["$any"];
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
304
|
+
if (!handler) {
|
|
305
|
+
if (!options.noAck) settle(() => channel.nack(message, false, options.requeueOnFailure ?? false));
|
|
306
|
+
await report(options, ClientError.handlerMissing(type), message);
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
try {
|
|
211
310
|
await handler(message, channel);
|
|
212
|
-
} catch (
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
311
|
+
} catch (error) {
|
|
312
|
+
await fail(message, channel, options, context, { error });
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
if (!options.noAck) settle(() => channel.ack(message));
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Settle a failed message: retry it (with retry), else nack it.
|
|
319
|
+
* failure is undefined for a redelivery of a message whose consumer died: there is no error to report.
|
|
320
|
+
*/
|
|
321
|
+
async function fail(message, channel, options, context, failure) {
|
|
322
|
+
if (options.noAck) {
|
|
323
|
+
if (failure) await report(options, failure.error, message);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
if (!options.retry || !context) {
|
|
327
|
+
settle(() => channel.nack(message, false, options.requeueOnFailure ?? false));
|
|
328
|
+
if (failure) await report(options, failure.error, message);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
let retried;
|
|
332
|
+
try {
|
|
333
|
+
retried = await retryMessage(message, context.republish, options.retry);
|
|
334
|
+
} catch {
|
|
335
|
+
settle(() => channel.nack(message, false, true));
|
|
336
|
+
if (failure) await report(options, failure.error, message);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
settle(() => channel.ack(message));
|
|
340
|
+
if (!retried) await report(options, ClientError.attemptsExhausted(message.properties.type, failure?.error), message);
|
|
341
|
+
else if (failure) await report(options, failure.error, message);
|
|
224
342
|
}
|
|
225
343
|
//#endregion
|
|
226
344
|
//#region src/errors/utils.ts
|
|
@@ -418,13 +536,18 @@ var Client = class Client {
|
|
|
418
536
|
let current;
|
|
419
537
|
let running;
|
|
420
538
|
const inFlight = /* @__PURE__ */ new Set();
|
|
539
|
+
const tracked = /* @__PURE__ */ new Map();
|
|
421
540
|
const channel = this.connection.createChannel({ setup: guard((ch) => {
|
|
422
541
|
running = (async () => {
|
|
423
542
|
if (cancelled) return;
|
|
424
543
|
const queue = await assertTopology(ch, topology);
|
|
425
544
|
if (typeof options.prefetchCount === "number") await ch.prefetch(options.prefetchCount);
|
|
545
|
+
const context = {
|
|
546
|
+
inFlight: tracked,
|
|
547
|
+
republish: (content, props) => this.republish(queue, content, props)
|
|
548
|
+
};
|
|
426
549
|
const { consumerTag } = await ch.consume(queue, (message) => {
|
|
427
|
-
const handled = handleMessage(message, ch, ctx.handlers, options);
|
|
550
|
+
const handled = handleMessage(message, ch, ctx.handlers, options, context);
|
|
428
551
|
inFlight.add(handled);
|
|
429
552
|
handled.then(() => inFlight.delete(handled));
|
|
430
553
|
}, options);
|
|
@@ -460,6 +583,29 @@ var Client = class Client {
|
|
|
460
583
|
throw toError(e);
|
|
461
584
|
}
|
|
462
585
|
}
|
|
586
|
+
/**
|
|
587
|
+
* Re-publish a message for a retry, through the default exchange by queue name:
|
|
588
|
+
* that reaches the queue whatever exchange delivered it, without re-declaring it.
|
|
589
|
+
* Its own channel, not the consume channel: that one may have been reset while
|
|
590
|
+
* the handler ran, and this one waits for the broker's confirm.
|
|
591
|
+
*
|
|
592
|
+
* ponytail: a server-named queue is gone after a reconnect, so a retry of a
|
|
593
|
+
* message from before it is unroutable and dropped by the broker.
|
|
594
|
+
*/
|
|
595
|
+
async republish(queue, content, options) {
|
|
596
|
+
this.assertOpen();
|
|
597
|
+
const channel = this.connection.createChannel();
|
|
598
|
+
const published = channel.publish("", queue, content, {
|
|
599
|
+
...options,
|
|
600
|
+
timeout: 3e4
|
|
601
|
+
});
|
|
602
|
+
published.catch(noop);
|
|
603
|
+
try {
|
|
604
|
+
await Promise.race([published, failure(channel)]);
|
|
605
|
+
} finally {
|
|
606
|
+
channel.close().catch(noop);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
463
609
|
async publish(_toOrCtx, _data, _options) {
|
|
464
610
|
const ctx = typeof _toOrCtx === "string" ? {
|
|
465
611
|
to: _toOrCtx,
|
|
@@ -497,6 +643,6 @@ var Client = class Client {
|
|
|
497
643
|
}
|
|
498
644
|
};
|
|
499
645
|
//#endregion
|
|
500
|
-
export { AMQP_EXTENSION_ERROR_MARKER, AmqpExtensionError, BROKER_ERROR_MARKER, BrokerError, CLIENT_ERROR_MARKER, Client, ClientError, ConsumeHandlerAnyKey, ErrorCode, ExchangeType, SERIALIZATION_ERROR_MARKER, SerializationError, TOPOLOGY_ERROR_MARKER, TopologyError, isAmqpExtensionError, isBrokerError, isClientError, isDefaultExchange, isSerializationError, isTopologyError };
|
|
646
|
+
export { AMQP_EXTENSION_ERROR_MARKER, ATTEMPT_HEADER, AmqpExtensionError, BROKER_ERROR_MARKER, BrokerError, CLIENT_ERROR_MARKER, Client, ClientError, ConsumeHandlerAnyKey, ErrorCode, ExchangeType, SERIALIZATION_ERROR_MARKER, SerializationError, TOPOLOGY_ERROR_MARKER, TopologyError, isAmqpExtensionError, isBrokerError, isClientError, isDefaultExchange, isSerializationError, isTopologyError, resolveAttempt };
|
|
501
647
|
|
|
502
648
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/consume/constants.ts","../src/errors/constants.ts","../src/errors/base.ts","../src/errors/broker.ts","../src/errors/check.ts","../src/errors/client.ts","../src/errors/serialization.ts","../src/errors/topology.ts","../src/exchange/constants.ts","../src/exchange/utils.ts","../src/consume/utils.ts","../src/errors/utils.ts","../src/queue/utils.ts","../src/utils.ts","../src/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport const ConsumeHandlerAnyKey = '$any';\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum ErrorCode {\n QUEUE_NAME_EMPTY = 'QUEUE_NAME_EMPTY',\n EXCHANGE_NAME_MISSING = 'EXCHANGE_NAME_MISSING',\n DESTINATION_MISSING = 'DESTINATION_MISSING',\n CLIENT_CLOSED = 'CLIENT_CLOSED',\n CHANNEL_CLOSED = 'CHANNEL_CLOSED',\n PUBLISH_TIMEOUT = 'PUBLISH_TIMEOUT',\n HANDLER_MISSING = 'HANDLER_MISSING',\n BROKER_REJECTED = 'BROKER_REJECTED',\n SERIALIZATION_FAILED = 'SERIALIZATION_FAILED',\n}\n\n// Symbol.for markers, shared by every copy of the library (see check.ts)\nexport const AMQP_EXTENSION_ERROR_MARKER = Symbol.for('amqp-extension/AmqpExtensionError');\nexport const TOPOLOGY_ERROR_MARKER = Symbol.for('amqp-extension/TopologyError');\nexport const CLIENT_ERROR_MARKER = Symbol.for('amqp-extension/ClientError');\nexport const BROKER_ERROR_MARKER = Symbol.for('amqp-extension/BrokerError');\nexport const SERIALIZATION_ERROR_MARKER = Symbol.for('amqp-extension/SerializationError');\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { BaseError, hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AMQP_EXTENSION_ERROR_MARKER } from './constants';\n\n/**\n * Root of every error thrown by amqp-extension.\n *\n * instanceof is duck-typed through @ebec/core's marker chain, so it also matches errors\n * from a duplicate copy of the library. Every subclass overrides Symbol.hasInstance with\n * its own marker, otherwise it would inherit this one and match every library error.\n */\nexport class AmqpExtensionError extends BaseError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, AMQP_EXTENSION_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, AMQP_EXTENSION_ERROR_MARKER);\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { BROKER_ERROR_MARKER, ErrorCode } from './constants';\nimport type { AmqpReplyError, BrokerReply } from './types';\n\n/**\n * The broker rejected an operation, e.g. 406 PRECONDITION_FAILED or 403 ACCESS_REFUSED.\n */\nexport class BrokerError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, BROKER_ERROR_MARKER);\n }\n\n readonly replyCode: number;\n\n readonly classId?: number;\n\n readonly methodId?: number;\n\n constructor(input: ErrorInput, reply: BrokerReply) {\n super(input);\n\n this.replyCode = reply.replyCode;\n this.classId = reply.classId;\n this.methodId = reply.methodId;\n\n markInstanceof(this, BROKER_ERROR_MARKER);\n }\n\n override toJSON() {\n return {\n ...super.toJSON(),\n replyCode: this.replyCode,\n classId: this.classId,\n methodId: this.methodId,\n };\n }\n\n static fromAmqp(err: AmqpReplyError) {\n return new BrokerError(\n {\n code: ErrorCode.BROKER_REJECTED,\n message: err.message,\n cause: err,\n },\n {\n replyCode: err.code,\n classId: err.classId,\n methodId: err.methodId,\n },\n );\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { matchesInstanceof } from '@ebec/core';\nimport type { AmqpExtensionError } from './base';\nimport type { BrokerError } from './broker';\nimport type { ClientError } from './client';\nimport {\n AMQP_EXTENSION_ERROR_MARKER,\n BROKER_ERROR_MARKER,\n CLIENT_ERROR_MARKER,\n SERIALIZATION_ERROR_MARKER,\n TOPOLOGY_ERROR_MARKER,\n} from './constants';\nimport type { SerializationError } from './serialization';\nimport type { TopologyError } from './topology';\n\n// Unlike instanceof, the guards also match an error that crossed a boundary as JSON\n// (toJSON() keeps the marker chain as strings). ponytail: such a plain object has the\n// fields but not the methods of the class it is narrowed to.\n\nexport function isAmqpExtensionError(input: unknown) : input is AmqpExtensionError {\n return matchesInstanceof(input, AMQP_EXTENSION_ERROR_MARKER);\n}\n\nexport function isTopologyError(input: unknown) : input is TopologyError {\n return matchesInstanceof(input, TOPOLOGY_ERROR_MARKER);\n}\n\nexport function isClientError(input: unknown) : input is ClientError {\n return matchesInstanceof(input, CLIENT_ERROR_MARKER);\n}\n\nexport function isBrokerError(input: unknown) : input is BrokerError {\n return matchesInstanceof(input, BROKER_ERROR_MARKER);\n}\n\nexport function isSerializationError(input: unknown) : input is SerializationError {\n return matchesInstanceof(input, SERIALIZATION_ERROR_MARKER);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { CLIENT_ERROR_MARKER, ErrorCode } from './constants';\n\nexport class ClientError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, CLIENT_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, CLIENT_ERROR_MARKER);\n }\n static closed() {\n return new ClientError({ code: ErrorCode.CLIENT_CLOSED, message: 'The client is closed.' });\n }\n\n static channelClosed(cause?: unknown) {\n return new ClientError({\n code: ErrorCode.CHANNEL_CLOSED,\n message: 'Channel closed',\n cause,\n });\n }\n\n static handlerMissing(type?: string) {\n return new ClientError({\n code: ErrorCode.HANDLER_MISSING,\n message: typeof type === 'string' ? `No handler for the message type \"${type}\".` : 'No handler for a message without type.',\n });\n }\n\n static timeout(cause?: unknown) {\n return new ClientError({\n code: ErrorCode.PUBLISH_TIMEOUT,\n message: 'The publish operation timed out.',\n cause,\n });\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { ErrorCode, SERIALIZATION_ERROR_MARKER } from './constants';\n\nexport class SerializationError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, SERIALIZATION_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, SERIALIZATION_ERROR_MARKER);\n }\n static payload(cause?: unknown) {\n return new SerializationError({\n code: ErrorCode.SERIALIZATION_FAILED,\n message: 'The message payload could not be serialized.',\n cause,\n });\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { ErrorCode, TOPOLOGY_ERROR_MARKER } from './constants';\n\nexport class TopologyError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, TOPOLOGY_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, TOPOLOGY_ERROR_MARKER);\n }\n static queueNameEmpty() {\n return new TopologyError({\n code: ErrorCode.QUEUE_NAME_EMPTY,\n message: 'The queue name can not be empty if the default exchange is selected.',\n });\n }\n\n static exchangeNameMissing() {\n return new TopologyError({\n code: ErrorCode.EXCHANGE_NAME_MISSING,\n message: 'A non default exchange requires a name.',\n });\n }\n\n static destinationMissing() {\n return new TopologyError({\n code: ErrorCode.DESTINATION_MISSING,\n message: 'The publish operation requires a destination.',\n });\n }\n}\n","export enum ExchangeType {\n FANOUT = 'fanout',\n DIRECT = 'direct',\n TOPIC = 'topic',\n HEADERS = 'headers',\n}\n","import { ExchangeType } from './constants';\n\nexport function isDefaultExchange(\n input?: `${ExchangeType}`,\n) : input is ExchangeType.DIRECT {\n return typeof input === 'undefined' || input === ExchangeType.DIRECT;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport { ClientError } from '../errors';\nimport { ConsumeHandlerAnyKey } from './constants';\nimport type { ConsumeHandlers, ConsumeOptions } from './types';\n\n/**\n * Dispatch a delivery to the handler for its type (or $any) and settle it:\n * ack on success, nack (requeue = requeueOnFailure) on failure or without handler, nothing with noAck.\n * A failure is then reported to onError.\n */\nexport async function handleMessage(\n message: ConsumeMessage | null,\n channel: Pick<Channel, 'ack' | 'nack'>,\n handlers: ConsumeHandlers,\n options: ConsumeOptions,\n) : Promise<void> {\n // null = the broker cancelled the consumer\n if (!message) {\n return;\n }\n\n // the type is set by the publisher (untrusted): never resolve inherited properties like 'toString'\n const { type } = message.properties;\n const handler = (typeof type === 'string' && Object.hasOwn(handlers, type) ? handlers[type] : undefined) ||\n handlers[ConsumeHandlerAnyKey];\n\n let ok = !!handler;\n let error : unknown;\n if (handler) {\n try {\n await handler(message, channel as Channel);\n } catch (e) {\n ok = false;\n error = e;\n }\n } else {\n error = ClientError.handlerMissing(type);\n }\n\n if (!options.noAck) {\n try {\n if (ok) {\n channel.ack(message);\n } else {\n channel.nack(message, false, options.requeueOnFailure ?? false);\n }\n } catch {\n // the channel closed while the handler ran (e.g. reconnect): the broker redelivers the message anyway\n }\n }\n\n if (!ok && options.onError) {\n try {\n await options.onError(error, message);\n } catch {\n // never reject: amqplib discards the consumer callback's promise\n }\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { AmqpExtensionError } from './base';\nimport { BrokerError } from './broker';\nimport { ClientError } from './client';\nimport type { AmqpReplyError } from './types';\n\n/**\n * Map anything thrown below the Client (amqplib, amqp-connection-manager) onto the error tree.\n */\nexport function toError(e: unknown) : AmqpExtensionError {\n if (e instanceof AmqpExtensionError) {\n return e;\n }\n\n if (!(e instanceof Error)) {\n return new AmqpExtensionError({ message: String(e), cause: e });\n }\n\n if (typeof (e as Partial<AmqpReplyError>).code === 'number') {\n return BrokerError.fromAmqp(e as AmqpReplyError);\n }\n\n // ponytail: amqp-connection-manager's errors carry no class or code, only these messages;\n // a reworded message falls through to the base class\n if (e.message === 'timeout') {\n return ClientError.timeout(e);\n }\n\n if (e.message === 'Channel closed') {\n return ClientError.channelClosed(e);\n }\n\n return new AmqpExtensionError({ message: e.message, cause: e });\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { Channel, Options } from 'amqplib';\nimport type { Exchange } from '../exchange';\nimport { TopologyError } from '../errors';\nimport { isDefaultExchange } from '../exchange';\nimport type { QueueOptions, Topology } from './types';\n\n\nconst QueueArguments = {\n queueType: 'x-queue-type',\n deliveryLimit: 'x-delivery-limit',\n deadLetterExchange: 'x-dead-letter-exchange',\n deadLetterRoutingKey: 'x-dead-letter-routing-key',\n messageTtl: 'x-message-ttl',\n maxLength: 'x-max-length',\n singleActiveConsumer: 'x-single-active-consumer',\n} as const satisfies Record<keyof QueueOptions, string>;\n\nfunction planQueueOptions(options: QueueOptions) : Options.AssertQueue {\n const queueOptions : Options.AssertQueue = { durable: true };\n\n const keys = Object.keys(QueueArguments) as (keyof QueueOptions)[];\n for (const key of keys) {\n const value = options[key];\n // false is left out like undefined, so a queue declared without the option stays equivalent\n if (typeof value !== 'undefined' && value !== false) {\n queueOptions.arguments = { ...queueOptions.arguments, [QueueArguments[key]]: value };\n }\n }\n\n return queueOptions;\n}\n\n/**\n * Plan the topology for publishing to or consuming from (consume = true) a key.\n * Throws on invalid input, before anything touches the broker.\n */\nexport function planTopology(\n exchange: Exchange,\n key: string,\n options: QueueOptions & { queue?: string },\n consume?: boolean,\n) : Topology {\n if (isDefaultExchange(exchange.type)) {\n if (!key) {\n throw TopologyError.queueNameEmpty();\n }\n\n return { queue: { name: key, options: planQueueOptions(options) } };\n }\n\n if (!exchange.name) {\n throw TopologyError.exchangeNameMissing();\n }\n\n const topology : Topology = {\n exchange: {\n name: exchange.name,\n type: exchange.type,\n options: exchange.options,\n },\n };\n\n if (!consume) {\n if (!key) {\n throw TopologyError.destinationMissing();\n }\n\n return topology;\n }\n\n if (options.queue === '') {\n throw TopologyError.queueNameEmpty();\n }\n\n topology.queue = options.queue ?\n { name: options.queue, options: planQueueOptions(options) } :\n {\n name: '',\n options: {\n durable: false,\n autoDelete: true,\n exclusive: true,\n },\n };\n topology.bind = key;\n\n return topology;\n}\n\n/**\n * Declare a planned topology. Returns the (possibly server generated) queue name.\n * Must run inside a channel setup function, so it is replayed on reconnect.\n */\nexport async function assertTopology(channel: Channel, topology: Topology) : Promise<string | undefined> {\n if (topology.exchange) {\n await channel.assertExchange(topology.exchange.name, topology.exchange.type, topology.exchange.options);\n }\n\n if (!topology.queue) {\n return undefined;\n }\n\n const { queue } = await channel.assertQueue(topology.queue.name, topology.queue.options);\n if (topology.exchange && typeof topology.bind === 'string') {\n await channel.bindQueue(queue, topology.exchange.name, topology.bind);\n }\n\n return queue;\n}\n","import { createMerger } from 'smob';\n\nconst mergeOptions = createMerger({\n priority: 'left',\n inPlace: false,\n clone: true,\n array: true,\n arrayDistinct: true,\n});\n\nexport {\n mergeOptions,\n};\n","/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ChannelWrapper } from 'amqp-connection-manager';\nimport { connect } from 'amqp-connection-manager';\nimport type { Channel } from 'amqplib';\nimport type {\n ConsumeContext,\n ConsumeHandlers,\n ConsumeOptions,\n Consumer,\n} from './consume';\nimport { handleMessage } from './consume/utils';\nimport { ClientError, SerializationError } from './errors';\nimport { toError } from './errors/utils';\nimport type { Exchange } from './exchange';\nimport { ExchangeType } from './exchange';\nimport type { PublishContext, PublishOptions } from './publish';\nimport { assertTopology, planTopology } from './queue/utils';\nimport type { ClientContext, Connection } from './types';\nimport { mergeOptions } from './utils';\n\n// connections closed through Client.close(), shared by of() siblings\nconst closed = new WeakSet<Connection>();\n\nconst noop = () => undefined;\n\n/**\n * Wrap a setup function, so a broker rejection during it (e.g. 403/406) closes only this channel:\n * without an 'error' listener on the raw channel, amqplib rethrows it and tears down the whole connection.\n * Only during setup: a channel error afterwards must still recycle the connection, because\n * amqp-connection-manager never recovers a channel-only close, so consumers would silently die.\n */\nfunction guard(setup: (channel: Channel) => Promise<unknown>) {\n return async (channel: Channel) => {\n channel.on('error', noop);\n\n try {\n await setup(channel);\n } finally {\n channel.off('error', noop);\n }\n };\n}\n\n/**\n * Reject when the broker rejects a setup function (an error with an AMQP reply code)\n * or the channel is closed (client.close()).\n * Errors without a reply code (connection dropped mid-setup) are transient:\n * the setup runs again on reconnect, so keep waiting.\n */\nfunction failure(channel: ChannelWrapper) : Promise<never> {\n const promise = new Promise<never>((_resolve, reject) => {\n // ponytail: the listener stays, so setup errors after a reconnect are swallowed instead of crashing the process\n channel.on('error', (err: Error & { code?: unknown }) => {\n if (typeof err.code === 'number') {\n reject(err);\n }\n });\n channel.once('close', () => reject(ClientError.channelClosed()));\n });\n\n // it may reject long after the call settled (e.g. close()), which is not an unhandled rejection\n promise.catch(noop);\n\n return promise;\n}\n\nexport class Client {\n public readonly connection: Connection;\n\n protected publishOptions : PublishOptions;\n\n protected consumeOptions : ConsumeOptions;\n\n protected exchange: Exchange;\n\n constructor(ctx: ClientContext) {\n this.connection = ctx.connection ?? connect(ctx.connectionOptions, ctx.connectionManagerOptions);\n this.publishOptions = ctx.publishOptions || {};\n this.consumeOptions = ctx.consumeOptions || {};\n this.exchange = ctx.exchange || {\n type: ExchangeType.DIRECT,\n name: '',\n };\n }\n\n of(exchange: Exchange) : Client {\n return new Client({\n connection: this.connection,\n publishOptions: this.publishOptions,\n consumeOptions: this.consumeOptions,\n exchange,\n });\n }\n\n /**\n * Close the (shared) connection and all its channels.\n */\n async close() : Promise<void> {\n closed.add(this.connection);\n await this.connection.close();\n }\n\n /**\n * `await using client = new Client(...)` closes the client when the scope ends.\n * Like close(), it closes the shared connection, so use it on the root client, not on of() siblings.\n */\n async [Symbol.asyncDispose]() : Promise<void> {\n await this.close();\n }\n\n protected assertOpen() : void {\n if (closed.has(this.connection)) {\n throw ClientError.closed();\n }\n }\n\n async consume(ctx: ConsumeContext) : Promise<Consumer>;\n\n async consume(from: string, handlers: ConsumeHandlers): Promise<Consumer>;\n\n async consume(from: string, options: ConsumeOptions, handlers: ConsumeHandlers): Promise<Consumer>;\n\n async consume(\n _ctxOrFrom: ConsumeContext | string,\n _optionsOrHandlers?: ConsumeOptions | ConsumeHandlers,\n _handlers?: ConsumeHandlers,\n ) : Promise<Consumer> {\n const ctx : ConsumeContext = typeof _ctxOrFrom === 'string' ?\n {\n from: _ctxOrFrom,\n options: _handlers ? _optionsOrHandlers as ConsumeOptions : undefined,\n handlers: _handlers || _optionsOrHandlers as ConsumeHandlers,\n } :\n _ctxOrFrom;\n\n try {\n this.assertOpen();\n\n let options = this.consumeOptions;\n if (ctx.options) {\n // smob clones through structuredClone, which throws on functions\n const { onError, ...rest } = ctx.options;\n const { onError: fallback, ...defaults } = this.consumeOptions;\n options = { ...mergeOptions(rest, defaults), onError: onError ?? fallback };\n }\n\n const topology = planTopology(this.exchange, ctx.from, options, true);\n\n let cancelled = false;\n // the raw channel and consumer tag of the latest setup run\n let current : { ch: Channel, consumerTag: string } | undefined;\n // the latest setup run, awaited by cancel(): one in progress during a reconnect still registers a consumer\n let running : Promise<void> | undefined;\n const inFlight = new Set<Promise<void>>();\n\n const channel = this.connection.createChannel({\n setup: guard((ch: Channel) => {\n running = (async () => {\n if (cancelled) {\n return;\n }\n\n const queue = await assertTopology(ch, topology) as string;\n\n if (typeof options.prefetchCount === 'number') {\n await ch.prefetch(options.prefetchCount);\n }\n\n const { consumerTag } = await ch.consume(queue, (message) => {\n const handled = handleMessage(message, ch, ctx.handlers, options);\n inFlight.add(handled);\n // handleMessage never rejects\n handled.then(() => inFlight.delete(handled));\n }, options);\n current = { ch, consumerTag };\n })();\n\n return running;\n }),\n });\n\n try {\n await Promise.race([channel.waitForConnect(), failure(channel)]);\n } catch (e) {\n // not awaited: amqplib never settles the close when the connection drops before close-ok\n channel.close().catch(noop);\n throw e;\n }\n\n let cancelling : Promise<void> | undefined;\n const cancel = () => {\n cancelling ??= (async () => {\n // no setup run after this one: a reconnect does not re-register the consumer\n cancelled = true;\n await running?.catch(noop);\n\n // basic.cancel: no new deliveries, the channel stays open to settle the in-flight ones\n // (fails on a closed channel, e.g. after close() or during a reconnect)\n await current?.ch.cancel(current.consumerTag).catch(noop);\n\n // ponytail: a handler that never settles hangs cancel()\n // (a loop: deliveries that arrived before the cancel took effect add to the set)\n while (inFlight.size > 0) {\n await Promise.all(inFlight);\n }\n\n // ponytail: hangs if the connection drops between ChannelClose and CloseOk (amqplib)\n await channel.close().catch(noop);\n })();\n\n return cancelling;\n };\n\n return { cancel, [Symbol.asyncDispose]: cancel };\n } catch (e) {\n throw toError(e);\n }\n }\n\n async publish(ctx: PublishContext) : Promise<boolean>;\n\n async publish(to: string, data: any) : Promise<boolean>;\n\n async publish(to: string, data: any, options: PublishOptions): Promise<boolean>;\n\n async publish(\n _toOrCtx: PublishContext | string,\n _data?: any,\n _options?: PublishOptions,\n ) : Promise<boolean> {\n const ctx : PublishContext = typeof _toOrCtx === 'string' ?\n {\n to: _toOrCtx,\n data: _data,\n options: _options,\n } :\n _toOrCtx;\n\n try {\n this.assertOpen();\n\n const options = ctx.options ? mergeOptions(ctx.options, this.publishOptions) : this.publishOptions;\n const topology = planTopology(this.exchange, ctx.to, options);\n\n let content : Buffer;\n if (Buffer.isBuffer(ctx.data)) {\n content = ctx.data;\n } else if (typeof ctx.data === 'string') {\n content = Buffer.from(ctx.data, 'utf-8');\n } else {\n let json : string | undefined;\n try {\n json = JSON.stringify(ctx.data);\n } catch (e) {\n throw SerializationError.payload(e);\n }\n\n // undefined, functions and symbols serialize to undefined\n if (typeof json === 'undefined') {\n throw SerializationError.payload();\n }\n\n content = Buffer.from(json, 'utf-8');\n }\n\n // ponytail: one channel per publish (self-healing, no shared state), reuse channels when throughput matters\n const channel = this.connection.createChannel({ setup: guard((ch: Channel) => assertTopology(ch, topology)) });\n\n // queued right away: sent once the setup ran, bounded by options.timeout, rejected by close()\n const published = channel.publish(this.exchange.name || '', ctx.to, content, options);\n published.catch(noop);\n\n try {\n return await Promise.race([published, failure(channel)]);\n } finally {\n // not awaited, see consume()\n channel.close().catch(noop);\n }\n } catch (e) {\n throw toError(e);\n }\n }\n}\n"],"mappings":";;;;AAOA,MAAa,uBAAuB;;;ACApC,IAAY,YAAL,yBAAA,WAAA;CACH,UAAA,sBAAA;CACA,UAAA,2BAAA;CACA,UAAA,yBAAA;CACA,UAAA,mBAAA;CACA,UAAA,oBAAA;CACA,UAAA,qBAAA;CACA,UAAA,qBAAA;CACA,UAAA,qBAAA;CACA,UAAA,0BAAA;;AACJ,EAAA,CAAA,CAAA;AAGA,MAAa,8BAA8B,OAAO,IAAI,mCAAmC;AACzF,MAAa,wBAAwB,OAAO,IAAI,8BAA8B;AAC9E,MAAa,sBAAsB,OAAO,IAAI,4BAA4B;AAC1E,MAAa,sBAAsB,OAAO,IAAI,4BAA4B;AAC1E,MAAa,6BAA6B,OAAO,IAAI,mCAAmC;;;;;;;;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C;GAGA,MAAM,UAAU,KAAK,WAAW,cAAc,EAAE,OAAO,OAAO,OAAgB,eAAe,IAAI,QAAQ,CAAC,EAAE,CAAC;GAG7G,MAAM,YAAY,QAAQ,QAAQ,KAAK,SAAS,QAAQ,IAAI,IAAI,IAAI,SAAS,OAAO;GACpF,UAAU,MAAM,IAAI;GAEpB,IAAI;IACA,OAAO,MAAM,QAAQ,KAAK,CAAC,WAAW,QAAQ,OAAO,CAAC,CAAC;GAC3D,UAAU;IAEN,QAAQ,MAAM,CAAC,CAAC,MAAM,IAAI;GAC9B;EACJ,SAAS,GAAG;GACR,MAAM,QAAQ,CAAC;EACnB;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/consume/constants.ts","../src/consume/retry.ts","../src/errors/constants.ts","../src/errors/base.ts","../src/errors/broker.ts","../src/errors/check.ts","../src/errors/client.ts","../src/errors/serialization.ts","../src/errors/topology.ts","../src/exchange/constants.ts","../src/exchange/utils.ts","../src/consume/utils.ts","../src/errors/utils.ts","../src/queue/utils.ts","../src/utils.ts","../src/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport const ConsumeHandlerAnyKey = '$any';\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ConsumeMessage } from 'amqplib';\nimport type { RepublishOptions } from '../publish';\nimport type { ConsumeRetryOptions } from './types';\n\n/**\n * The 1-based delivery attempt of a re-published message.\n */\nexport const ATTEMPT_HEADER = 'x-attempt';\n\n/**\n * The attempt a message is on. A missing or invalid header (a first delivery, an\n * older publisher counting elsewhere) is attempt 1: at worst a message is retried\n * more often, never dropped early.\n */\nexport function resolveAttempt(properties: { headers?: Record<string, unknown> }) : number {\n const value = properties.headers?.[ATTEMPT_HEADER];\n\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 ? value : 1;\n}\n\n/**\n * Delay before the given attempt: base, doubled per attempt, capped at 30s.\n */\nexport function resolveRetryDelay(attempt: number, base: number) : number {\n return Math.min(base * 2 ** (attempt - 2), 30_000);\n}\n\n/**\n * Re-publish a message with the next attempt in its x-attempt header, after the backoff.\n * Resolves false (without re-publishing) once the attempts are exhausted.\n * Rejects when the re-publish fails.\n *\n * ponytail: the backoff holds the prefetch slot, fine for seconds;\n * move to TTL + dead-letter-exchange delay queues for longer delays.\n */\nexport async function retryMessage(\n message: ConsumeMessage,\n publish: (content: Buffer, options: RepublishOptions) => Promise<void>,\n options: ConsumeRetryOptions,\n) : Promise<boolean> {\n const attempt = resolveAttempt(message.properties) + 1;\n if (attempt > (options.maxAttempts ?? 5)) {\n return false;\n }\n\n await new Promise((resolve) => {\n setTimeout(resolve, resolveRetryDelay(attempt, options.delay ?? 1000));\n });\n\n const properties : RepublishOptions = {\n ...message.properties,\n headers: { ...message.properties.headers, [ATTEMPT_HEADER]: attempt },\n };\n // the broker rejects a user-id that is not the re-publishing connection's user\n delete properties.userId;\n\n await publish(message.content, properties);\n\n return true;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum ErrorCode {\n QUEUE_NAME_EMPTY = 'QUEUE_NAME_EMPTY',\n EXCHANGE_NAME_MISSING = 'EXCHANGE_NAME_MISSING',\n DESTINATION_MISSING = 'DESTINATION_MISSING',\n CLIENT_CLOSED = 'CLIENT_CLOSED',\n CHANNEL_CLOSED = 'CHANNEL_CLOSED',\n PUBLISH_TIMEOUT = 'PUBLISH_TIMEOUT',\n HANDLER_MISSING = 'HANDLER_MISSING',\n ATTEMPTS_EXHAUSTED = 'ATTEMPTS_EXHAUSTED',\n BROKER_REJECTED = 'BROKER_REJECTED',\n SERIALIZATION_FAILED = 'SERIALIZATION_FAILED',\n}\n\n// Symbol.for markers, shared by every copy of the library (see check.ts)\nexport const AMQP_EXTENSION_ERROR_MARKER = Symbol.for('amqp-extension/AmqpExtensionError');\nexport const TOPOLOGY_ERROR_MARKER = Symbol.for('amqp-extension/TopologyError');\nexport const CLIENT_ERROR_MARKER = Symbol.for('amqp-extension/ClientError');\nexport const BROKER_ERROR_MARKER = Symbol.for('amqp-extension/BrokerError');\nexport const SERIALIZATION_ERROR_MARKER = Symbol.for('amqp-extension/SerializationError');\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { BaseError, hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AMQP_EXTENSION_ERROR_MARKER } from './constants';\n\n/**\n * Root of every error thrown by amqp-extension.\n *\n * instanceof is duck-typed through @ebec/core's marker chain, so it also matches errors\n * from a duplicate copy of the library. Every subclass overrides Symbol.hasInstance with\n * its own marker, otherwise it would inherit this one and match every library error.\n */\nexport class AmqpExtensionError extends BaseError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, AMQP_EXTENSION_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, AMQP_EXTENSION_ERROR_MARKER);\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { BROKER_ERROR_MARKER, ErrorCode } from './constants';\nimport type { AmqpReplyError, BrokerReply } from './types';\n\n/**\n * The broker rejected an operation, e.g. 406 PRECONDITION_FAILED or 403 ACCESS_REFUSED.\n */\nexport class BrokerError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, BROKER_ERROR_MARKER);\n }\n\n readonly replyCode: number;\n\n readonly classId?: number;\n\n readonly methodId?: number;\n\n constructor(input: ErrorInput, reply: BrokerReply) {\n super(input);\n\n this.replyCode = reply.replyCode;\n this.classId = reply.classId;\n this.methodId = reply.methodId;\n\n markInstanceof(this, BROKER_ERROR_MARKER);\n }\n\n override toJSON() {\n return {\n ...super.toJSON(),\n replyCode: this.replyCode,\n classId: this.classId,\n methodId: this.methodId,\n };\n }\n\n static fromAmqp(err: AmqpReplyError) {\n return new BrokerError(\n {\n code: ErrorCode.BROKER_REJECTED,\n message: err.message,\n cause: err,\n },\n {\n replyCode: err.code,\n classId: err.classId,\n methodId: err.methodId,\n },\n );\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { matchesInstanceof } from '@ebec/core';\nimport type { AmqpExtensionError } from './base';\nimport type { BrokerError } from './broker';\nimport type { ClientError } from './client';\nimport {\n AMQP_EXTENSION_ERROR_MARKER,\n BROKER_ERROR_MARKER,\n CLIENT_ERROR_MARKER,\n SERIALIZATION_ERROR_MARKER,\n TOPOLOGY_ERROR_MARKER,\n} from './constants';\nimport type { SerializationError } from './serialization';\nimport type { TopologyError } from './topology';\n\n// Unlike instanceof, the guards also match an error that crossed a boundary as JSON\n// (toJSON() keeps the marker chain as strings). ponytail: such a plain object has the\n// fields but not the methods of the class it is narrowed to.\n\nexport function isAmqpExtensionError(input: unknown) : input is AmqpExtensionError {\n return matchesInstanceof(input, AMQP_EXTENSION_ERROR_MARKER);\n}\n\nexport function isTopologyError(input: unknown) : input is TopologyError {\n return matchesInstanceof(input, TOPOLOGY_ERROR_MARKER);\n}\n\nexport function isClientError(input: unknown) : input is ClientError {\n return matchesInstanceof(input, CLIENT_ERROR_MARKER);\n}\n\nexport function isBrokerError(input: unknown) : input is BrokerError {\n return matchesInstanceof(input, BROKER_ERROR_MARKER);\n}\n\nexport function isSerializationError(input: unknown) : input is SerializationError {\n return matchesInstanceof(input, SERIALIZATION_ERROR_MARKER);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { CLIENT_ERROR_MARKER, ErrorCode } from './constants';\n\nexport class ClientError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, CLIENT_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, CLIENT_ERROR_MARKER);\n }\n static closed() {\n return new ClientError({ code: ErrorCode.CLIENT_CLOSED, message: 'The client is closed.' });\n }\n\n static channelClosed(cause?: unknown) {\n return new ClientError({\n code: ErrorCode.CHANNEL_CLOSED,\n message: 'Channel closed',\n cause,\n });\n }\n\n static handlerMissing(type?: string) {\n return new ClientError({\n code: ErrorCode.HANDLER_MISSING,\n message: typeof type === 'string' ? `No handler for the message type \"${type}\".` : 'No handler for a message without type.',\n });\n }\n\n static attemptsExhausted(type?: string, cause?: unknown) {\n return new ClientError({\n code: ErrorCode.ATTEMPTS_EXHAUSTED,\n message: typeof type === 'string' ?\n `The retry attempts for the message type \"${type}\" are exhausted.` :\n 'The retry attempts for a message without type are exhausted.',\n cause,\n });\n }\n\n static timeout(cause?: unknown) {\n return new ClientError({\n code: ErrorCode.PUBLISH_TIMEOUT,\n message: 'The publish operation timed out.',\n cause,\n });\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { ErrorCode, SERIALIZATION_ERROR_MARKER } from './constants';\n\nexport class SerializationError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, SERIALIZATION_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, SERIALIZATION_ERROR_MARKER);\n }\n static payload(cause?: unknown) {\n return new SerializationError({\n code: ErrorCode.SERIALIZATION_FAILED,\n message: 'The message payload could not be serialized.',\n cause,\n });\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { ErrorCode, TOPOLOGY_ERROR_MARKER } from './constants';\n\nexport class TopologyError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, TOPOLOGY_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, TOPOLOGY_ERROR_MARKER);\n }\n static queueNameEmpty() {\n return new TopologyError({\n code: ErrorCode.QUEUE_NAME_EMPTY,\n message: 'The queue name can not be empty if the default exchange is selected.',\n });\n }\n\n static exchangeNameMissing() {\n return new TopologyError({\n code: ErrorCode.EXCHANGE_NAME_MISSING,\n message: 'A non default exchange requires a name.',\n });\n }\n\n static destinationMissing() {\n return new TopologyError({\n code: ErrorCode.DESTINATION_MISSING,\n message: 'The publish operation requires a destination.',\n });\n }\n}\n","export enum ExchangeType {\n FANOUT = 'fanout',\n DIRECT = 'direct',\n TOPIC = 'topic',\n HEADERS = 'headers',\n}\n","import { ExchangeType } from './constants';\n\nexport function isDefaultExchange(\n input?: `${ExchangeType}`,\n) : input is ExchangeType.DIRECT {\n return typeof input === 'undefined' || input === ExchangeType.DIRECT;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport { ClientError } from '../errors';\nimport { ConsumeHandlerAnyKey } from './constants';\nimport { retryMessage } from './retry';\nimport type { ConsumeHandlers, ConsumeOptions, HandleMessageContext } from './types';\n\ntype Settlement = Pick<Channel, 'ack' | 'nack'>;\n\nfunction settle(fn: () => void) : void {\n try {\n fn();\n } catch {\n // the channel closed while the handler ran (e.g. reconnect): the broker redelivers the message anyway\n }\n}\n\nasync function report(options: ConsumeOptions, error: unknown, message: ConsumeMessage) : Promise<void> {\n if (!options.onError) {\n return;\n }\n\n try {\n await options.onError(error, message);\n } catch {\n // never reject: amqplib discards the consumer callback's promise\n }\n}\n\n/**\n * Track a run by message id until it settles, so redelivered copies can find it.\n */\nasync function track(inFlight: Map<string, Promise<void>>, id: string, run: Promise<void>) : Promise<void> {\n inFlight.set(id, run);\n\n try {\n await run;\n } finally {\n if (inFlight.get(id) === run) {\n inFlight.delete(id);\n }\n }\n}\n\n/**\n * Dispatch a delivery to the handler for its type (or $any) and settle it:\n * ack on success, nack (requeue = requeueOnFailure) on failure or without handler, nothing with noAck.\n * With retry, a handler failure is re-published with the next attempt and the original acked instead,\n * and redeliveries of messages with a messageId are guarded (see ConsumeOptions.retry).\n * A failure is then reported to onError.\n */\nexport async function handleMessage(\n message: ConsumeMessage | null,\n channel: Settlement,\n handlers: ConsumeHandlers,\n options: ConsumeOptions,\n context?: HandleMessageContext,\n) : Promise<void> {\n // null = the broker cancelled the consumer\n if (!message) {\n return;\n }\n\n const id = message.properties.messageId;\n if (!options.retry || options.noAck || !context || typeof id !== 'string') {\n await dispatch(message, channel, handlers, options, context);\n return;\n }\n\n if (message.fields.redelivered) {\n const running = context.inFlight.get(id);\n if (running) {\n // the channel was reset while this consumer still handles the original: drop the copy.\n // Acking it would free the prefetch slot and let the next message of an ordered\n // stream run next to the original, so with ordered it waits (runs never reject).\n if (options.ordered) {\n await running;\n }\n\n settle(() => channel.ack(message));\n return;\n }\n\n // the consumer died mid-handling (crash, consumer timeout), or a channel reset lost the ack\n // of a run that succeeded (that one runs again, at-least-once): a failed attempt.\n // Tracked through the backoff, so a reset during it does not retry it twice.\n // ponytail: in-process only; a redelivery landing on another consumer runs again.\n await track(context.inFlight, id, fail(message, channel, options, context));\n return;\n }\n\n await track(context.inFlight, id, dispatch(message, channel, handlers, options, context));\n}\n\nasync function dispatch(\n message: ConsumeMessage,\n channel: Settlement,\n handlers: ConsumeHandlers,\n options: ConsumeOptions,\n context?: HandleMessageContext,\n) : Promise<void> {\n // the type is set by the publisher (untrusted): never resolve inherited properties like 'toString'\n const { type } = message.properties;\n const handler = (typeof type === 'string' && Object.hasOwn(handlers, type) ? handlers[type] : undefined) ||\n handlers[ConsumeHandlerAnyKey];\n\n if (!handler) {\n if (!options.noAck) {\n settle(() => channel.nack(message, false, options.requeueOnFailure ?? false));\n }\n\n await report(options, ClientError.handlerMissing(type), message);\n return;\n }\n\n try {\n await handler(message, channel as Channel);\n } catch (error) {\n await fail(message, channel, options, context, { error });\n return;\n }\n\n if (!options.noAck) {\n settle(() => channel.ack(message));\n }\n}\n\n/**\n * Settle a failed message: retry it (with retry), else nack it.\n * failure is undefined for a redelivery of a message whose consumer died: there is no error to report.\n */\nasync function fail(\n message: ConsumeMessage,\n channel: Settlement,\n options: ConsumeOptions,\n context?: HandleMessageContext,\n failure?: { error: unknown },\n) : Promise<void> {\n if (options.noAck) {\n if (failure) await report(options, failure.error, message);\n return;\n }\n\n if (!options.retry || !context) {\n settle(() => channel.nack(message, false, options.requeueOnFailure ?? false));\n if (failure) await report(options, failure.error, message);\n return;\n }\n\n let retried : boolean;\n try {\n retried = await retryMessage(message, context.republish, options.retry);\n } catch {\n // the re-publish failed (e.g. broker unavailable): requeue, so it comes back as a redelivery\n settle(() => channel.nack(message, false, true));\n if (failure) await report(options, failure.error, message);\n return;\n }\n\n // ponytail: a crash between the re-publish and this ack duplicates the message (at-least-once)\n settle(() => channel.ack(message));\n\n if (!retried) {\n await report(options, ClientError.attemptsExhausted(message.properties.type, failure?.error), message);\n } else if (failure) {\n await report(options, failure.error, message);\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { AmqpExtensionError } from './base';\nimport { BrokerError } from './broker';\nimport { ClientError } from './client';\nimport type { AmqpReplyError } from './types';\n\n/**\n * Map anything thrown below the Client (amqplib, amqp-connection-manager) onto the error tree.\n */\nexport function toError(e: unknown) : AmqpExtensionError {\n if (e instanceof AmqpExtensionError) {\n return e;\n }\n\n if (!(e instanceof Error)) {\n return new AmqpExtensionError({ message: String(e), cause: e });\n }\n\n if (typeof (e as Partial<AmqpReplyError>).code === 'number') {\n return BrokerError.fromAmqp(e as AmqpReplyError);\n }\n\n // ponytail: amqp-connection-manager's errors carry no class or code, only these messages;\n // a reworded message falls through to the base class\n if (e.message === 'timeout') {\n return ClientError.timeout(e);\n }\n\n if (e.message === 'Channel closed') {\n return ClientError.channelClosed(e);\n }\n\n return new AmqpExtensionError({ message: e.message, cause: e });\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { Channel, Options } from 'amqplib';\nimport type { Exchange } from '../exchange';\nimport { TopologyError } from '../errors';\nimport { isDefaultExchange } from '../exchange';\nimport type { QueueOptions, Topology } from './types';\n\n\nconst QueueArguments = {\n queueType: 'x-queue-type',\n deliveryLimit: 'x-delivery-limit',\n deadLetterExchange: 'x-dead-letter-exchange',\n deadLetterRoutingKey: 'x-dead-letter-routing-key',\n messageTtl: 'x-message-ttl',\n maxLength: 'x-max-length',\n singleActiveConsumer: 'x-single-active-consumer',\n} as const satisfies Record<keyof QueueOptions, string>;\n\nfunction planQueueOptions(options: QueueOptions) : Options.AssertQueue {\n const queueOptions : Options.AssertQueue = { durable: true };\n\n const keys = Object.keys(QueueArguments) as (keyof QueueOptions)[];\n for (const key of keys) {\n const value = options[key];\n // false is left out like undefined, so a queue declared without the option stays equivalent\n if (typeof value !== 'undefined' && value !== false) {\n queueOptions.arguments = { ...queueOptions.arguments, [QueueArguments[key]]: value };\n }\n }\n\n return queueOptions;\n}\n\n/**\n * Plan the topology for publishing to or consuming from (consume = true) a key.\n * Throws on invalid input, before anything touches the broker.\n */\nexport function planTopology(\n exchange: Exchange,\n key: string,\n options: QueueOptions & { queue?: string },\n consume?: boolean,\n) : Topology {\n if (isDefaultExchange(exchange.type)) {\n if (!key) {\n throw TopologyError.queueNameEmpty();\n }\n\n return { queue: { name: key, options: planQueueOptions(options) } };\n }\n\n if (!exchange.name) {\n throw TopologyError.exchangeNameMissing();\n }\n\n const topology : Topology = {\n exchange: {\n name: exchange.name,\n type: exchange.type,\n options: exchange.options,\n },\n };\n\n if (!consume) {\n if (!key) {\n throw TopologyError.destinationMissing();\n }\n\n return topology;\n }\n\n if (options.queue === '') {\n throw TopologyError.queueNameEmpty();\n }\n\n topology.queue = options.queue ?\n { name: options.queue, options: planQueueOptions(options) } :\n {\n name: '',\n options: {\n durable: false,\n autoDelete: true,\n exclusive: true,\n },\n };\n topology.bind = key;\n\n return topology;\n}\n\n/**\n * Declare a planned topology. Returns the (possibly server generated) queue name.\n * Must run inside a channel setup function, so it is replayed on reconnect.\n */\nexport async function assertTopology(channel: Channel, topology: Topology) : Promise<string | undefined> {\n if (topology.exchange) {\n await channel.assertExchange(topology.exchange.name, topology.exchange.type, topology.exchange.options);\n }\n\n if (!topology.queue) {\n return undefined;\n }\n\n const { queue } = await channel.assertQueue(topology.queue.name, topology.queue.options);\n if (topology.exchange && typeof topology.bind === 'string') {\n await channel.bindQueue(queue, topology.exchange.name, topology.bind);\n }\n\n return queue;\n}\n","import { createMerger } from 'smob';\n\nconst mergeOptions = createMerger({\n priority: 'left',\n inPlace: false,\n clone: true,\n array: true,\n arrayDistinct: true,\n});\n\nexport {\n mergeOptions,\n};\n","/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ChannelWrapper } from 'amqp-connection-manager';\nimport { connect } from 'amqp-connection-manager';\nimport type { Channel } from 'amqplib';\nimport type {\n ConsumeContext,\n ConsumeHandlers,\n ConsumeOptions,\n Consumer,\n HandleMessageContext,\n} from './consume';\nimport { handleMessage } from './consume/utils';\nimport { ClientError, SerializationError } from './errors';\nimport { toError } from './errors/utils';\nimport type { Exchange } from './exchange';\nimport { ExchangeType } from './exchange';\nimport type { PublishContext, PublishOptions, RepublishOptions } from './publish';\nimport { assertTopology, planTopology } from './queue/utils';\nimport type { ClientContext, Connection } from './types';\nimport { mergeOptions } from './utils';\n\n// connections closed through Client.close(), shared by of() siblings\nconst closed = new WeakSet<Connection>();\n\nconst noop = () => undefined;\n\n/**\n * Wrap a setup function, so a broker rejection during it (e.g. 403/406) closes only this channel:\n * without an 'error' listener on the raw channel, amqplib rethrows it and tears down the whole connection.\n * Only during setup: a channel error afterwards must still recycle the connection, because\n * amqp-connection-manager never recovers a channel-only close, so consumers would silently die.\n */\nfunction guard(setup: (channel: Channel) => Promise<unknown>) {\n return async (channel: Channel) => {\n channel.on('error', noop);\n\n try {\n await setup(channel);\n } finally {\n channel.off('error', noop);\n }\n };\n}\n\n/**\n * Reject when the broker rejects a setup function (an error with an AMQP reply code)\n * or the channel is closed (client.close()).\n * Errors without a reply code (connection dropped mid-setup) are transient:\n * the setup runs again on reconnect, so keep waiting.\n */\nfunction failure(channel: ChannelWrapper) : Promise<never> {\n const promise = new Promise<never>((_resolve, reject) => {\n // ponytail: the listener stays, so setup errors after a reconnect are swallowed instead of crashing the process\n channel.on('error', (err: Error & { code?: unknown }) => {\n if (typeof err.code === 'number') {\n reject(err);\n }\n });\n channel.once('close', () => reject(ClientError.channelClosed()));\n });\n\n // it may reject long after the call settled (e.g. close()), which is not an unhandled rejection\n promise.catch(noop);\n\n return promise;\n}\n\nexport class Client {\n public readonly connection: Connection;\n\n protected publishOptions : PublishOptions;\n\n protected consumeOptions : ConsumeOptions;\n\n protected exchange: Exchange;\n\n constructor(ctx: ClientContext) {\n this.connection = ctx.connection ?? connect(ctx.connectionOptions, ctx.connectionManagerOptions);\n this.publishOptions = ctx.publishOptions || {};\n this.consumeOptions = ctx.consumeOptions || {};\n this.exchange = ctx.exchange || {\n type: ExchangeType.DIRECT,\n name: '',\n };\n }\n\n of(exchange: Exchange) : Client {\n return new Client({\n connection: this.connection,\n publishOptions: this.publishOptions,\n consumeOptions: this.consumeOptions,\n exchange,\n });\n }\n\n /**\n * Close the (shared) connection and all its channels.\n */\n async close() : Promise<void> {\n closed.add(this.connection);\n await this.connection.close();\n }\n\n /**\n * `await using client = new Client(...)` closes the client when the scope ends.\n * Like close(), it closes the shared connection, so use it on the root client, not on of() siblings.\n */\n async [Symbol.asyncDispose]() : Promise<void> {\n await this.close();\n }\n\n protected assertOpen() : void {\n if (closed.has(this.connection)) {\n throw ClientError.closed();\n }\n }\n\n async consume(ctx: ConsumeContext) : Promise<Consumer>;\n\n async consume(from: string, handlers: ConsumeHandlers): Promise<Consumer>;\n\n async consume(from: string, options: ConsumeOptions, handlers: ConsumeHandlers): Promise<Consumer>;\n\n async consume(\n _ctxOrFrom: ConsumeContext | string,\n _optionsOrHandlers?: ConsumeOptions | ConsumeHandlers,\n _handlers?: ConsumeHandlers,\n ) : Promise<Consumer> {\n const ctx : ConsumeContext = typeof _ctxOrFrom === 'string' ?\n {\n from: _ctxOrFrom,\n options: _handlers ? _optionsOrHandlers as ConsumeOptions : undefined,\n handlers: _handlers || _optionsOrHandlers as ConsumeHandlers,\n } :\n _ctxOrFrom;\n\n try {\n this.assertOpen();\n\n let options = this.consumeOptions;\n if (ctx.options) {\n // smob clones through structuredClone, which throws on functions\n const { onError, ...rest } = ctx.options;\n const { onError: fallback, ...defaults } = this.consumeOptions;\n options = { ...mergeOptions(rest, defaults), onError: onError ?? fallback };\n }\n\n const topology = planTopology(this.exchange, ctx.from, options, true);\n\n let cancelled = false;\n // the raw channel and consumer tag of the latest setup run\n let current : { ch: Channel, consumerTag: string } | undefined;\n // the latest setup run, awaited by cancel(): one in progress during a reconnect still registers a consumer\n let running : Promise<void> | undefined;\n const inFlight = new Set<Promise<void>>();\n // with retry: the same runs by messageId, for the redelivery guard; kept across setup runs (reconnects)\n const tracked = new Map<string, Promise<void>>();\n\n const channel = this.connection.createChannel({\n setup: guard((ch: Channel) => {\n running = (async () => {\n if (cancelled) {\n return;\n }\n\n const queue = await assertTopology(ch, topology) as string;\n\n if (typeof options.prefetchCount === 'number') {\n await ch.prefetch(options.prefetchCount);\n }\n\n const context : HandleMessageContext = {\n inFlight: tracked,\n republish: (content, props) => this.republish(queue, content, props),\n };\n\n const { consumerTag } = await ch.consume(queue, (message) => {\n const handled = handleMessage(message, ch, ctx.handlers, options, context);\n inFlight.add(handled);\n // handleMessage never rejects\n handled.then(() => inFlight.delete(handled));\n }, options);\n current = { ch, consumerTag };\n })();\n\n return running;\n }),\n });\n\n try {\n await Promise.race([channel.waitForConnect(), failure(channel)]);\n } catch (e) {\n // not awaited: amqplib never settles the close when the connection drops before close-ok\n channel.close().catch(noop);\n throw e;\n }\n\n let cancelling : Promise<void> | undefined;\n const cancel = () => {\n cancelling ??= (async () => {\n // no setup run after this one: a reconnect does not re-register the consumer\n cancelled = true;\n await running?.catch(noop);\n\n // basic.cancel: no new deliveries, the channel stays open to settle the in-flight ones\n // (fails on a closed channel, e.g. after close() or during a reconnect)\n await current?.ch.cancel(current.consumerTag).catch(noop);\n\n // ponytail: a handler that never settles hangs cancel()\n // (a loop: deliveries that arrived before the cancel took effect add to the set)\n while (inFlight.size > 0) {\n await Promise.all(inFlight);\n }\n\n // ponytail: hangs if the connection drops between ChannelClose and CloseOk (amqplib)\n await channel.close().catch(noop);\n })();\n\n return cancelling;\n };\n\n return { cancel, [Symbol.asyncDispose]: cancel };\n } catch (e) {\n throw toError(e);\n }\n }\n\n /**\n * Re-publish a message for a retry, through the default exchange by queue name:\n * that reaches the queue whatever exchange delivered it, without re-declaring it.\n * Its own channel, not the consume channel: that one may have been reset while\n * the handler ran, and this one waits for the broker's confirm.\n *\n * ponytail: a server-named queue is gone after a reconnect, so a retry of a\n * message from before it is unroutable and dropped by the broker.\n */\n protected async republish(queue: string, content: Buffer, options: RepublishOptions) : Promise<void> {\n this.assertOpen();\n\n const channel = this.connection.createChannel();\n\n // bounded, so a broker outage reaches the requeue nack instead of hanging cancel()\n const published = channel.publish('', queue, content, { ...options, timeout: 30_000 });\n published.catch(noop);\n\n try {\n // failure() also listens for the channel's errors: without a listener, a connection\n // lost while the channel opens surfaces as an unhandled rejection\n await Promise.race([published, failure(channel)]);\n } finally {\n // not awaited, see consume()\n channel.close().catch(noop);\n }\n }\n\n async publish(ctx: PublishContext) : Promise<boolean>;\n\n async publish(to: string, data: any) : Promise<boolean>;\n\n async publish(to: string, data: any, options: PublishOptions): Promise<boolean>;\n\n async publish(\n _toOrCtx: PublishContext | string,\n _data?: any,\n _options?: PublishOptions,\n ) : Promise<boolean> {\n const ctx : PublishContext = typeof _toOrCtx === 'string' ?\n {\n to: _toOrCtx,\n data: _data,\n options: _options,\n } :\n _toOrCtx;\n\n try {\n this.assertOpen();\n\n const options = ctx.options ? mergeOptions(ctx.options, this.publishOptions) : this.publishOptions;\n const topology = planTopology(this.exchange, ctx.to, options);\n\n let content : Buffer;\n if (Buffer.isBuffer(ctx.data)) {\n content = ctx.data;\n } else if (typeof ctx.data === 'string') {\n content = Buffer.from(ctx.data, 'utf-8');\n } else {\n let json : string | undefined;\n try {\n json = JSON.stringify(ctx.data);\n } catch (e) {\n throw SerializationError.payload(e);\n }\n\n // undefined, functions and symbols serialize to undefined\n if (typeof json === 'undefined') {\n throw SerializationError.payload();\n }\n\n content = Buffer.from(json, 'utf-8');\n }\n\n // ponytail: one channel per publish (self-healing, no shared state), reuse channels when throughput matters\n const channel = this.connection.createChannel({ setup: guard((ch: Channel) => assertTopology(ch, topology)) });\n\n // queued right away: sent once the setup ran, bounded by options.timeout, rejected by close()\n const published = channel.publish(this.exchange.name || '', ctx.to, content, options);\n published.catch(noop);\n\n try {\n return await Promise.race([published, failure(channel)]);\n } finally {\n // not awaited, see consume()\n channel.close().catch(noop);\n }\n } catch (e) {\n throw toError(e);\n }\n }\n}\n"],"mappings":";;;;AAOA,MAAa,uBAAuB;;;;;;ACOpC,MAAa,iBAAiB;;;;;;AAO9B,SAAgB,eAAe,YAA4D;CACvF,MAAM,QAAQ,WAAW,UAAU;CAEnC,OAAO,OAAO,UAAU,YAAY,OAAO,cAAc,KAAK,KAAK,SAAS,IAAI,QAAQ;AAC5F;;;;AAKA,SAAgB,kBAAkB,SAAiB,MAAuB;CACtE,OAAO,KAAK,IAAI,OAAO,MAAM,UAAU,IAAI,GAAM;AACrD;;;;;;;;;AAUA,eAAsB,aAClB,SACA,SACA,SACiB;CACjB,MAAM,UAAU,eAAe,QAAQ,UAAU,IAAI;CACrD,IAAI,WAAW,QAAQ,eAAe,IAClC,OAAO;CAGX,MAAM,IAAI,SAAS,YAAY;EAC3B,WAAW,SAAS,kBAAkB,SAAS,QAAQ,SAAS,GAAI,CAAC;CACzE,CAAC;CAED,MAAM,aAAgC;EAClC,GAAG,QAAQ;EACX,SAAS;GAAE,GAAG,QAAQ,WAAW;IAAU,iBAAiB;EAAQ;CACxE;CAEA,OAAO,WAAW;CAElB,MAAM,QAAQ,QAAQ,SAAS,UAAU;CAEzC,OAAO;AACX;;;AC3DA,IAAY,YAAL,yBAAA,WAAA;CACH,UAAA,sBAAA;CACA,UAAA,2BAAA;CACA,UAAA,yBAAA;CACA,UAAA,mBAAA;CACA,UAAA,oBAAA;CACA,UAAA,qBAAA;CACA,UAAA,qBAAA;CACA,UAAA,wBAAA;CACA,UAAA,qBAAA;CACA,UAAA,0BAAA;;AACJ,EAAA,CAAA,CAAA;AAGA,MAAa,8BAA8B,OAAO,IAAI,mCAAmC;AACzF,MAAa,wBAAwB,OAAO,IAAI,8BAA8B;AAC9E,MAAa,sBAAsB,OAAO,IAAI,4BAA4B;AAC1E,MAAa,sBAAs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