diff --git a/README.md b/README.md index 2f5f01e..ba2402c 100644 --- a/README.md +++ b/README.md @@ -32,12 +32,14 @@ const rabbit = new Rabbit(process.env.RABBIT_URL || 'amqp://localhost', { prefix: '', //prefix all queues with an application name tolerateQueueTypeMismatch: false, //consume an existing queue whose type or priority differs from the declared one (see Queue Type Behavior) cancelConsumersOnSigterm: true, //cancel every consumer when the process receives SIGTERM (see Shutdown) + resubscribeOnReconnect: true, //bind the queues to the new channel and subscribe them again after a reconnect (see the changelog); set to false to create them again yourself on 'connected' socketOptions: {} // socketOptions will be passed as a second param to amqp.connect and from ther to the socket library (net or tls) }); rabbit.on('connected', () => { - //create queues, add halders etc. //this will be called on every reconnection too + //queues created before the reconnect are bound to the new channel and subscribed again before this fires, + //so you don't need to create them again here (doing so is safe: it replaces the consumer, it doesn't add one) }); rabbit.on('disconnected', (err = new Error('Rabbitmq Disconnected')) => { @@ -292,6 +294,10 @@ const rabbit = new Rabbit(process.env.RABBIT_URL, { cancelConsumersOnSigterm: fa ### Changelog +### New in v5.13.x + +- A reconnect subscribes the queues again on its own. Before, every consumer stayed gone after a reconnect unless the `connected` handler created the queues again, so a process that didn't kept running and reported healthy with no consumers. The new consume channel gets each queue back (declared again, bindings added again, handler subscribed with the queue's own prefetch) before `connected` is emitted. A queue that fails to subscribe is retried like a consumer the broker cancelled. Creating a queue with a handler for a name that already has one on the same channel cancels the old consumer first, so a `connected` handler that creates the queues again doesn't leave two. Pass `resubscribeOnReconnect: false` to turn it off and manage the queues yourself on `connected`, as before. + ### New in v5.12.x - A consumer the broker cancels, e.g. because its queue was deleted, subscribes again once the queue exists again, with the queue's own prefetch. Before, it stayed cancelled until the process restarted or reconnected. `destroyQueue` now unsubscribes the queue before deleting it. diff --git a/test/rabbit.test.ts b/test/rabbit.test.ts index 8dfe0dc..c08af38 100644 --- a/test/rabbit.test.ts +++ b/test/rabbit.test.ts @@ -667,6 +667,160 @@ describe('Test rabbit class', function() { (await consumerCount()).should.equal(1); }); + describe('when the app does not create its queues again on "connected"', function() { + function reconnectOnDisconnect() { + rabbit.on('disconnected', () => setTimeout(() => rabbit.reconnect(), 10)); + } + + async function dropConnections(connections: amqp.ChannelModel[]) { + const reconnected = new Promise(resolve => rabbit.once('connected', resolve)); + await Promise.all(connections.map(connection => connection.close())); + await reconnected; + } + + it('should subscribe again after both connections drop', async function() { + const received = []; + rabbit = new Rabbit(this.url, { replyPattern: false }); + reconnectOnDisconnect(); + await rabbit.createQueue(queueName, {}, (msg, ack) => { + received.push(msg.content.toString()); + ack(); + }); + await waitForConsumers(1); + + await dropConnections([rabbit.consumeConnection, rabbit.publishConnection]); + await waitForConsumers(1); + await rabbit.publish(queueName, 'after'); + + for (let i = 0; i < 50 && !received.length; i++) { + await new Promise(r => setTimeout(r, 20)); + } + received.should.have.length(1); + received[0].should.containEql('after'); + }); + + it('should leave the queues alone when resubscribeOnReconnect is false', async function() { + rabbit = new Rabbit(this.url, { replyPattern: false, resubscribeOnReconnect: false }); + reconnectOnDisconnect(); + await rabbit.createQueue(queueName, {}, (msg, ack) => ack()); + await waitForConsumers(1); + + await dropConnections([rabbit.consumeConnection]); + await new Promise(r => setTimeout(r, 200)); + + (await consumerCount()).should.equal(0); + }); + + it('should still create the queues again on "connected" when resubscribeOnReconnect is false', async function() { + rabbit = new Rabbit(this.url, { replyPattern: false, resubscribeOnReconnect: false }); + resubscribeOnReconnect(); + await rabbit.connected; + await waitForConsumers(1); + + await dropConnections([rabbit.consumeConnection]); + await waitForConsumers(1); + await new Promise(r => setTimeout(r, 200)); + + (await consumerCount()).should.equal(1); + }); + + it('should subscribe again when only the consume connection drops', async function() { + rabbit = new Rabbit(this.url, { replyPattern: false }); + reconnectOnDisconnect(); + await rabbit.createQueue(queueName, {}, (msg, ack) => ack()); + await waitForConsumers(1); + + await dropConnections([rabbit.consumeConnection]); + await waitForConsumers(1); + }); + + it('should keep working through repeated reconnects without leaving extra consumers', async function() { + rabbit = new Rabbit(this.url, { replyPattern: false }); + reconnectOnDisconnect(); + await rabbit.createQueue(queueName, {}, (msg, ack) => ack()); + + for (let i = 0; i < 3; i++) { + await dropConnections([rabbit.consumeConnection]); + await waitForConsumers(1); + } + await new Promise(r => setTimeout(r, 200)); + (await consumerCount()).should.equal(1); + }); + + it('should subscribe again with the queue\'s own prefetch', async function() { + rabbit = new Rabbit(this.url, { replyPattern: false, prefetch: 1 }); + reconnectOnDisconnect(); + const queue = await rabbit.createQueue(queueName, { prefetch: 7 }, (msg, ack) => ack()); + const prefetch = sandbox.spy(AmqpChannel.prototype, 'prefetch'); + await dropConnections([rabbit.consumeConnection]); + await waitForConsumers(1); + + queue.channel.should.equal(rabbit.consumeChannel); + prefetch.calledWith(7).should.be.true(); + }); + + it('should not subscribe a queue that was unsubscribed', async function() { + rabbit = new Rabbit(this.url, { replyPattern: false }); + reconnectOnDisconnect(); + await rabbit.createQueue(queueName, {}, (msg, ack) => ack()); + await rabbit.unsubscribe(queueName); + await waitForConsumers(0); + + await dropConnections([rabbit.consumeConnection]); + await new Promise(r => setTimeout(r, 200)); + + (await consumerCount()).should.equal(0); + }); + + it('should bind a queue to its exchange again when the queue is gone with the connection', async function() { + const exclusive = `${queueName}_exclusive`; + const received = []; + rabbit = new Rabbit(this.url, { replyPattern: false }); + reconnectOnDisconnect(); + await rabbit.createQueue(exclusive, { exclusive: true, durable: false }, (msg, ack) => { + received.push(msg.content.toString()); + ack(); + }); + await rabbit.bindToTopic(exclusive, `${exclusive}.topic`); + + await dropConnections([rabbit.consumeConnection]); + await rabbit.publishTopic(`${exclusive}.topic`, 'after'); + + for (let i = 0; i < 50 && !received.length; i++) { + await new Promise(r => setTimeout(r, 20)); + } + received.should.have.length(1); + }); + + it('should emit "connected" only after the consumers are back', async function() { + rabbit = new Rabbit(this.url, { replyPattern: false }); + reconnectOnDisconnect(); + await rabbit.createQueue(queueName, {}, (msg, ack) => ack()); + await waitForConsumers(1); + + const countOnConnected = new Promise(resolve => rabbit.once('connected', () => resolve(consumerCount()))); + await rabbit.consumeConnection.close(); + + (await countOnConnected).should.equal(1); + }); + + it('should subscribe again once the queue exists if rebinding the consumer fails', async function() { + this.timeout(8000); + rabbit = new Rabbit(this.url, { replyPattern: false }); + reconnectOnDisconnect(); + const queue = await rabbit.createQueue(queueName, {}, (msg, ack) => ack()); + await waitForConsumers(1); + const subscribe = sandbox.stub(Queue.prototype, 'subscribe'); + subscribe.onFirstCall().rejects(new Error('consume failed')); + subscribe.callThrough(); + + await dropConnections([rabbit.consumeConnection]); + await waitForConsumers(1, 200); + + queue.subscribed.should.be.true(); + }); + }); + describe('when the broker cancels a consumer because its queue was deleted', function() { this.timeout(10000); diff --git a/ts/queue.ts b/ts/queue.ts index 7ff557e..61acd7e 100644 --- a/ts/queue.ts +++ b/ts/queue.ts @@ -62,7 +62,7 @@ async function withDeclareChannel(channel: Channel, queueName: string, declar } } -export type QueueOptions = amqp.Options.AssertQueue & amqp.Options.Consume & { tolerateQueueTypeMismatch?: boolean }; +export type QueueOptions = amqp.Options.AssertQueue & amqp.Options.Consume & { tolerateQueueTypeMismatch?: boolean; prefetch?: number }; export default class Queue { static STOP_PROPAGATION = { stopPropagation: true }; @@ -78,6 +78,7 @@ export default class Queue { public created: Promise; public handler: Function; public onCancel?: () => void; + public bindings = new Map(); private tag: amqp.Replies.Consume; constructor(public channel: Channel, public name: string, options: QueueOptions) { @@ -156,6 +157,28 @@ export default class Queue { return !!this.tag; } + // Moves the queue to a new channel after a reconnect: the old channel took its consumer with it. The handler is kept, + // so the caller subscribes again. Declares the queue and its bindings again because a non-durable, exclusive or + // auto-delete queue doesn't survive the connection. + async rebind(channel: Channel) { + this.channel = channel; + this.tag = null; + this.created = this.create(); + await this.created; + for (const { exchange, routingKey } of this.bindings.values()) { + await Queue.bindToExchange(exchange, routingKey, channel, this.name, this); + } + } + + trackBinding(exchange: string, routingKey: string, bound: boolean) { + const key = `${exchange}\u0000${routingKey}`; + if (bound) { + this.bindings.set(key, { exchange, routingKey }); + } else { + this.bindings.delete(key); + } + } + // Resolves to whether the consumer is running: an unsubscribe or a broker cancel can land before the consume resolves. async subscribe(handler: (msg: any, ack: (error?, reply?) => any) => any) { // Before any await, so the check after the consume also catches an unsubscribe while the queue is being created. @@ -337,6 +360,7 @@ export default class Queue { await queue.created; } await withDeclareChannel(channel, name, declareChannel => declareChannel.bindQueue(name, exchange, routingKey)); + queue?.trackBinding(exchange, routingKey, true); logger.debug(`created binding ${exchange} routingkey:${routingKey} --> queue:${name}`); } @@ -345,6 +369,7 @@ export default class Queue { await queue.created; } await withDeclareChannel(channel, name, declareChannel => declareChannel.unbindQueue(name, exchange, routingKey)); + queue?.trackBinding(exchange, routingKey, false); logger.debug(`deleted binding${exchange} routingkey:${routingKey} -X-> queue:${name}}`); } } diff --git a/ts/rabbit.ts b/ts/rabbit.ts index ba8108f..aee4ff4 100644 --- a/ts/rabbit.ts +++ b/ts/rabbit.ts @@ -38,6 +38,7 @@ export default class Rabbit extends EventEmitter { private defaultQueueType: string | undefined; private scheduledPublishQueuesAsQuorum: boolean; private tolerateQueueTypeMismatch: boolean; + private resubscribeOnReconnect: boolean; public logger: ReturnType; private readonly sigtermHandler: () => void; @@ -53,6 +54,7 @@ export default class Rabbit extends EventEmitter { scheduledPublishQueuesAsQuorum = false, tolerateQueueTypeMismatch = false, cancelConsumersOnSigterm = true, + resubscribeOnReconnect = true, }: { prefetch?: number replyPattern?: boolean @@ -63,6 +65,7 @@ export default class Rabbit extends EventEmitter { scheduledPublishQueuesAsQuorum?: boolean tolerateQueueTypeMismatch?: boolean cancelConsumersOnSigterm?: boolean + resubscribeOnReconnect?: boolean } = {} ) { super(); @@ -79,6 +82,7 @@ export default class Rabbit extends EventEmitter { this.defaultQueueType = defaultQueueType; this.scheduledPublishQueuesAsQuorum = scheduledPublishQueuesAsQuorum; this.tolerateQueueTypeMismatch = tolerateQueueTypeMismatch; + this.resubscribeOnReconnect = resubscribeOnReconnect; this.sigtermHandler = this.handleSigterm.bind(this); this.reconnect(); @@ -127,8 +131,63 @@ export default class Rabbit extends EventEmitter { this.reportLoss(error); throw error; } + // Before the rebind: a connection lost while it runs must emit 'disconnected'. this.connecting = false; - this.emit('connected'); + if (this.resubscribeOnReconnect) { + await this.rebindQueues(this.consumeChannel); + } + // Lost again while the queues were rebinding: 'disconnected' went out already, and 'connected' would contradict it. + if (!this.lossReported && !this.closed) { + this.emit('connected'); + } + } + + // The queues belong to the channel they were created on, and a reconnect replaces it: without this, every consumer + // stays gone until the app creates its queues again, and an app that doesn't (orka's default) stops consuming + // while it still reports healthy. An app that does create them again on 'connected' replaces these consumers in + // createQueue, so none runs twice. + private async rebindQueues(consumeChannel: Channel) { + for (const queue of Object.values(this.queues)) { + if (queue.channel === consumeChannel) { + continue; + } + // A newer connection took over while this one was rebinding. + if (this.consumeChannel !== consumeChannel || this.lossReported || this.closed) { + return; + } + const handler = queue.handler; + const prefetch = queue.options.prefetch || this.prefetch; + // Server-named queues can't be declared again under the same name. + if (!queue.name) { + if (handler) { + this.logger.error(`Consumer for server-named queue won't subscribe again after the reconnect`); + } + continue; + } + try { + await queue.rebind(consumeChannel); + this.logger.debug(`rebound queue ${queue.name}`); + } catch (error) { + this.logger.error(`Rebinding queue ${queue.name} after the reconnect failed (${error.code}): ${error.message}`); + continue; + } + if (handler) { + try { + await this.subscribeWithPrefetch(queue, handler, prefetch); + this.logger.info(`Subscribed to queue ${queue.name} again after the reconnect`); + } catch (error) { + this.logger.warn(`Subscribing to queue ${queue.name} after the reconnect failed (${error.code}): ${error.message}`); + this.watchForResubscribe(queue, prefetch); + } + } + } + } + + private watchForResubscribe(queue: Queue, prefetch: number) { + // Nothing awaits this; console in case the failure came from a 'log' listener. + this.resubscribe(queue, prefetch).catch(error => + console.error(`[error] rabbit-queue Subscribing to queue ${queue.name} again failed`, error) + ); } async reconnect() { @@ -214,17 +273,18 @@ export default class Rabbit extends EventEmitter { options.prefetch = options.prefetch || this.prefetch; name = this.updateName(name, options.prefix); await this.connected; + // Creating the queue again with a handler replaces the consumer, e.g. the app's own 'connected' handler running + // after the queue was rebound on its own. The old one is cancelled first so the queue doesn't have two. + const previous = this.queues[name]; + if (handler && previous?.handler && previous.channel === this.consumeChannel) { + await previous.unsubscribe(); + } const queue = new Queue(this.consumeChannel, name, { ...options, tolerateQueueTypeMismatch: this.tolerateQueueTypeMismatch }); this.queues[name] = queue; - queue.onCancel = () => { - // Nothing awaits this; console in case the failure came from a 'log' listener. - this.resubscribe(queue, options.prefetch).catch(error => - console.error(`[error] rabbit-queue Subscribing to queue ${name} again failed`, error) - ); - }; + queue.onCancel = () => this.watchForResubscribe(queue, options.prefetch); await queue.created; this.logger.debug(`created queue ${name}`); if (handler) {