amqpx 0.0.0 → 1.0.1
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/LICENSE +8 -0
- package/README.md +63 -0
- package/dist/cjs/channel/channel-implementation.d.ts +30 -0
- package/dist/cjs/channel/channel-implementation.js +212 -0
- package/dist/cjs/channel/channel.d.ts +149 -0
- package/dist/cjs/channel/channel.js +2 -0
- package/dist/cjs/channel/index.d.ts +2 -0
- package/dist/cjs/channel/index.js +5 -0
- package/dist/cjs/channel/types.d.ts +12 -0
- package/dist/cjs/channel/types.js +2 -0
- package/dist/cjs/connection/connection-implementation.d.ts +35 -0
- package/dist/cjs/connection/connection-implementation.js +195 -0
- package/dist/cjs/connection/connection.d.ts +143 -0
- package/dist/cjs/connection/connection.js +11 -0
- package/dist/cjs/connection/index.d.ts +2 -0
- package/dist/cjs/connection/index.js +8 -0
- package/dist/cjs/consumer/base-consumer.d.ts +33 -0
- package/dist/cjs/consumer/base-consumer.js +85 -0
- package/dist/cjs/consumer/batch-consumer-implementation.d.ts +25 -0
- package/dist/cjs/consumer/batch-consumer-implementation.js +313 -0
- package/dist/cjs/consumer/batch-consumer.d.ts +39 -0
- package/dist/cjs/consumer/batch-consumer.js +2 -0
- package/dist/cjs/consumer/consumer-implementation.d.ts +12 -0
- package/dist/cjs/consumer/consumer-implementation.js +105 -0
- package/dist/cjs/consumer/consumer.d.ts +40 -0
- package/dist/cjs/consumer/consumer.js +4 -0
- package/dist/cjs/consumer/index.d.ts +5 -0
- package/dist/cjs/consumer/index.js +10 -0
- package/dist/cjs/consumer/types.d.ts +194 -0
- package/dist/cjs/consumer/types.js +34 -0
- package/dist/cjs/errors.d.ts +22 -0
- package/dist/cjs/errors.js +13 -0
- package/dist/cjs/exchange/default-exchange.d.ts +10 -0
- package/dist/cjs/exchange/default-exchange.js +14 -0
- package/dist/cjs/exchange/exchange-implementation.d.ts +24 -0
- package/dist/cjs/exchange/exchange-implementation.js +159 -0
- package/dist/cjs/exchange/exchange.d.ts +67 -0
- package/dist/cjs/exchange/exchange.js +2 -0
- package/dist/cjs/exchange/index.d.ts +3 -0
- package/dist/cjs/exchange/index.js +5 -0
- package/dist/cjs/exchange/types.d.ts +58 -0
- package/dist/cjs/exchange/types.js +8 -0
- package/dist/cjs/extensions/jest/index.d.ts +7 -0
- package/dist/cjs/extensions/jest/index.js +23 -0
- package/dist/cjs/extensions/jest/test-batch-consumer.d.ts +48 -0
- package/dist/cjs/extensions/jest/test-batch-consumer.js +56 -0
- package/dist/cjs/extensions/jest/test-channel.d.ts +71 -0
- package/dist/cjs/extensions/jest/test-channel.js +75 -0
- package/dist/cjs/extensions/jest/test-connection.d.ts +38 -0
- package/dist/cjs/extensions/jest/test-connection.js +29 -0
- package/dist/cjs/extensions/jest/test-consumer.d.ts +49 -0
- package/dist/cjs/extensions/jest/test-consumer.js +54 -0
- package/dist/cjs/extensions/jest/test-exchange.d.ts +26 -0
- package/dist/cjs/extensions/jest/test-exchange.js +16 -0
- package/dist/cjs/extensions/jest/test-producer.d.ts +33 -0
- package/dist/cjs/extensions/jest/test-producer.js +17 -0
- package/dist/cjs/extensions/jest/test-queue.d.ts +25 -0
- package/dist/cjs/extensions/jest/test-queue.js +17 -0
- package/dist/cjs/extensions/vitest/index.d.ts +7 -0
- package/dist/cjs/extensions/vitest/index.js +23 -0
- package/dist/cjs/extensions/vitest/test-batch-consumer.d.ts +48 -0
- package/dist/cjs/extensions/vitest/test-batch-consumer.js +56 -0
- package/dist/cjs/extensions/vitest/test-channel.d.ts +71 -0
- package/dist/cjs/extensions/vitest/test-channel.js +77 -0
- package/dist/cjs/extensions/vitest/test-connection.d.ts +38 -0
- package/dist/cjs/extensions/vitest/test-connection.js +29 -0
- package/dist/cjs/extensions/vitest/test-consumer.d.ts +49 -0
- package/dist/cjs/extensions/vitest/test-consumer.js +54 -0
- package/dist/cjs/extensions/vitest/test-exchange.d.ts +26 -0
- package/dist/cjs/extensions/vitest/test-exchange.js +16 -0
- package/dist/cjs/extensions/vitest/test-producer.d.ts +34 -0
- package/dist/cjs/extensions/vitest/test-producer.js +18 -0
- package/dist/cjs/extensions/vitest/test-queue.d.ts +25 -0
- package/dist/cjs/extensions/vitest/test-queue.js +17 -0
- package/dist/cjs/extensions/zod/index.d.ts +2 -0
- package/dist/cjs/extensions/zod/index.js +18 -0
- package/dist/cjs/extensions/zod/zod-validated-batch-consumer.d.ts +57 -0
- package/dist/cjs/extensions/zod/zod-validated-batch-consumer.js +46 -0
- package/dist/cjs/extensions/zod/zod-validated-consumer.d.ts +55 -0
- package/dist/cjs/extensions/zod/zod-validated-consumer.js +42 -0
- package/dist/cjs/graceful-shutdown/index.d.ts +1 -0
- package/dist/cjs/graceful-shutdown/index.js +17 -0
- package/dist/cjs/graceful-shutdown/rabbit-closer.d.ts +29 -0
- package/dist/cjs/graceful-shutdown/rabbit-closer.js +42 -0
- package/dist/cjs/index.d.ts +11 -0
- package/dist/cjs/index.js +51 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/predefined.d.ts +62 -0
- package/dist/cjs/predefined.js +27 -0
- package/dist/cjs/producer/index.d.ts +3 -0
- package/dist/cjs/producer/index.js +5 -0
- package/dist/cjs/producer/producer-implementation.d.ts +18 -0
- package/dist/cjs/producer/producer-implementation.js +109 -0
- package/dist/cjs/producer/producer.d.ts +44 -0
- package/dist/cjs/producer/producer.js +2 -0
- package/dist/cjs/producer/types.d.ts +70 -0
- package/dist/cjs/producer/types.js +13 -0
- package/dist/cjs/queue/index.d.ts +3 -0
- package/dist/cjs/queue/index.js +5 -0
- package/dist/cjs/queue/queue-implementation.d.ts +21 -0
- package/dist/cjs/queue/queue-implementation.js +91 -0
- package/dist/cjs/queue/queue.d.ts +55 -0
- package/dist/cjs/queue/queue.js +2 -0
- package/dist/cjs/queue/types.d.ts +25 -0
- package/dist/cjs/queue/types.js +2 -0
- package/dist/cjs/retry/default-retry-strategy.d.ts +9 -0
- package/dist/cjs/retry/default-retry-strategy.js +8 -0
- package/dist/cjs/retry/index.d.ts +4 -0
- package/dist/cjs/retry/index.js +45 -0
- package/dist/cjs/retry/retry-implementation.d.ts +18 -0
- package/dist/cjs/retry/retry-implementation.js +44 -0
- package/dist/cjs/retry/retry-strategy.d.ts +28 -0
- package/dist/cjs/retry/retry-strategy.js +10 -0
- package/dist/cjs/retry/time-strategies.d.ts +45 -0
- package/dist/cjs/retry/time-strategies.js +32 -0
- package/dist/cjs/types.d.ts +30 -0
- package/dist/cjs/types.js +9 -0
- package/dist/cjs/utils.d.ts +11 -0
- package/dist/cjs/utils.js +83 -0
- package/dist/esm/channel/channel-implementation.d.ts +30 -0
- package/dist/esm/channel/channel-implementation.js +208 -0
- package/dist/esm/channel/channel.d.ts +149 -0
- package/dist/esm/channel/channel.js +1 -0
- package/dist/esm/channel/index.d.ts +2 -0
- package/dist/esm/channel/index.js +1 -0
- package/dist/esm/channel/types.d.ts +12 -0
- package/dist/esm/channel/types.js +1 -0
- package/dist/esm/connection/connection-implementation.d.ts +35 -0
- package/dist/esm/connection/connection-implementation.js +157 -0
- package/dist/esm/connection/connection.d.ts +143 -0
- package/dist/esm/connection/connection.js +8 -0
- package/dist/esm/connection/index.d.ts +2 -0
- package/dist/esm/connection/index.js +2 -0
- package/dist/esm/consumer/base-consumer.d.ts +33 -0
- package/dist/esm/consumer/base-consumer.js +81 -0
- package/dist/esm/consumer/batch-consumer-implementation.d.ts +25 -0
- package/dist/esm/consumer/batch-consumer-implementation.js +309 -0
- package/dist/esm/consumer/batch-consumer.d.ts +39 -0
- package/dist/esm/consumer/batch-consumer.js +1 -0
- package/dist/esm/consumer/consumer-implementation.d.ts +12 -0
- package/dist/esm/consumer/consumer-implementation.js +101 -0
- package/dist/esm/consumer/consumer.d.ts +40 -0
- package/dist/esm/consumer/consumer.js +1 -0
- package/dist/esm/consumer/index.d.ts +5 -0
- package/dist/esm/consumer/index.js +3 -0
- package/dist/esm/consumer/types.d.ts +194 -0
- package/dist/esm/consumer/types.js +31 -0
- package/dist/esm/errors.d.ts +22 -0
- package/dist/esm/errors.js +8 -0
- package/dist/esm/exchange/default-exchange.d.ts +10 -0
- package/dist/esm/exchange/default-exchange.js +10 -0
- package/dist/esm/exchange/exchange-implementation.d.ts +24 -0
- package/dist/esm/exchange/exchange-implementation.js +152 -0
- package/dist/esm/exchange/exchange.d.ts +67 -0
- package/dist/esm/exchange/exchange.js +1 -0
- package/dist/esm/exchange/index.d.ts +3 -0
- package/dist/esm/exchange/index.js +1 -0
- package/dist/esm/exchange/types.d.ts +58 -0
- package/dist/esm/exchange/types.js +5 -0
- package/dist/esm/extensions/jest/index.d.ts +7 -0
- package/dist/esm/extensions/jest/index.js +7 -0
- package/dist/esm/extensions/jest/test-batch-consumer.d.ts +48 -0
- package/dist/esm/extensions/jest/test-batch-consumer.js +52 -0
- package/dist/esm/extensions/jest/test-channel.d.ts +71 -0
- package/dist/esm/extensions/jest/test-channel.js +71 -0
- package/dist/esm/extensions/jest/test-connection.d.ts +38 -0
- package/dist/esm/extensions/jest/test-connection.js +25 -0
- package/dist/esm/extensions/jest/test-consumer.d.ts +49 -0
- package/dist/esm/extensions/jest/test-consumer.js +50 -0
- package/dist/esm/extensions/jest/test-exchange.d.ts +26 -0
- package/dist/esm/extensions/jest/test-exchange.js +12 -0
- package/dist/esm/extensions/jest/test-producer.d.ts +33 -0
- package/dist/esm/extensions/jest/test-producer.js +13 -0
- package/dist/esm/extensions/jest/test-queue.d.ts +25 -0
- package/dist/esm/extensions/jest/test-queue.js +13 -0
- package/dist/esm/extensions/vitest/index.d.ts +7 -0
- package/dist/esm/extensions/vitest/index.js +7 -0
- package/dist/esm/extensions/vitest/test-batch-consumer.d.ts +48 -0
- package/dist/esm/extensions/vitest/test-batch-consumer.js +52 -0
- package/dist/esm/extensions/vitest/test-channel.d.ts +71 -0
- package/dist/esm/extensions/vitest/test-channel.js +73 -0
- package/dist/esm/extensions/vitest/test-connection.d.ts +38 -0
- package/dist/esm/extensions/vitest/test-connection.js +25 -0
- package/dist/esm/extensions/vitest/test-consumer.d.ts +49 -0
- package/dist/esm/extensions/vitest/test-consumer.js +50 -0
- package/dist/esm/extensions/vitest/test-exchange.d.ts +26 -0
- package/dist/esm/extensions/vitest/test-exchange.js +12 -0
- package/dist/esm/extensions/vitest/test-producer.d.ts +34 -0
- package/dist/esm/extensions/vitest/test-producer.js +14 -0
- package/dist/esm/extensions/vitest/test-queue.d.ts +25 -0
- package/dist/esm/extensions/vitest/test-queue.js +13 -0
- package/dist/esm/extensions/zod/index.d.ts +2 -0
- package/dist/esm/extensions/zod/index.js +2 -0
- package/dist/esm/extensions/zod/zod-validated-batch-consumer.d.ts +57 -0
- package/dist/esm/extensions/zod/zod-validated-batch-consumer.js +42 -0
- package/dist/esm/extensions/zod/zod-validated-consumer.d.ts +55 -0
- package/dist/esm/extensions/zod/zod-validated-consumer.js +38 -0
- package/dist/esm/graceful-shutdown/index.d.ts +1 -0
- package/dist/esm/graceful-shutdown/index.js +1 -0
- package/dist/esm/graceful-shutdown/rabbit-closer.d.ts +29 -0
- package/dist/esm/graceful-shutdown/rabbit-closer.js +38 -0
- package/dist/esm/index.d.ts +11 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/predefined.d.ts +62 -0
- package/dist/esm/predefined.js +18 -0
- package/dist/esm/producer/index.d.ts +3 -0
- package/dist/esm/producer/index.js +1 -0
- package/dist/esm/producer/producer-implementation.d.ts +18 -0
- package/dist/esm/producer/producer-implementation.js +105 -0
- package/dist/esm/producer/producer.d.ts +44 -0
- package/dist/esm/producer/producer.js +1 -0
- package/dist/esm/producer/types.d.ts +70 -0
- package/dist/esm/producer/types.js +10 -0
- package/dist/esm/queue/index.d.ts +3 -0
- package/dist/esm/queue/index.js +1 -0
- package/dist/esm/queue/queue-implementation.d.ts +21 -0
- package/dist/esm/queue/queue-implementation.js +87 -0
- package/dist/esm/queue/queue.d.ts +55 -0
- package/dist/esm/queue/queue.js +1 -0
- package/dist/esm/queue/types.d.ts +25 -0
- package/dist/esm/queue/types.js +1 -0
- package/dist/esm/retry/default-retry-strategy.d.ts +9 -0
- package/dist/esm/retry/default-retry-strategy.js +5 -0
- package/dist/esm/retry/index.d.ts +4 -0
- package/dist/esm/retry/index.js +4 -0
- package/dist/esm/retry/retry-implementation.d.ts +18 -0
- package/dist/esm/retry/retry-implementation.js +40 -0
- package/dist/esm/retry/retry-strategy.d.ts +28 -0
- package/dist/esm/retry/retry-strategy.js +6 -0
- package/dist/esm/retry/time-strategies.d.ts +45 -0
- package/dist/esm/retry/time-strategies.js +24 -0
- package/dist/esm/types.d.ts +30 -0
- package/dist/esm/types.js +6 -0
- package/dist/esm/utils.d.ts +11 -0
- package/dist/esm/utils.js +72 -0
- package/package.json +101 -6
- package/.claude/settings.local.json +0 -13
- package/.idea/amqp-oop.iml +0 -15
- package/.idea/aws.xml +0 -11
- package/.idea/inspectionProfiles/Project_Default.xml +0 -6
- package/.idea/jsLibraryMappings.xml +0 -6
- package/.idea/jsLinters/eslint.xml +0 -6
- package/.idea/modules.xml +0 -8
- package/.idea/vcs.xml +0 -6
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
import * as amqp from 'amqplib';
|
|
3
|
+
import { Channel } from '../channel';
|
|
4
|
+
import { Queue } from '../queue';
|
|
5
|
+
import { ProducerOptions, Producer } from '../producer';
|
|
6
|
+
import { Exchange, ExchangeConsumerQueueOptions, ExchangeConsumerOptions, ExchangeBatchConsumerOptions } from '../exchange';
|
|
7
|
+
import { ConsumerOptions, Consumer, BatchConsumerOptions, BatchConsumer } from '../consumer';
|
|
8
|
+
/**
|
|
9
|
+
* State in which the connection can be.
|
|
10
|
+
*/
|
|
11
|
+
export declare enum ConnectionState {
|
|
12
|
+
/**
|
|
13
|
+
* Connection is not created yet and there hasn't been attempt to establish it.
|
|
14
|
+
* This is the beginning state.
|
|
15
|
+
*/
|
|
16
|
+
preconnect = "preconnect",
|
|
17
|
+
/**
|
|
18
|
+
* The initial connection is being established.
|
|
19
|
+
*/
|
|
20
|
+
connecting = "connecting",
|
|
21
|
+
/**
|
|
22
|
+
* The connection is established and ready to be used.
|
|
23
|
+
*/
|
|
24
|
+
connected = "connected",
|
|
25
|
+
/**
|
|
26
|
+
* The connection is being closed.
|
|
27
|
+
*/
|
|
28
|
+
closing = "closing",
|
|
29
|
+
/**
|
|
30
|
+
* The connection is fully closed.
|
|
31
|
+
*/
|
|
32
|
+
closed = "closed"
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Events emitted by a {@link Connection}.
|
|
36
|
+
*/
|
|
37
|
+
export interface ConnectionEventMap {
|
|
38
|
+
/**
|
|
39
|
+
* Emitted when the connection retry attempts have been exhausted.
|
|
40
|
+
*/
|
|
41
|
+
connectionRetryExhausted: [];
|
|
42
|
+
/**
|
|
43
|
+
* Emitted when the connection is explicitly closed by calling {@link Connection.close}.
|
|
44
|
+
* This event fires after the underlying amqplib connection is fully shut down.
|
|
45
|
+
* It is NOT emitted when the server drops the connection — in that case,
|
|
46
|
+
* the `reconnecting` event is emitted instead and the client attempts to reconnect.
|
|
47
|
+
* Not emitted if the connection was never established (`preconnect` state) or already closed.
|
|
48
|
+
*/
|
|
49
|
+
close: [];
|
|
50
|
+
/**
|
|
51
|
+
* Emitted once when the server drops the connection and the client begins attempting to reconnect.
|
|
52
|
+
* Followed by one or more `error` events (one per failed attempt), and then either `connected` on success
|
|
53
|
+
* or `connectionRetryExhausted` if all retries are exhausted.
|
|
54
|
+
*/
|
|
55
|
+
reconnecting: [];
|
|
56
|
+
/**
|
|
57
|
+
* Emitted when a connection attempt fails.
|
|
58
|
+
* The error originates from `amqplib` and is forwarded directly.
|
|
59
|
+
* This may fire multiple times during reconnection retries before the connection succeeds or
|
|
60
|
+
* `connectionRetryExhausted` is emitted.
|
|
61
|
+
*/
|
|
62
|
+
connectionError: [err: unknown];
|
|
63
|
+
/**
|
|
64
|
+
* Emitted when the connection is successfully established (or re-established after reconnection).
|
|
65
|
+
*/
|
|
66
|
+
connected: [connection: Connection];
|
|
67
|
+
/**
|
|
68
|
+
* Emitted when the underlying amqplib connection encounters an error.
|
|
69
|
+
*/
|
|
70
|
+
error: [err: unknown];
|
|
71
|
+
}
|
|
72
|
+
export interface Connection extends EventEmitter<ConnectionEventMap> {
|
|
73
|
+
/**
|
|
74
|
+
* Establishes the connection. Safe to call concurrently — multiple callers will share the same attempt.
|
|
75
|
+
* After retries are exhausted ({@link ConnectionEventMap.connectionRetryExhausted}), the connection moves to the
|
|
76
|
+
* `closed` state, but `connect()` may be called again to start a fresh connection attempt.
|
|
77
|
+
*/
|
|
78
|
+
connect(): Promise<Connection>;
|
|
79
|
+
/**
|
|
80
|
+
* Returns the current state of the connection.
|
|
81
|
+
*/
|
|
82
|
+
state(): ConnectionState;
|
|
83
|
+
/**
|
|
84
|
+
* Gracefully closes the connection.
|
|
85
|
+
* Emits the `close` event after the underlying amqplib connection is fully shut down.
|
|
86
|
+
* Has no effect if the connection is in `preconnect` or `closed` state.
|
|
87
|
+
* @param timeout - Maximum milliseconds to wait for the underlying connection to close.
|
|
88
|
+
* Throws `'Connection close timed out'` if exceeded. Waits 30s when omitted.
|
|
89
|
+
*/
|
|
90
|
+
close(timeout?: number): Promise<void>;
|
|
91
|
+
/**
|
|
92
|
+
* Creates a new channel on this connection.
|
|
93
|
+
* @param isConfirmed - If true, creates a confirm channel (publisher confirms enabled).
|
|
94
|
+
*/
|
|
95
|
+
createChannel(isConfirmed?: boolean): Channel;
|
|
96
|
+
/**
|
|
97
|
+
* Creates a producer for a queue and opens a dedicated channel for it.
|
|
98
|
+
* @param queue - Target queue.
|
|
99
|
+
* @param options - Optional producer options (serialization, routing key, hooks, …).
|
|
100
|
+
* @param isConfirmed - If true, the dedicated channel uses publisher confirms.
|
|
101
|
+
*/
|
|
102
|
+
createProducerForQueue<T>(queue: Queue, options?: ProducerOptions<T>, isConfirmed?: boolean): Promise<Producer<T>>;
|
|
103
|
+
/**
|
|
104
|
+
* Creates a producer for an exchange and opens a dedicated channel for it.
|
|
105
|
+
* @param exchange - Target exchange.
|
|
106
|
+
* @param options - Optional producer options (serialization, routing key, hooks, …).
|
|
107
|
+
* @param isConfirmed - If true, the dedicated channel uses publisher confirms.
|
|
108
|
+
*/
|
|
109
|
+
createProducerForExchange<T>(exchange: Exchange, options?: ProducerOptions<T>, isConfirmed?: boolean): Promise<Producer<T>>;
|
|
110
|
+
/**
|
|
111
|
+
* Creates a consumer for a queue and opens a dedicated channel for it.
|
|
112
|
+
* @param queue - Source queue.
|
|
113
|
+
* @param options - Optional consumer options (failure strategy, prefetch, …).
|
|
114
|
+
*/
|
|
115
|
+
createConsumerForQueue<T>(queue: Queue, options?: ConsumerOptions<T>): Promise<Consumer<T>>;
|
|
116
|
+
/**
|
|
117
|
+
* Creates a consumer for an exchange and opens a dedicated channel for it.
|
|
118
|
+
* Internally asserts an exclusive queue and binds it to the exchange.
|
|
119
|
+
* @param exchange - Source exchange.
|
|
120
|
+
* @param options - Consumer options, including the binding pattern.
|
|
121
|
+
* @param queueOptions - Options for the auto-created exclusive queue.
|
|
122
|
+
*/
|
|
123
|
+
createConsumerForExchange<T>(exchange: Exchange, options: ExchangeConsumerOptions<T>, queueOptions?: ExchangeConsumerQueueOptions): Promise<Consumer<T>>;
|
|
124
|
+
/**
|
|
125
|
+
* Creates a batch consumer for a queue and opens a dedicated channel for it.
|
|
126
|
+
* @param queue - Source queue.
|
|
127
|
+
* @param options - Optional batch consumer options (batch size, failure strategy, prefetch, …).
|
|
128
|
+
*/
|
|
129
|
+
createBatchConsumerForQueue<T>(queue: Queue, options?: BatchConsumerOptions<T>): Promise<BatchConsumer<T>>;
|
|
130
|
+
/**
|
|
131
|
+
* Creates a batch consumer for an exchange and opens a dedicated channel for it.
|
|
132
|
+
* Internally asserts an exclusive queue and binds it to the exchange.
|
|
133
|
+
* @param exchange - Source exchange.
|
|
134
|
+
* @param options - Batch consumer options, including the binding pattern.
|
|
135
|
+
* @param queueOptions - Options for the auto-created exclusive queue.
|
|
136
|
+
*/
|
|
137
|
+
createBatchConsumerForExchange<T>(exchange: Exchange, options: ExchangeBatchConsumerOptions<T>, queueOptions?: ExchangeConsumerQueueOptions): Promise<BatchConsumer<T>>;
|
|
138
|
+
/**
|
|
139
|
+
* Returns the underlying amqplib connection. Resolves once the connection is established.
|
|
140
|
+
* This is intended for internal use.
|
|
141
|
+
*/
|
|
142
|
+
native(): Promise<amqp.ChannelModel>;
|
|
143
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export var ConnectionState;
|
|
2
|
+
(function (ConnectionState) {
|
|
3
|
+
ConnectionState["preconnect"] = "preconnect";
|
|
4
|
+
ConnectionState["connecting"] = "connecting";
|
|
5
|
+
ConnectionState["connected"] = "connected";
|
|
6
|
+
ConnectionState["closing"] = "closing";
|
|
7
|
+
ConnectionState["closed"] = "closed";
|
|
8
|
+
})(ConnectionState || (ConnectionState = {}));
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { Queue } from '../queue';
|
|
3
|
+
import { Channel } from '../channel';
|
|
4
|
+
import { ConsumerWrapper } from './types';
|
|
5
|
+
/**
|
|
6
|
+
* Events emitted by a {@link BaseConsumer}.
|
|
7
|
+
*/
|
|
8
|
+
export type BaseConsumerEventMap = {
|
|
9
|
+
/**
|
|
10
|
+
* Emitted when an error occurs during reconnection to RabbitMQ.
|
|
11
|
+
*/
|
|
12
|
+
reconnectError: [error: unknown];
|
|
13
|
+
/**
|
|
14
|
+
* Emitted when the consumer is closed and all in-flight messages have been processed.
|
|
15
|
+
*/
|
|
16
|
+
close: [];
|
|
17
|
+
/**
|
|
18
|
+
* Emitted when an internal processing error occurs.
|
|
19
|
+
*/
|
|
20
|
+
error: [error: Error];
|
|
21
|
+
[event: string]: unknown[];
|
|
22
|
+
};
|
|
23
|
+
export declare abstract class BaseConsumer<CallbackFn, EventMap extends BaseConsumerEventMap> extends EventEmitter<EventMap> {
|
|
24
|
+
readonly channel: Channel;
|
|
25
|
+
readonly queue: Queue;
|
|
26
|
+
protected consumer: Promise<ConsumerWrapper<CallbackFn>> | null;
|
|
27
|
+
protected notifyMessageProcessed: (() => void) | undefined;
|
|
28
|
+
private reconnectTimer;
|
|
29
|
+
protected constructor(channel: Channel, queue: Queue);
|
|
30
|
+
protected readonly channelCloseCallback: () => void;
|
|
31
|
+
abstract listen(callback: CallbackFn): Promise<this>;
|
|
32
|
+
close(timeout?: number): Promise<void>;
|
|
33
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { debuglog } from 'util';
|
|
11
|
+
import { EventEmitter } from 'node:events';
|
|
12
|
+
import { errToMessage, LIB_NAME, sleepPromise } from '../utils';
|
|
13
|
+
import { RECONNECT_TIMEOUT } from './consumer';
|
|
14
|
+
const debug = debuglog(`${LIB_NAME}:consume`);
|
|
15
|
+
export class BaseConsumer extends EventEmitter {
|
|
16
|
+
constructor(channel, queue) {
|
|
17
|
+
super();
|
|
18
|
+
this.channel = channel;
|
|
19
|
+
this.queue = queue;
|
|
20
|
+
this.consumer = null;
|
|
21
|
+
this.notifyMessageProcessed = undefined;
|
|
22
|
+
this.channelCloseCallback = () => {
|
|
23
|
+
debug(`native-close reconnect-in=%dms`, RECONNECT_TIMEOUT);
|
|
24
|
+
this.reconnectTimer = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
|
|
25
|
+
this.reconnectTimer = undefined;
|
|
26
|
+
if (this.consumer) {
|
|
27
|
+
debug(`reconnecting`);
|
|
28
|
+
try {
|
|
29
|
+
const { callback } = yield this.consumer;
|
|
30
|
+
this.consumer = null;
|
|
31
|
+
yield this.listen(callback);
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
debug(`reconnect-error error=%s`, errToMessage(err));
|
|
35
|
+
this.emit('reconnectError', err);
|
|
36
|
+
this.consumer = null;
|
|
37
|
+
void this.close();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}), RECONNECT_TIMEOUT);
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
close() {
|
|
44
|
+
return __awaiter(this, arguments, void 0, function* (timeout = 30000) {
|
|
45
|
+
clearTimeout(this.reconnectTimer);
|
|
46
|
+
this.reconnectTimer = undefined;
|
|
47
|
+
this.channel.off('close', this.channelCloseCallback);
|
|
48
|
+
if (this.consumer) {
|
|
49
|
+
debug(`closing timeout=%dms`, timeout);
|
|
50
|
+
const consumer = yield this.consumer;
|
|
51
|
+
const channel = yield this.channel.native();
|
|
52
|
+
debug('closing tag=%s in-flight=%d', consumer.amqpConsumer.consumerTag, consumer.messagesInFlight);
|
|
53
|
+
yield channel.cancel(consumer.amqpConsumer.consumerTag);
|
|
54
|
+
const waitForAllMessagesPromise = new Promise(resolve => {
|
|
55
|
+
this.notifyMessageProcessed = () => {
|
|
56
|
+
if (consumer.messagesInFlight === 0)
|
|
57
|
+
resolve();
|
|
58
|
+
};
|
|
59
|
+
this.notifyMessageProcessed();
|
|
60
|
+
});
|
|
61
|
+
try {
|
|
62
|
+
const abort = new AbortController();
|
|
63
|
+
yield Promise.race([
|
|
64
|
+
waitForAllMessagesPromise.then(() => abort.abort()),
|
|
65
|
+
sleepPromise(timeout).then(() => {
|
|
66
|
+
if (!abort.signal.aborted)
|
|
67
|
+
throw new Error('Consumer close timeout');
|
|
68
|
+
}),
|
|
69
|
+
]);
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
debug('closed');
|
|
73
|
+
consumer.isConnected = false;
|
|
74
|
+
this.consumer = null;
|
|
75
|
+
this.notifyMessageProcessed = undefined;
|
|
76
|
+
this.emit('close');
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Queue } from '../queue';
|
|
2
|
+
import { Channel } from '../channel';
|
|
3
|
+
import { BatchConsumerCallbackFn, BatchConsumerOptions } from './types';
|
|
4
|
+
import { BatchConsumer, BatchConsumerEventMap } from './batch-consumer';
|
|
5
|
+
import { BaseConsumer } from './base-consumer';
|
|
6
|
+
export declare class BatchConsumerImplementation<Message> extends BaseConsumer<BatchConsumerCallbackFn<Message>, BatchConsumerEventMap> implements BatchConsumer<Message> {
|
|
7
|
+
private static readonly DEFAULT_BATCH_SIZE;
|
|
8
|
+
private readonly options;
|
|
9
|
+
private batchFillTimer;
|
|
10
|
+
constructor(channel: Channel, queue: Queue, options?: BatchConsumerOptions<Message>);
|
|
11
|
+
listen(callback: BatchConsumerCallbackFn<Message>): Promise<this>;
|
|
12
|
+
private messageReceiver;
|
|
13
|
+
private get effectiveBatchSize();
|
|
14
|
+
private get shouldAutoAck();
|
|
15
|
+
private get maxWaitTimeForAck();
|
|
16
|
+
private get maxWaitTimeForBatch();
|
|
17
|
+
private processError;
|
|
18
|
+
private handleBatch;
|
|
19
|
+
private handleBatchError;
|
|
20
|
+
private handleFailureStrategy;
|
|
21
|
+
private nackMessages;
|
|
22
|
+
private splitBatch;
|
|
23
|
+
private removeProcessedBatches;
|
|
24
|
+
private planMessageAcknowledgment;
|
|
25
|
+
}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { debuglog } from 'util';
|
|
11
|
+
import { deepMerge, errToMessage, last, LIB_NAME } from '../utils';
|
|
12
|
+
import { BatchFailureStrategy, BatchState, ConsumptionFailureStrategy, DEFAULT_CONSUMER_OPTIONS, } from './types';
|
|
13
|
+
import { BaseConsumer } from './base-consumer';
|
|
14
|
+
const debug = debuglog(`${LIB_NAME}:consume:batch`);
|
|
15
|
+
export class BatchConsumerImplementation extends BaseConsumer {
|
|
16
|
+
constructor(channel, queue, options = {}) {
|
|
17
|
+
super(channel, queue);
|
|
18
|
+
this.options = deepMerge({}, DEFAULT_CONSUMER_OPTIONS, options);
|
|
19
|
+
if (this.effectiveBatchSize <= 1 && this.options.batchFailureStrategy === BatchFailureStrategy.Split)
|
|
20
|
+
throw new Error('Cannot have split batch failure strategy when batch size is 1');
|
|
21
|
+
}
|
|
22
|
+
listen(callback) {
|
|
23
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
24
|
+
if (this.consumer)
|
|
25
|
+
throw new Error('Listener is already attached');
|
|
26
|
+
this.consumer = (() => __awaiter(this, void 0, void 0, function* () {
|
|
27
|
+
const [channel, queueName] = yield Promise.all([
|
|
28
|
+
this.channel.native(),
|
|
29
|
+
this.queue.name(),
|
|
30
|
+
]);
|
|
31
|
+
debug('start-listening queue=%s prefetch=%d ack=%s', queueName, this.options.prefetch, !this.shouldAutoAck);
|
|
32
|
+
yield channel.prefetch(this.options.prefetch);
|
|
33
|
+
const consumerWrapper = {
|
|
34
|
+
callback,
|
|
35
|
+
messagesInFlight: 0,
|
|
36
|
+
isConnected: true,
|
|
37
|
+
batches: [],
|
|
38
|
+
};
|
|
39
|
+
let listenerCloseHandler;
|
|
40
|
+
const channelCloseHandler = () => {
|
|
41
|
+
debug(`channel-closed queue=%s`, queueName);
|
|
42
|
+
consumerWrapper.isConnected = false;
|
|
43
|
+
this.off('close', listenerCloseHandler);
|
|
44
|
+
this.channelCloseCallback();
|
|
45
|
+
};
|
|
46
|
+
listenerCloseHandler = () => {
|
|
47
|
+
debug(`catch-close-event queue=%s`, queueName);
|
|
48
|
+
consumerWrapper.isConnected = false;
|
|
49
|
+
this.channel.off('close', channelCloseHandler);
|
|
50
|
+
};
|
|
51
|
+
this.channel.once('close', channelCloseHandler);
|
|
52
|
+
this.once('close', listenerCloseHandler);
|
|
53
|
+
consumerWrapper.amqpConsumer = yield channel.consume(queueName, this.messageReceiver.bind(this, callback, channel, consumerWrapper, queueName), Object.assign(Object.assign({}, this.options.consumeOptions), { noAck: this.shouldAutoAck }));
|
|
54
|
+
return consumerWrapper;
|
|
55
|
+
}))();
|
|
56
|
+
yield this.consumer;
|
|
57
|
+
return this;
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
messageReceiver(callback, originalChannel, consumerWrapper, queueName, msg) {
|
|
61
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
62
|
+
var _a;
|
|
63
|
+
if (!msg) {
|
|
64
|
+
debug('receive-empty-message queue=%s', queueName);
|
|
65
|
+
yield this.close();
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
consumerWrapper.messagesInFlight++;
|
|
69
|
+
debug('receive-message queue=%s in-flight=%d', queueName, consumerWrapper.messagesInFlight);
|
|
70
|
+
if (consumerWrapper.batches.length === 0 || ((_a = last(consumerWrapper.batches)) === null || _a === void 0 ? void 0 : _a.state) !== BatchState.WaitingForData) {
|
|
71
|
+
consumerWrapper.batches.push({
|
|
72
|
+
messages: [],
|
|
73
|
+
state: BatchState.WaitingForData,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
const lastBatch = last(consumerWrapper.batches);
|
|
77
|
+
if (!lastBatch)
|
|
78
|
+
throw this.processError('Internal error: Cannot get last batch');
|
|
79
|
+
lastBatch.messages.push({ rabbitMessage: msg });
|
|
80
|
+
if (lastBatch.messages.length >= this.effectiveBatchSize) {
|
|
81
|
+
debug('processing-batch queue=%s reason=%s', queueName, 'full-batch');
|
|
82
|
+
clearTimeout(this.batchFillTimer);
|
|
83
|
+
this.batchFillTimer = undefined;
|
|
84
|
+
yield this.handleBatch(callback, originalChannel, lastBatch, consumerWrapper, queueName);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (!this.batchFillTimer) {
|
|
88
|
+
this.batchFillTimer = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
|
|
89
|
+
debug('processing-batch queue=%s reason=%s', queueName, 'timeout');
|
|
90
|
+
this.batchFillTimer = undefined;
|
|
91
|
+
yield this.handleBatch(callback, originalChannel, lastBatch, consumerWrapper, queueName);
|
|
92
|
+
}), this.maxWaitTimeForBatch);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
get effectiveBatchSize() {
|
|
97
|
+
if (this.options.batchSize >= 0)
|
|
98
|
+
return this.options.batchSize;
|
|
99
|
+
if (this.options.prefetch > 0)
|
|
100
|
+
return this.options.prefetch;
|
|
101
|
+
debug('use-default-batch-size effective-batch-size=%d provided-batch-size=%d provided-prefetch=%d', BatchConsumerImplementation.DEFAULT_BATCH_SIZE, this.options.batchSize, this.options.prefetch);
|
|
102
|
+
return BatchConsumerImplementation.DEFAULT_BATCH_SIZE;
|
|
103
|
+
}
|
|
104
|
+
get shouldAutoAck() {
|
|
105
|
+
return this.options.failureStrategy === ConsumptionFailureStrategy.Drop && this.options.prefetch <= 0;
|
|
106
|
+
}
|
|
107
|
+
get maxWaitTimeForAck() {
|
|
108
|
+
return Math.max(this.options.maxWaitTimeForAck, 0);
|
|
109
|
+
}
|
|
110
|
+
get maxWaitTimeForBatch() {
|
|
111
|
+
return Math.max(this.options.maxWaitTimeForBatch, 0);
|
|
112
|
+
}
|
|
113
|
+
processError(message) {
|
|
114
|
+
const err = new Error(message);
|
|
115
|
+
this.emit('error', err);
|
|
116
|
+
return err;
|
|
117
|
+
}
|
|
118
|
+
handleBatch(callback, originalChannel, batch, consumerWrapper, queueName) {
|
|
119
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
120
|
+
if (batch.state !== BatchState.WaitingForData)
|
|
121
|
+
return;
|
|
122
|
+
if (!consumerWrapper.isConnected) {
|
|
123
|
+
debug('batch-acknowledged queue=%s reason=%s', queueName, 'disconnected');
|
|
124
|
+
batch.state = BatchState.Acknowledged;
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
debug('processing-batch-started queue=%s batch-size=%d', queueName, batch.messages.length);
|
|
129
|
+
batch.state = BatchState.Processing;
|
|
130
|
+
const parsedMessages = yield Promise.all(batch.messages.map((_a) => __awaiter(this, [_a], void 0, function* ({ rabbitMessage }) {
|
|
131
|
+
return ({
|
|
132
|
+
rabbitMessage,
|
|
133
|
+
message: yield this.options.parseMessageFn(rabbitMessage.content),
|
|
134
|
+
});
|
|
135
|
+
})));
|
|
136
|
+
yield callback({
|
|
137
|
+
messages: parsedMessages,
|
|
138
|
+
channel: this.channel,
|
|
139
|
+
});
|
|
140
|
+
debug('batch-processed queue=%s reason=%s', queueName, 'succeess');
|
|
141
|
+
batch.state = BatchState.Processed;
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
debug('batch-processing-failed queue=%s error=%s strategy=%s', queueName, errToMessage(error), this.options.batchFailureStrategy);
|
|
145
|
+
this.emit('handlingFailed', error);
|
|
146
|
+
yield this.handleBatchError(callback, originalChannel, batch, consumerWrapper, queueName);
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
yield this.planMessageAcknowledgment(consumerWrapper, originalChannel, queueName);
|
|
150
|
+
this.removeProcessedBatches(consumerWrapper, queueName);
|
|
151
|
+
debug('processing-batch-finished queue=%s batch-size=%d', queueName, batch.messages.length);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
handleBatchError(callback, originalChannel, batch, consumerWrapper, queueName) {
|
|
156
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
157
|
+
batch.state = BatchState.Failed;
|
|
158
|
+
if (!consumerWrapper.isConnected) {
|
|
159
|
+
debug('batch-acknowledged queue=%s reason=%s', queueName, 'disconnected');
|
|
160
|
+
batch.state = BatchState.Acknowledged;
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const batchIndex = consumerWrapper.batches.indexOf(batch);
|
|
164
|
+
if (batchIndex < 0)
|
|
165
|
+
throw this.processError('Internal error: Cannot find batch in the list of batches');
|
|
166
|
+
const strategy = this.options.batchFailureStrategy;
|
|
167
|
+
if (strategy === BatchFailureStrategy.Fail || batch.messages.length <= 1) {
|
|
168
|
+
yield this.handleFailureStrategy(originalChannel, batch, consumerWrapper, batchIndex, queueName);
|
|
169
|
+
}
|
|
170
|
+
else if (strategy === BatchFailureStrategy.Split) {
|
|
171
|
+
yield this.splitBatch(originalChannel, batch, consumerWrapper, batchIndex, callback, queueName);
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
throw this.processError(`Not supported batch failure strategy: ${strategy}`);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
handleFailureStrategy(originalChannel, batch, consumerWrapper, batchIndex, queueName) {
|
|
179
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
180
|
+
switch (this.options.failureStrategy) {
|
|
181
|
+
case ConsumptionFailureStrategy.Drop:
|
|
182
|
+
batch.state = BatchState.Processed;
|
|
183
|
+
debug('batch-processed queue=%s reason=%s', queueName, 'drop-strategy');
|
|
184
|
+
yield this.planMessageAcknowledgment(consumerWrapper, originalChannel, queueName);
|
|
185
|
+
break;
|
|
186
|
+
case ConsumptionFailureStrategy.Requeue:
|
|
187
|
+
yield this.nackMessages(originalChannel, batch, batchIndex, true, queueName);
|
|
188
|
+
break;
|
|
189
|
+
case ConsumptionFailureStrategy.Reject:
|
|
190
|
+
yield this.nackMessages(originalChannel, batch, batchIndex, false, queueName);
|
|
191
|
+
break;
|
|
192
|
+
default:
|
|
193
|
+
throw this.processError(`Not supported failure strategy: ${this.options.failureStrategy}`);
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
nackMessages(originalChannel, batch, batchIndex, requeue, queueName) {
|
|
198
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
199
|
+
if (batchIndex > 0) {
|
|
200
|
+
yield Promise.all(batch.messages.map(msg => originalChannel.nack(msg.rabbitMessage, false, requeue)));
|
|
201
|
+
}
|
|
202
|
+
else if (batchIndex === 0) {
|
|
203
|
+
const lastMessage = last(batch.messages);
|
|
204
|
+
if (!lastMessage)
|
|
205
|
+
throw this.processError('Internal error: Last message in batch not found during nack');
|
|
206
|
+
yield originalChannel.nack(lastMessage.rabbitMessage, true, requeue);
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
throw this.processError('Internal error: Negative batch index during nack');
|
|
210
|
+
}
|
|
211
|
+
debug('batch-acknowledged queue=%s reason=%s requeue=%s', queueName, 'nacked', requeue);
|
|
212
|
+
batch.state = BatchState.Acknowledged;
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
splitBatch(originalChannel, batch, consumerWrapper, batchIndex, callback, queueName) {
|
|
216
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
217
|
+
debug('batch-split queue=%s messages=%d', queueName, batch.messages.length);
|
|
218
|
+
const splitBatches = batch.messages.map(message => ({
|
|
219
|
+
state: BatchState.WaitingForData,
|
|
220
|
+
messages: [message],
|
|
221
|
+
}));
|
|
222
|
+
consumerWrapper.batches.splice(batchIndex, 1, ...splitBatches);
|
|
223
|
+
yield Promise.all(splitBatches.map(batch => this.handleBatch(callback, originalChannel, batch, consumerWrapper, queueName)));
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
removeProcessedBatches(consumerWrapper, queueName) {
|
|
227
|
+
var _a;
|
|
228
|
+
if (!consumerWrapper.isConnected || this.shouldAutoAck) {
|
|
229
|
+
consumerWrapper.batches
|
|
230
|
+
.filter(batch => batch.state === BatchState.Processed || batch.state === BatchState.Acknowledging).forEach(batch => {
|
|
231
|
+
debug('batch-acknowledged queue=%s reason=%s', queueName, 'disconnected');
|
|
232
|
+
batch.state = BatchState.Acknowledged;
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
const indicesOfBatchesToRemove = consumerWrapper.batches
|
|
236
|
+
.flatMap((b, i) => {
|
|
237
|
+
if (b.state === BatchState.Acknowledged)
|
|
238
|
+
return [i];
|
|
239
|
+
return [];
|
|
240
|
+
});
|
|
241
|
+
if (indicesOfBatchesToRemove.length === 0)
|
|
242
|
+
return;
|
|
243
|
+
debug('acknowledged-cleanup queue=%s batches=%d', queueName, indicesOfBatchesToRemove.length);
|
|
244
|
+
for (const index of indicesOfBatchesToRemove.reverse()) {
|
|
245
|
+
const batch = consumerWrapper.batches[index];
|
|
246
|
+
if (!batch)
|
|
247
|
+
throw this.processError('Internal error: Batch for removal not found');
|
|
248
|
+
consumerWrapper.batches.splice(index, 1);
|
|
249
|
+
clearTimeout(batch.confirmTimer);
|
|
250
|
+
batch.confirmTimer = undefined;
|
|
251
|
+
consumerWrapper.messagesInFlight -= batch.messages.length;
|
|
252
|
+
}
|
|
253
|
+
debug('acknowledged-cleaned queue=%s batches=%d in-flight=%d', queueName, indicesOfBatchesToRemove.length, consumerWrapper.messagesInFlight);
|
|
254
|
+
(_a = this.notifyMessageProcessed) === null || _a === void 0 ? void 0 : _a.call(this);
|
|
255
|
+
}
|
|
256
|
+
planMessageAcknowledgment(consumerWrapper, originalChannel, queueName) {
|
|
257
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
258
|
+
var _a;
|
|
259
|
+
if (consumerWrapper.batches.length === 0)
|
|
260
|
+
return;
|
|
261
|
+
if (!consumerWrapper.isConnected || this.shouldAutoAck)
|
|
262
|
+
return;
|
|
263
|
+
const firstUnprocessedIndex = consumerWrapper.batches.findIndex(({ state }) => [BatchState.WaitingForData, BatchState.Processing, BatchState.Failed].includes(state));
|
|
264
|
+
const processedToIndex = firstUnprocessedIndex < 0 ? consumerWrapper.batches.length : firstUnprocessedIndex;
|
|
265
|
+
const batchesToConfirm = consumerWrapper.batches.slice(0, processedToIndex);
|
|
266
|
+
batchesToConfirm.forEach(batch => {
|
|
267
|
+
clearTimeout(batch.confirmTimer);
|
|
268
|
+
batch.confirmTimer = undefined;
|
|
269
|
+
});
|
|
270
|
+
if (batchesToConfirm.length > 0 && ((_a = last(batchesToConfirm)) === null || _a === void 0 ? void 0 : _a.state) === BatchState.Processed) {
|
|
271
|
+
debug('acknowledging-from-head queue=%s batches=%d', queueName, batchesToConfirm.length);
|
|
272
|
+
const lastConfirmBatch = last(batchesToConfirm);
|
|
273
|
+
if (!lastConfirmBatch)
|
|
274
|
+
throw this.processError('Internal Error: Last batch for confirmation not found');
|
|
275
|
+
const lastMessageOfLastConfirmBatch = last(lastConfirmBatch.messages);
|
|
276
|
+
if (!lastMessageOfLastConfirmBatch)
|
|
277
|
+
throw this.processError('Internal Error: Last batch or last message for confirmation not found');
|
|
278
|
+
batchesToConfirm.forEach(batch => {
|
|
279
|
+
if (batch.state === BatchState.Processed)
|
|
280
|
+
batch.state = BatchState.Acknowledging;
|
|
281
|
+
});
|
|
282
|
+
yield originalChannel.ack(lastMessageOfLastConfirmBatch.rabbitMessage, true);
|
|
283
|
+
batchesToConfirm.forEach(batch => {
|
|
284
|
+
debug('batch-acknowledged queue=%s reason=%s', queueName, 'success');
|
|
285
|
+
batch.state = BatchState.Acknowledged;
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
consumerWrapper.batches
|
|
289
|
+
.filter(batch => batch.state === BatchState.Processed && !batch.confirmTimer)
|
|
290
|
+
.forEach(batch => {
|
|
291
|
+
batch.confirmTimer = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
|
|
292
|
+
if (!consumerWrapper.isConnected) {
|
|
293
|
+
debug('batch-acknowledged queue=%s reason=%s', queueName, 'disconnect');
|
|
294
|
+
batch.state = BatchState.Acknowledged;
|
|
295
|
+
}
|
|
296
|
+
if (batch.state !== BatchState.Processed)
|
|
297
|
+
return;
|
|
298
|
+
debug('acknowledging-out-of-order queue=%s', queueName);
|
|
299
|
+
batch.state = BatchState.Acknowledging;
|
|
300
|
+
yield Promise.all(batch.messages.map(({ rabbitMessage }) => originalChannel.ack(rabbitMessage, false)));
|
|
301
|
+
debug('batch-acknowledged queue=%s reason=%s', queueName, 'success');
|
|
302
|
+
batch.state = BatchState.Acknowledged;
|
|
303
|
+
this.removeProcessedBatches(consumerWrapper, queueName);
|
|
304
|
+
}), this.maxWaitTimeForAck);
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
BatchConsumerImplementation.DEFAULT_BATCH_SIZE = 20;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { Queue } from '../queue';
|
|
3
|
+
import { Channel } from '../channel';
|
|
4
|
+
import { BatchConsumerCallbackFn } from './types';
|
|
5
|
+
import { BaseConsumerEventMap } from './base-consumer';
|
|
6
|
+
/**
|
|
7
|
+
* Events emitted by a {@link BatchConsumer}.
|
|
8
|
+
*/
|
|
9
|
+
export type BatchConsumerEventMap = BaseConsumerEventMap & {
|
|
10
|
+
/**
|
|
11
|
+
* Emitted when the message handler or message parsing throws an error.
|
|
12
|
+
*/
|
|
13
|
+
handlingFailed: [error: unknown];
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Represents a service consuming messages from RabbitMQ in batches.
|
|
17
|
+
* The generic type `Message` is the type of each parsed message payload,
|
|
18
|
+
* and `AdditionalProperties` are extra fields that a consumer implementation can add to each message entry in the callback.
|
|
19
|
+
*/
|
|
20
|
+
export interface BatchConsumer<Message, AdditionalProperties = Record<string, unknown>> extends EventEmitter<BatchConsumerEventMap> {
|
|
21
|
+
/**
|
|
22
|
+
* Stops consuming new messages and waits for all in-flight batches to finish processing.
|
|
23
|
+
* @param timeout - Maximum time in milliseconds to wait for in-flight messages to complete. Defaults to 30000.
|
|
24
|
+
*/
|
|
25
|
+
close(timeout?: number): Promise<void>;
|
|
26
|
+
/**
|
|
27
|
+
* Registers the batch handler and starts consuming from the queue.
|
|
28
|
+
* @param callback - Handler invoked with a batch of received messages.
|
|
29
|
+
*/
|
|
30
|
+
listen(callback: BatchConsumerCallbackFn<Message, AdditionalProperties>): Promise<BatchConsumer<Message, AdditionalProperties>>;
|
|
31
|
+
/**
|
|
32
|
+
* The queue this consumer reads from.
|
|
33
|
+
*/
|
|
34
|
+
get queue(): Queue;
|
|
35
|
+
/**
|
|
36
|
+
* The channel used by this consumer.
|
|
37
|
+
*/
|
|
38
|
+
get channel(): Channel;
|
|
39
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Queue } from '../queue';
|
|
2
|
+
import { Channel } from '../channel';
|
|
3
|
+
import { Consumer, ConsumerEventMap } from './consumer';
|
|
4
|
+
import { ConsumerCallbackFn, ConsumerOptions } from './types';
|
|
5
|
+
import { BaseConsumer } from './base-consumer';
|
|
6
|
+
export declare class ConsumerImplementation<Message> extends BaseConsumer<ConsumerCallbackFn<Message>, ConsumerEventMap> implements Consumer<Message> {
|
|
7
|
+
private readonly options;
|
|
8
|
+
constructor(channel: Channel, queue: Queue, options: ConsumerOptions<Message>);
|
|
9
|
+
listen(callback: ConsumerCallbackFn<Message>): Promise<this>;
|
|
10
|
+
private messageReceiver;
|
|
11
|
+
private shouldAcknowledge;
|
|
12
|
+
}
|