amqp-connection-manager 4.1.15 → 5.0.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "amqp-connection-manager",
3
- "version": "4.1.15",
3
+ "version": "5.0.0",
4
4
  "description": "Auto-reconnect and round robin support for amqplib.",
5
5
  "module": "./dist/esm/index.js",
6
6
  "main": "./dist/cjs/index.js",
@@ -1,83 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.InMemoryMessageStore = void 0;
4
- class InMemoryMessageStore {
5
- constructor() {
6
- /** Queued messages, not yet sent. */
7
- this._messages = [];
8
- /** Published, but not yet confirmed messages. */
9
- this._unconfirmedMessages = [];
10
- }
11
- queueMessage(message, timeout) {
12
- if (timeout) {
13
- message.timeout = setTimeout(() => {
14
- let idx = this._messages.indexOf(message);
15
- if (idx !== -1) {
16
- this._messages.splice(idx, 1);
17
- }
18
- else {
19
- idx = this._unconfirmedMessages.indexOf(message);
20
- if (idx !== -1) {
21
- this._unconfirmedMessages.splice(idx, 1);
22
- }
23
- }
24
- message.isTimedout = true;
25
- message.reject(new Error('timeout'));
26
- }, timeout);
27
- }
28
- this._messages.push(message);
29
- }
30
- getMessageToSend() {
31
- return this._messages.shift();
32
- }
33
- queueLength() {
34
- return this._messages.length;
35
- }
36
- messageSent(message) {
37
- this._unconfirmedMessages.push(message);
38
- }
39
- messageSendFailed(message) {
40
- this._removeUnconfirmedMessage(message);
41
- // Tried to write to a closed channel. Put the message back in the queue
42
- // and we'll try again when we reconnect.
43
- // TODO: Are we worried about re-ordering messages here?
44
- this._messages.unshift(message);
45
- }
46
- messageResolved(message, canSend) {
47
- this._removeUnconfirmedMessage(message);
48
- message.resolve(canSend);
49
- }
50
- messageRejected(message, err) {
51
- this._removeUnconfirmedMessage(message);
52
- message.reject(err);
53
- }
54
- rejectAll(err) {
55
- if (this._messages.length !== 0) {
56
- // Reject any unsent messages.
57
- this._messages.forEach((message) => {
58
- if (message.timeout) {
59
- clearTimeout(message.timeout);
60
- }
61
- message.reject(err);
62
- });
63
- }
64
- if (this._unconfirmedMessages.length !== 0) {
65
- // Reject any unconfirmed messages.
66
- this._unconfirmedMessages.forEach((message) => {
67
- if (message.timeout) {
68
- clearTimeout(message.timeout);
69
- }
70
- message.reject(err);
71
- });
72
- }
73
- }
74
- _removeUnconfirmedMessage(message) {
75
- const toRemove = this._unconfirmedMessages.indexOf(message);
76
- if (toRemove === -1) {
77
- throw new Error(`Message is not in _unconfirmedMessages!`);
78
- }
79
- const removed = this._unconfirmedMessages.splice(toRemove, 1);
80
- return removed[0];
81
- }
82
- }
83
- exports.InMemoryMessageStore = InMemoryMessageStore;
@@ -1,184 +0,0 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- /// <reference types="node" />
4
- /// <reference types="node" />
5
- import * as amqp from 'amqplib';
6
- import { EventEmitter } from 'events';
7
- import { TcpSocketConnectOpts } from 'net';
8
- import { ConnectionOptions } from 'tls';
9
- import ChannelWrapper, { CreateChannelOpts } from './ChannelWrapper.js';
10
- export declare type ConnectionUrl = string | amqp.Options.Connect | {
11
- url: string;
12
- connectionOptions?: AmqpConnectionOptions;
13
- };
14
- export interface ConnectListener {
15
- (arg: {
16
- connection: amqp.Connection;
17
- url: string | amqp.Options.Connect;
18
- }): void;
19
- }
20
- export interface ConnectFailedListener {
21
- (arg: {
22
- err: Error;
23
- url: string | amqp.Options.Connect | undefined;
24
- }): void;
25
- }
26
- export declare type AmqpConnectionOptions = (ConnectionOptions | TcpSocketConnectOpts) & {
27
- noDelay?: boolean;
28
- timeout?: number;
29
- keepAlive?: boolean;
30
- keepAliveDelay?: number;
31
- clientProperties?: any;
32
- credentials?: {
33
- mechanism: string;
34
- username: string;
35
- password: string;
36
- response: () => Buffer;
37
- } | {
38
- mechanism: string;
39
- response: () => Buffer;
40
- } | undefined;
41
- };
42
- export interface AmqpConnectionManagerOptions {
43
- /** Interval to send heartbeats to broker. Defaults to 5 seconds. */
44
- heartbeatIntervalInSeconds?: number;
45
- /**
46
- * The time to wait before trying to reconnect. If not specified, defaults
47
- * to `heartbeatIntervalInSeconds`.
48
- */
49
- reconnectTimeInSeconds?: number | undefined;
50
- /**
51
- * `findServers` is a function that which returns one or more servers to
52
- * connect to. This should return either a single URL or an array of URLs.
53
- * This is handy when you're using a service discovery mechanism such as
54
- * Consul or etcd. Instead of taking a callback, this can also return a
55
- * Promise. Note that if this is supplied, then `urls` is ignored.
56
- */
57
- findServers?: ((callback: (urls: ConnectionUrl | ConnectionUrl[]) => void) => void) | (() => Promise<ConnectionUrl | ConnectionUrl[]>) | undefined;
58
- /** Connection options, passed as options to the amqplib.connect() method. */
59
- connectionOptions?: AmqpConnectionOptions;
60
- }
61
- export interface IAmqpConnectionManager {
62
- connectionOptions?: AmqpConnectionOptions;
63
- heartbeatIntervalInSeconds: number;
64
- reconnectTimeInSeconds: number;
65
- addListener(event: string, listener: (...args: any[]) => void): this;
66
- addListener(event: 'connect', listener: ConnectListener): this;
67
- addListener(event: 'connectFailed', listener: ConnectFailedListener): this;
68
- addListener(event: 'blocked', listener: (arg: {
69
- reason: string;
70
- }) => void): this;
71
- addListener(event: 'unblocked', listener: () => void): this;
72
- addListener(event: 'disconnect', listener: (arg: {
73
- err: Error;
74
- }) => void): this;
75
- listeners(eventName: string | symbol): Function[];
76
- on(event: string, listener: (...args: any[]) => void): this;
77
- on(event: 'connect', listener: ConnectListener): this;
78
- on(event: 'connectFailed', listener: ConnectFailedListener): this;
79
- on(event: 'blocked', listener: (arg: {
80
- reason: string;
81
- }) => void): this;
82
- on(event: 'unblocked', listener: () => void): this;
83
- on(event: 'disconnect', listener: (arg: {
84
- err: Error;
85
- }) => void): this;
86
- once(event: string, listener: (...args: any[]) => void): this;
87
- once(event: 'connect', listener: ConnectListener): this;
88
- once(event: 'connectFailed', listener: ConnectFailedListener): this;
89
- once(event: 'blocked', listener: (arg: {
90
- reason: string;
91
- }) => void): this;
92
- once(event: 'unblocked', listener: () => void): this;
93
- once(event: 'disconnect', listener: (arg: {
94
- err: Error;
95
- }) => void): this;
96
- prependListener(event: string, listener: (...args: any[]) => void): this;
97
- prependListener(event: 'connect', listener: ConnectListener): this;
98
- prependListener(event: 'connectFailed', listener: ConnectFailedListener): this;
99
- prependListener(event: 'blocked', listener: (arg: {
100
- reason: string;
101
- }) => void): this;
102
- prependListener(event: 'unblocked', listener: () => void): this;
103
- prependListener(event: 'disconnect', listener: (arg: {
104
- err: Error;
105
- }) => void): this;
106
- prependOnceListener(event: string, listener: (...args: any[]) => void): this;
107
- prependOnceListener(event: 'connect', listener: ConnectListener): this;
108
- prependOnceListener(event: 'connectFailed', listener: ConnectFailedListener): this;
109
- prependOnceListener(event: 'blocked', listener: (arg: {
110
- reason: string;
111
- }) => void): this;
112
- prependOnceListener(event: 'unblocked', listener: () => void): this;
113
- prependOnceListener(event: 'disconnect', listener: (arg: {
114
- err: Error;
115
- }) => void): this;
116
- removeListener(event: string, listener: (...args: any[]) => void): this;
117
- connect(options?: {
118
- timeout?: number;
119
- }): Promise<void>;
120
- reconnect(): void;
121
- createChannel(options?: CreateChannelOpts): ChannelWrapper;
122
- close(): Promise<void>;
123
- isConnected(): boolean;
124
- /** The current connection. */
125
- readonly connection: amqp.Connection | undefined;
126
- /** Returns the number of registered channels. */
127
- readonly channelCount: number;
128
- }
129
- export default class AmqpConnectionManager extends EventEmitter implements IAmqpConnectionManager {
130
- private _channels;
131
- private _currentUrl;
132
- private _closed;
133
- private _cancelRetriesHandler?;
134
- private _connectPromise?;
135
- private _currentConnection?;
136
- private _findServers;
137
- private _urls?;
138
- connectionOptions: AmqpConnectionOptions | undefined;
139
- heartbeatIntervalInSeconds: number;
140
- reconnectTimeInSeconds: number;
141
- /**
142
- * Create a new AmqplibConnectionManager.
143
- *
144
- * @param urls - An array of brokers to connect to.
145
- * Takes url strings or objects {url: string, connectionOptions?: object}
146
- * If present, a broker's [connectionOptions] will be used instead
147
- * of [options.connectionOptions] when passed to the amqplib connect method.
148
- * AmqplibConnectionManager will round-robin between them whenever it
149
- * needs to create a new connection.
150
- * @param [options={}] -
151
- * @param [options.heartbeatIntervalInSeconds=5] - The interval,
152
- * in seconds, to send heartbeats.
153
- * @param [options.reconnectTimeInSeconds] - The time to wait
154
- * before trying to reconnect. If not specified, defaults to
155
- * `heartbeatIntervalInSeconds`.
156
- * @param [options.connectionOptions] - Passed to the amqplib
157
- * connect method.
158
- * @param [options.findServers] - A `fn(callback)` or a `fn()`
159
- * which returns a Promise. This should resolve to one or more servers
160
- * to connect to, either a single URL or an array of URLs. This is handy
161
- * when you're using a service discovery mechanism such as Consul or etcd.
162
- * Note that if this is supplied, then `urls` is ignored.
163
- */
164
- constructor(urls: ConnectionUrl | ConnectionUrl[] | undefined | null, options?: AmqpConnectionManagerOptions);
165
- /**
166
- * Start the connect retries and await the first connect result. Even if the initial connect fails or timeouts, the
167
- * reconnect attempts will continue in the background.
168
- * @param [options={}] -
169
- * @param [options.timeout] - Time to wait for initial connect
170
- */
171
- connect({ timeout }?: {
172
- timeout?: number;
173
- }): Promise<void>;
174
- createChannel(options?: CreateChannelOpts): ChannelWrapper;
175
- close(): Promise<void>;
176
- isConnected(): boolean;
177
- /** Force reconnect - noop unless connected */
178
- reconnect(): void;
179
- /** The current connection. */
180
- get connection(): amqp.Connection | undefined;
181
- /** Returns the number of registered channels. */
182
- get channelCount(): number;
183
- private _connect;
184
- }
@@ -1,249 +0,0 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- import type * as amqplib from 'amqplib';
4
- import { Options } from 'amqplib';
5
- import { EventEmitter } from 'events';
6
- import pb from 'promise-breaker';
7
- import { IAmqpConnectionManager } from './AmqpConnectionManager.js';
8
- export declare type Channel = amqplib.ConfirmChannel | amqplib.Channel;
9
- export declare type SetupFunc = ((channel: Channel, callback: (error?: Error) => void) => void) | ((channel: Channel) => Promise<void>) | ((channel: amqplib.ConfirmChannel, callback: (error?: Error) => void) => void) | ((channel: amqplib.ConfirmChannel) => Promise<void>);
10
- export interface CreateChannelOpts {
11
- /** Name for this channel. Used for debugging. */
12
- name?: string;
13
- /**
14
- * A function to call whenever we reconnect to the broker (and therefore create a new underlying channel.)
15
- * This function should either accept a callback, or return a Promise. See addSetup below
16
- */
17
- setup?: SetupFunc;
18
- /**
19
- * True to create a ConfirmChannel (default). False to create a regular Channel.
20
- */
21
- confirm?: boolean;
22
- /**
23
- * if true, then ChannelWrapper assumes all messages passed to publish() and sendToQueue() are plain JSON objects.
24
- * These will be encoded automatically before being sent.
25
- */
26
- json?: boolean;
27
- /**
28
- * Default publish timeout in ms. Messages not published within the given time are rejected with a timeout error.
29
- */
30
- publishTimeout?: number;
31
- }
32
- export interface PublishOptions extends Options.Publish {
33
- /** Message will be rejected after timeout ms */
34
- timeout?: number;
35
- }
36
- interface ConsumerOptions extends amqplib.Options.Consume {
37
- prefetch?: number;
38
- }
39
- interface Consumer {
40
- consumerTag: string | null;
41
- queue: string;
42
- onMessage: (msg: amqplib.ConsumeMessage) => void;
43
- options: ConsumerOptions;
44
- }
45
- /**
46
- * Calls to `publish()` or `sendToQueue()` work just like in amqplib, but messages are queued internally and
47
- * are guaranteed to be delivered. If the underlying connection drops, ChannelWrapper will wait for a new
48
- * connection and continue.
49
- *
50
- * Events:
51
- * * `connect` - emitted every time this channel connects or reconnects.
52
- * * `error(err, {name})` - emitted if an error occurs setting up the channel.
53
- * * `drop({message, err})` - called when a JSON message was dropped because it could not be encoded.
54
- * * `close` - emitted when this channel closes via a call to `close()`
55
- *
56
- */
57
- export default class ChannelWrapper extends EventEmitter {
58
- private _connectionManager;
59
- private _json;
60
- /** If we're in the process of creating a channel, this is a Promise which
61
- * will resolve when the channel is set up. Otherwise, this is `null`.
62
- */
63
- private _settingUp;
64
- private _setups;
65
- /** Queued messages, not yet sent. */
66
- private _messages;
67
- /** Oublished, but not yet confirmed messages. */
68
- private _unconfirmedMessages;
69
- /** Reason code during publish or sendtoqueue messages. */
70
- private _irrecoverableCode;
71
- /** Consumers which will be reconnected on channel errors etc. */
72
- private _consumers;
73
- /**
74
- * The currently connected channel. Note that not all setup functions
75
- * have been run on this channel until `@_settingUp` is either null or
76
- * resolved.
77
- */
78
- private _channel?;
79
- /**
80
- * True to create a ConfirmChannel. False to create a regular Channel.
81
- */
82
- private _confirm;
83
- /**
84
- * True if the "worker" is busy sending messages. False if we need to
85
- * start the worker to get stuff done.
86
- */
87
- private _working;
88
- /**
89
- * We kill off workers when we disconnect. Whenever we start a new
90
- * worker, we bump up the `_workerNumber` - this makes it so if stale
91
- * workers ever do wake up, they'll know to stop working.
92
- */
93
- private _workerNumber;
94
- /**
95
- * True if the underlying channel has room for more messages.
96
- */
97
- private _channelHasRoom;
98
- /**
99
- * Default publish timeout
100
- */
101
- private _publishTimeout?;
102
- name?: string;
103
- addListener(event: string, listener: (...args: any[]) => void): this;
104
- addListener(event: 'connect', listener: () => void): this;
105
- addListener(event: 'error', listener: (err: Error, info: {
106
- name: string;
107
- }) => void): this;
108
- addListener(event: 'close', listener: () => void): this;
109
- on(event: string, listener: (...args: any[]) => void): this;
110
- on(event: 'connect', listener: () => void): this;
111
- on(event: 'error', listener: (err: Error, info: {
112
- name: string;
113
- }) => void): this;
114
- on(event: 'close', listener: () => void): this;
115
- once(event: string, listener: (...args: any[]) => void): this;
116
- once(event: 'connect', listener: () => void): this;
117
- once(event: 'error', listener: (err: Error, info: {
118
- name: string;
119
- }) => void): this;
120
- once(event: 'close', listener: () => void): this;
121
- prependListener(event: string, listener: (...args: any[]) => void): this;
122
- prependListener(event: 'connect', listener: () => void): this;
123
- prependListener(event: 'error', listener: (err: Error, info: {
124
- name: string;
125
- }) => void): this;
126
- prependListener(event: 'close', listener: () => void): this;
127
- prependOnceListener(event: string, listener: (...args: any[]) => void): this;
128
- prependOnceListener(event: 'connect', listener: () => void): this;
129
- prependOnceListener(event: 'error', listener: (err: Error, info: {
130
- name: string;
131
- }) => void): this;
132
- prependOnceListener(event: 'close', listener: () => void): this;
133
- /**
134
- * Adds a new 'setup handler'.
135
- *
136
- * `setup(channel, [cb])` is a function to call when a new underlying channel is created - handy for asserting
137
- * exchanges and queues exists, and whatnot. The `channel` object here is a ConfigChannel from amqplib.
138
- * The `setup` function should return a Promise (or optionally take a callback) - no messages will be sent until
139
- * this Promise resolves.
140
- *
141
- * If there is a connection, `setup()` will be run immediately, and the addSetup Promise/callback won't resolve
142
- * until `setup` is complete. Note that in this case, if the setup throws an error, no 'error' event will
143
- * be emitted, since you can just handle the error here (although the `setup` will still be added for future
144
- * reconnects, even if it throws an error.)
145
- *
146
- * Setup functions should, ideally, not throw errors, but if they do then the ChannelWrapper will emit an 'error'
147
- * event.
148
- *
149
- * @param setup - setup function.
150
- * @param [done] - callback.
151
- * @returns - Resolves when complete.
152
- */
153
- addSetup(setup: SetupFunc, done?: pb.Callback<void>): Promise<void>;
154
- /**
155
- * Remove a setup function added with `addSetup`. If there is currently a
156
- * connection, `teardown(channel, [cb])` will be run immediately, and the
157
- * returned Promise will not resolve until it completes.
158
- *
159
- * @param {function} setup - the setup function to remove.
160
- * @param {function} [teardown] - `function(channel, [cb])` to run to tear
161
- * down the channel.
162
- * @param {function} [done] - Optional callback.
163
- * @returns {void | Promise} - Resolves when complete.
164
- */
165
- removeSetup(setup: SetupFunc, teardown?: SetupFunc, done?: pb.Callback<void>): Promise<void>;
166
- /**
167
- * Returns a Promise which resolves when this channel next connects.
168
- * (Mainly here for unit testing...)
169
- *
170
- * @param [done] - Optional callback.
171
- * @returns - Resolves when connected.
172
- */
173
- waitForConnect(done?: pb.Callback<void>): Promise<void>;
174
- publish(exchange: string, routingKey: string, content: Buffer | string | unknown, options?: PublishOptions, done?: pb.Callback<boolean>): Promise<boolean>;
175
- sendToQueue(queue: string, content: Buffer | string | unknown, options?: PublishOptions, done?: pb.Callback<boolean>): Promise<boolean>;
176
- private _enqueueMessage;
177
- /**
178
- * Create a new ChannelWrapper.
179
- *
180
- * @param connectionManager - connection manager which
181
- * created this channel.
182
- * @param [options] -
183
- * @param [options.name] - A name for this channel. Handy for debugging.
184
- * @param [options.setup] - A default setup function to call. See
185
- * `addSetup` for details.
186
- * @param [options.json] - if true, then ChannelWrapper assumes all
187
- * messages passed to `publish()` and `sendToQueue()` are plain JSON objects.
188
- * These will be encoded automatically before being sent.
189
- *
190
- */
191
- constructor(connectionManager: IAmqpConnectionManager, options?: CreateChannelOpts);
192
- private _onConnect;
193
- private _onChannelClose;
194
- /** Called whenever the channel drains. */
195
- private _onChannelDrain;
196
- private _onDisconnect;
197
- queueLength(): number;
198
- close(): Promise<void>;
199
- private _shouldPublish;
200
- private _startWorker;
201
- private _canWaitReconnection;
202
- private _messageResolved;
203
- private _messageRejected;
204
- private _getEncodedMessage;
205
- private _publishQueuedMessages;
206
- /**
207
- * Setup a consumer
208
- * This consumer will be reconnected on cancellation and channel errors.
209
- */
210
- consume(queue: string, onMessage: Consumer['onMessage'], options?: ConsumerOptions): Promise<amqplib.Replies.Consume>;
211
- private _consume;
212
- private _reconnectConsumer;
213
- /**
214
- * Cancel all consumers
215
- */
216
- cancelAll(): Promise<void>;
217
- cancel(consumerTag: string): Promise<void>;
218
- /** Send an `ack` to the underlying channel. */
219
- ack(message: amqplib.Message, allUpTo?: boolean): void;
220
- /** Send an `ackAll` to the underlying channel. */
221
- ackAll(): void;
222
- /** Send a `nack` to the underlying channel. */
223
- nack(message: amqplib.Message, allUpTo?: boolean, requeue?: boolean): void;
224
- /** Send a `nackAll` to the underlying channel. */
225
- nackAll(requeue?: boolean): void;
226
- /** Send a `purgeQueue` to the underlying channel. */
227
- purgeQueue(queue: string): Promise<amqplib.Replies.PurgeQueue>;
228
- /** Send a `checkQueue` to the underlying channel. */
229
- checkQueue(queue: string): Promise<amqplib.Replies.AssertQueue>;
230
- /** Send a `assertQueue` to the underlying channel. */
231
- assertQueue(queue: string, options?: amqplib.Options.AssertQueue): Promise<amqplib.Replies.AssertQueue>;
232
- /** Send a `bindQueue` to the underlying channel. */
233
- bindQueue(queue: string, source: string, pattern: string, args?: any): Promise<void>;
234
- /** Send a `deleteQueue` to the underlying channel. */
235
- deleteQueue(queue: string, options?: Options.DeleteQueue): Promise<amqplib.Replies.DeleteQueue>;
236
- /** Send a `assertExchange` to the underlying channel. */
237
- assertExchange(exchange: string, type: 'direct' | 'topic' | 'headers' | 'fanout' | 'match' | string, options?: Options.AssertExchange): Promise<amqplib.Replies.AssertExchange>;
238
- /** Send a `bindExchange` to the underlying channel. */
239
- bindExchange(destination: string, source: string, pattern: string, args?: any): Promise<amqplib.Replies.Empty>;
240
- /** Send a `checkExchange` to the underlying channel. */
241
- checkExchange(exchange: string): Promise<amqplib.Replies.Empty>;
242
- /** Send a `deleteExchange` to the underlying channel. */
243
- deleteExchange(exchange: string, options?: Options.DeleteExchange): Promise<amqplib.Replies.Empty>;
244
- /** Send a `unbindExchange` to the underlying channel. */
245
- unbindExchange(destination: string, source: string, pattern: string, args?: any): Promise<amqplib.Replies.Empty>;
246
- /** Send a `get` to the underlying channel. */
247
- get(queue: string, options?: Options.Get): Promise<amqplib.GetMessage | false>;
248
- }
249
- export {};
@@ -1,71 +0,0 @@
1
- /// <reference types="node" />
2
- import type * as amqplib from 'amqplib';
3
- export interface PublishMessage {
4
- type: 'publish';
5
- exchange: string;
6
- routingKey: string;
7
- content: Buffer;
8
- options?: amqplib.Options.Publish;
9
- resolve: (result: boolean) => void;
10
- reject: (err: Error) => void;
11
- timeout?: NodeJS.Timeout;
12
- isTimedout: boolean;
13
- }
14
- export interface SendToQueueMessage {
15
- type: 'sendToQueue';
16
- queue: string;
17
- content: Buffer;
18
- options?: amqplib.Options.Publish;
19
- resolve: (result: boolean) => void;
20
- reject: (err: Error) => void;
21
- timeout?: NodeJS.Timeout;
22
- isTimedout: boolean;
23
- }
24
- export declare type Message = PublishMessage | SendToQueueMessage;
25
- export interface MessageStore {
26
- /**
27
- * This is called before a message is sent, to queue the message.
28
- */
29
- queueMessage(message: Message, timeout?: number): void;
30
- /**
31
- * Return the next message to send (the oldest queued message).
32
- */
33
- getMessageToSend(): Message | undefined;
34
- /** Returns the number of unsent messages queued in this MessageStore. */
35
- queueLength(): number;
36
- /**
37
- * This is called after a message is sent, to mark the message as unconfirmed.
38
- */
39
- messageSent(message: Message): void;
40
- /**
41
- * Called when a message failed to send because the connection was temporarily lost.
42
- */
43
- messageSendFailed(message: Message): void;
44
- /**
45
- * This is called after a message is confirmed, to remove the message from the store.
46
- */
47
- messageResolved(message: Message, canSend: boolean): void;
48
- /**
49
- * Called when a message has failed and cannot be sent.
50
- */
51
- messageRejected(message: Message, err: Error): void;
52
- /**
53
- * Called when the channel is closed, to reject any unsent/unconfirmed messages.
54
- */
55
- rejectAll(err: Error): void;
56
- }
57
- export declare class InMemoryMessageStore implements MessageStore {
58
- /** Queued messages, not yet sent. */
59
- private _messages;
60
- /** Published, but not yet confirmed messages. */
61
- private _unconfirmedMessages;
62
- queueMessage(message: Message, timeout?: number): void;
63
- getMessageToSend(): Message | undefined;
64
- queueLength(): number;
65
- messageSent(message: Message): void;
66
- messageSendFailed(message: Message): void;
67
- messageResolved(message: Message, canSend: boolean): void;
68
- messageRejected(message: Message, err: Error): void;
69
- rejectAll(err: Error): void;
70
- private _removeUnconfirmedMessage;
71
- }
@@ -1,80 +0,0 @@
1
- export class InMemoryMessageStore {
2
- constructor() {
3
- /** Queued messages, not yet sent. */
4
- this._messages = [];
5
- /** Published, but not yet confirmed messages. */
6
- this._unconfirmedMessages = [];
7
- }
8
- queueMessage(message, timeout) {
9
- if (timeout) {
10
- message.timeout = setTimeout(() => {
11
- let idx = this._messages.indexOf(message);
12
- if (idx !== -1) {
13
- this._messages.splice(idx, 1);
14
- }
15
- else {
16
- idx = this._unconfirmedMessages.indexOf(message);
17
- if (idx !== -1) {
18
- this._unconfirmedMessages.splice(idx, 1);
19
- }
20
- }
21
- message.isTimedout = true;
22
- message.reject(new Error('timeout'));
23
- }, timeout);
24
- }
25
- this._messages.push(message);
26
- }
27
- getMessageToSend() {
28
- return this._messages.shift();
29
- }
30
- queueLength() {
31
- return this._messages.length;
32
- }
33
- messageSent(message) {
34
- this._unconfirmedMessages.push(message);
35
- }
36
- messageSendFailed(message) {
37
- this._removeUnconfirmedMessage(message);
38
- // Tried to write to a closed channel. Put the message back in the queue
39
- // and we'll try again when we reconnect.
40
- // TODO: Are we worried about re-ordering messages here?
41
- this._messages.unshift(message);
42
- }
43
- messageResolved(message, canSend) {
44
- this._removeUnconfirmedMessage(message);
45
- message.resolve(canSend);
46
- }
47
- messageRejected(message, err) {
48
- this._removeUnconfirmedMessage(message);
49
- message.reject(err);
50
- }
51
- rejectAll(err) {
52
- if (this._messages.length !== 0) {
53
- // Reject any unsent messages.
54
- this._messages.forEach((message) => {
55
- if (message.timeout) {
56
- clearTimeout(message.timeout);
57
- }
58
- message.reject(err);
59
- });
60
- }
61
- if (this._unconfirmedMessages.length !== 0) {
62
- // Reject any unconfirmed messages.
63
- this._unconfirmedMessages.forEach((message) => {
64
- if (message.timeout) {
65
- clearTimeout(message.timeout);
66
- }
67
- message.reject(err);
68
- });
69
- }
70
- }
71
- _removeUnconfirmedMessage(message) {
72
- const toRemove = this._unconfirmedMessages.indexOf(message);
73
- if (toRemove === -1) {
74
- throw new Error(`Message is not in _unconfirmedMessages!`);
75
- }
76
- const removed = this._unconfirmedMessages.splice(toRemove, 1);
77
- return removed[0];
78
- }
79
- }
80
- //# sourceMappingURL=MessageStore.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"MessageStore.js","sourceRoot":"","sources":["../../src/MessageStore.ts"],"names":[],"mappings":"AAmEA,MAAM,OAAO,oBAAoB;IAAjC;QACI,qCAAqC;QAC7B,cAAS,GAAc,EAAE,CAAC;QAClC,iDAAiD;QACzC,yBAAoB,GAAc,EAAE,CAAC;IAgFjD,CAAC;IA9EG,YAAY,CAAC,OAAgB,EAAE,OAAgB;QAC3C,IAAI,OAAO,EAAE;YACT,OAAO,CAAC,OAAO,GAAG,UAAU,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
- export declare function wait(timeInMs: number): {
2
- promise: Promise<void>;
3
- cancel: () => void;
4
- };
@@ -1,21 +0,0 @@
1
- import AmqpConnectionManager, { AmqpConnectionManagerOptions, ConnectionUrl, IAmqpConnectionManager } from './AmqpConnectionManager.js';
2
- import { PublishOptions } from './ChannelWrapper.js';
3
- export type { AmqpConnectionManagerOptions, ConnectionUrl, IAmqpConnectionManager as AmqpConnectionManager, } from './AmqpConnectionManager.js';
4
- export type { CreateChannelOpts, default as ChannelWrapper, SetupFunc, Channel, } from './ChannelWrapper.js';
5
- import { Options as AmqpLibOptions } from 'amqplib';
6
- export declare namespace Options {
7
- type Connect = AmqpLibOptions.Connect;
8
- type AssertQueue = AmqpLibOptions.AssertQueue;
9
- type DeleteQueue = AmqpLibOptions.DeleteQueue;
10
- type AssertExchange = AmqpLibOptions.AssertExchange;
11
- type DeleteExchange = AmqpLibOptions.DeleteExchange;
12
- type Publish = PublishOptions;
13
- type Consume = AmqpLibOptions.Consume;
14
- type Get = AmqpLibOptions.Get;
15
- }
16
- export declare function connect(urls: ConnectionUrl | ConnectionUrl[] | undefined | null, options?: AmqpConnectionManagerOptions): IAmqpConnectionManager;
17
- export { AmqpConnectionManager as AmqpConnectionManagerClass };
18
- declare const amqp: {
19
- connect: typeof connect;
20
- };
21
- export default amqp;