- BunnyBus
- Constructor
- Getters and Setters
- Methods
async createExchange(name, type, [options])
async deleteExchange(name, [options])
async checkExchange(name)
async createQueue(name, [options])
async deleteQueue(name, [options])
async checkQueue(name)
async purgeQueue(name)
async publish(message, [options])
async subscribe(queue, handlers, [options])
async unsubscribe(queue)
await send(message, queue, [options])
async get(queue, [options])
async getAll(queue, handler, [options])
- Internal-use Methods
- Events
BunnyBus.LOG_DEBUG_EVENT
BunnyBus.LOG_INFO_EVENT
BunnyBus.LOG_WARN_EVENT
BunnyBus.LOG_ERROR_EVENT
BunnyBus.LOG_FATAL_EVENT
BunnyBus.PUBLISHED_EVENT
BunnyBus.MESSAGE_DISPATCHED_EVENT
BunnyBus.MESSAGE_ACKED_EVENT
BunnyBus.MESSAGE_REQUEUED_EVENT
BunnyBus.MESSAGE_REJECTED_EVENT
BunnyBus.SUBSCRIBED_EVENT
BunnyBus.UNSUBSCRIBED_EVENT
BunnyBus.RECOVERING_CONNECTION_EVENT
BunnyBus.RECOVERED_CONNECTION_EVENT
BunnyBus.RECOVERING_CHANNEL_EVENT
BunnyBus.RECOVERED_CHANNEL_EVENT
BunnyBus.RECOVERY_FAILED_EVENT
Connection
ConnectionManager
Channel
ChannelManager
SubscriptionManager
- Error Types
BunnyBus
is a class that instantiates into a singleton. It hosts all features for communicating with RabbitMQ to provide an easy to use enterprise bus facade.
Note About Versioning
A note regarding versioning: BunnyBus
attaches the version value found in its package.json
file to all messages that are sent. Optionally through the validateVersion
flag, any messages that are picked up from a subscribed queue which do not match the major semver will be rejected to the error queue. As an example, message sent from BunnyBus version 1.2.3
will only be accepted from other BunnyBus
clients with semver range of 1.x.x
.
Creates a new singleton instance of bunnybus
. Accepts a configuration parameter. See config
for allowed options.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus({ hostname : 'red-bee.cloudamqp.com' });
//do work;
Setter and Getter for singleton configuration. Accepts the following optional properties:
protocol
- value for creating a secure connection. Used in the connection string. Defaults toamqp
. [string] Optionalusername
- value of the username. Used in the connection string. Defaults toguest
. [string] Optionalpassword
- value of the password. Used in the connection string. Defaults toguest
. [string] Optionalhostname
- value of the server address. Just the host portion of the URI. egred-bee.cloudamqp.com
orrabbitbox
or56.23.0.123
. Used in the connection string. Defaults to127.0.0.1
. [string] Optionalport
- value of the port for client connections. Used in the conneciton string. Defaults to5672
. [number] Optionalvhost
- value of the virtual host the user connects to. Used in the connection string. Defaults to%2f
. [string] Optionalheartbeat
- value negotiated between client and server on when the TCP tunnel is considered dead. Unit is a measurement of milliseconds. Used in the connection string. Defaults to2000
. [number] Optionaltimeout
- value for timing out any network operations. Unit is a measurement of milliseconds. Defaults to2000
. [number] OptionalglobalExchange
- value of the exchange to transact through for message publishing. This is the default used when one is not provided within theoptions
for anyBunnyBus
methods that supports one transactionally. Defaults todefault-exchange
. [string] Optionalprefetch
- value of the maximum number of unacknowledged messages allowable in a channel. Defaults to5
. [number] OptionalmaxRetryCount
- maximum amount of attempts a message can be requeued. This is the default used when one is not provided within theoptions
for anyBunnyBus
methods that supports one transactionally. Defaults to10
. [number] OptionalvalidatePublisher
- flag to dictate if the publishing source for messages being consumed must bebunnyBus
. This is a safe guard to prevent unexpected message sources from entering the subscribing realm. A value ofbunnyBus
is stamped as a header property on the message duringpublish()
. Thesubscribe()
method will use the same value for authentication. Consumers detecting mismatched publishers will auto reject the message into an error queue. Defaults tofalse
. [boolean] OptionalvalidateVersion
- flag to dictate if major semver should be matched as part of the message subscription valiation. This is a safe guard to prevent mismatchedbunnyBus
drivers from pub/sub to each other. Consumers detecting mismatched major values will auto reject the message into an error queue. In order for this layer of validation to occur,validatePublisher
must be allowed because the version value is set against thebunnyBus
header. Defaults tofalse
. [boolean] OptionalnormalizeMessages
- flag to dictate whether we should coerce incoming messages into our expected shapes. This is primarily used to correct malformed messages from clients other thanbunnyBus
and should only be used when validatePublisher is set tofalse
. This will alter incoming messages. Defaults tofalse
. [boolean] OptionaldisableQueueBind
- flag to dictate if automatic queue binding should be turned on/off as part of the consume setup process. Defaults tofalse
. [boolean] OptionaldispatchType
- enumerated value to select dispatch mechanism used.serial
will flow messages to your message handler(s) in single file.concurrent
will flow messages simultaneously to your message handler(s). Defaults toserial
. [string] OptionalrejectUnroutedMessages
- flag to direct messages that were unroutable to provided handlers to either be automatically rejected or acknowledged off the queue. The default is silent acknowledgements. Defaults tofalse
. [boolean] Optional
Note that updates in the options directed at changing connection string will not take affect immediately. ConnectionManager.close()
needs to be called manually to invoke a new connection with new settings.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
//deferred configuration
bunnyBus.config = { hostname : 'red-bee.cloudamqp.com'};
//do work
Getter for connections. A reference to the Connection Manager.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
console.log(bunnyBus.connections.get('defaultConnection'));
// output : { name, connectionOptions, socketOptions, lock, blocked, connection }
Getter for channels. A reference to the Channel Manager.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
console.log(bunnyBus.channels.get('channelForQueue1'));
// output : { name, queue, connectionContext, channelOptions, lock, channel }
Getter for subscriptions. A reference to the Subscription Manager.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
console.log(bunnyBus.subscriptions.get('queue'));
//output : { queue : 'queue1', consumerTag : 'abc123', handlers : {}, options : {}}
Setter and Getter for logger. By default, BunnyBus
will instantiate and set a logger using the EventEmitter
. When a custom logger is set, BunnyBus
will no longer emit log messages through the EventEmitter
. The Setter will also validate the contract of the logger to ensure the following keys exist [debug
, info
, warn
, error
, fatal
] and are of type Function
. When validation fails, an error will be thrown.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const logHandler = (message) => {
//forward the message to some where such as
//process.stdout or console.log or syslog.
};
//custom logger
bunnyBus.logger = {
info : logHandler,
debug : logHandler,
warn : logHandler,
error : logHandler,
fatal : logHandler
};
Getter for AMQP connection string.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
console.log(bunnyBus.connectionString);
//output : amqp://guest:[email protected]:5672/%2f?heartbeat=2000
Creates an exchange.
name
- name of the exchange to be created. [string] Requiredtype
- type of exchange to create. Possible values are (direct
,fanout
,header
,topic
) [string] Requiredoptions
- optional settings. Settings are proxied through to amqplibassertExchange
. [Object] Optional
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnyBus.createExchange('default-exchange', 'topic');
Delete an exchange.
name
- name of the exchange to be deleted. [string] Requiredoptions
- optional settings. Settings are proxed through to amqplibdeleteExchange
. [Object] Optional
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnyBus.deleteExchange('default-exchange');
Checks if an exchange exists. The channel closes when the exchange does not exist.
name
- name of the exchange to be checked. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnyBus.checkExchange('default-exchange');
Creates a queue.
name
- name of the queue to be created. [string] Requiredoptions
- optional settings. Settings are proxied through to amqplibassertQueue
. [Object] Optional
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnyBus.createQueue('queue1');
Delete a queue.
name
- name of the queue to be created. [string] Requiredoptions
- optional settings. Settings are proxied through to amqplibdeleteQueue
. [Object] Optional
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnyBus.deleteQueue('queue1');
Checks if a queue exists. The channel closes when the queue does not exist.
name
- name of the queue to be checked. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnyBus.checkQueue('queue1');
Purges a queue. Will not throw error in cases where queue does not exist.
name
- name of the queue to be purged. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnyBus.purgeQueue('queue1');
Publish a message onto the bus.
message
- the content being sent to downstream subscribers. [string|Object|Buffer] Requiredevent
- override value for the route key. The value must be supplied here or inoptions.routeKey
. The value can be.
separated for namespacing. [string] Optional.options
- optional settings. [Object] OptionalrouteKey
- value for the route key to route the message with. The value must be supplied here or inmessage.event
. The value can be.
separated for namespacing. [string] OptionaltransactionId
- value attached to the header of the message for tracing. When one is not supplied, a random 40 character token is generated. [string] Optionalsource
- value attached to the header of the message to help with track the origin of messages in your application. For applications that leverage this plugin in multiple modules, each module can supply its own module name so a message can be tracked to the creator. [string] OptionalglobalExchange
- value to override the exchange specified inconfig
. [string] Optional- In addition to the above options, all of
amqplib
's configuration options (except forheaders
andimmediate
) from itssendToQueue
andpublish
methods can also be passed as top-level properties in thepublish
options.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const message = {
event : 'some.routeKey'
// other stuff you want to send
}
await bunnyBus.publish(message);
Subscribe to messages from a given queue.
queue
- the name of the queue to subscribe messages to. A queue with the provided name will be created if one does not exist. [string] Requiredhandlers
- akey
/handler
hash where the key reflects the name of themessage.event
orrouteKey
. And the handler reflects aAsyncFunction
asasync (message, [meta, [ack, [reject, [requeue]]]]) => {}
. [Object] Requiredoptions
- optional settings. [Object] Optionalqueue
- settings for the queue. Settings are proxied through to amqplibassertQueue
. [Object] OptionalglobalExchange
- value of the exchange to transact through for message publishing. Defaults to one provided in the config. [string] OptionalmaxRetryCount
- maximum amount of attempts a message can be requeued. Defaults to one provided in the config. [number] OptionalvalidatePublisher
- flag for validating messages havingbunnyBus
header. More info can be found in config. Defaults to one provided in the config. [boolean] OptionalvalidateVersion
- flag for validating messages generated from the same major version. More info can be found in config. Defaults to one provided in the config. [boolean] OptionaldisableQueueBind
- flag for disabling automatic queue binding. More info can be found in config. Defaults to one provided in the config. [boolean] OptionalrejectUnroutedMessages
- flag for enabling rejection for unroutable messages. More info can be found in config. Defaults to one provided in the config. [boolean]meta
- allows for meta data regarding the payload to be returned. Headers like thecreatedAt
ISO string timestamp and thetransactionId
are included in themeta.headers
object. Turning this on will adjust the handler to be anAsyncFunction
asasync (message, meta, [ack, [reject, [requeue]]]) => {}
. [boolean] Optional
A key
is the routeKey in RabbitMQ terminology. BunnyBus
specifically leverages topic exchange to route a message from the exchange to any number of queues that are subscribed. The keys are normally dot notated and wild cards of *
(can substitute for exactly one word) and #
(can substitute for zero or more words). Keys can look like vineyard.wine-produced
, vineyard.wine-sold
, vineyard.*
, vineyard.#
and etc... A bug was found during this implementation regarding expected behavior of wildcard syntax here
A handler
is an asynchronous function which contains the following arity. Order matters.
message
is what was received from the bus. The message does represent the RabbitMQ'payload.content
buffer. The original source of this object is frompayload.content
.meta
is only available whenoptions.meta
is set totrue
. This object will contain all payload related meta information likepayload.properties.headers
. Headers like thecreatedAt
ISO string timestamp and thetransactionId
are included in themeta.headers
object.async ack([option)
is an async function for acknowledging the message off the bus.option
- a placeholder for future optional parameters forack
. High chance of deprecation.
async reject([option)
is an async function for rejecting the message off the bus to a predefined error queue. The error queue is named by default<your queue name>_error
. It will also short circuit toerror_bus
when defaults can't be found.option
- An object with a property ofreason
to be supplied. [Object] Optional
async requeue()
is an async function for requeuing the message back to the back of the queue. This is feature circumvents Rabbit'snack
RPC.nack
natively requeues but pushes the message to the front of the queue.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const handlers = {
route.event1 : async (message, ack, reject, requeue) => {
await ack();
},
route.event2 : async (message, ack, reject, requeue) => {
if (//something not ready) {
await requeue();
} else {
await ack();
}
}
}
await bunnyBus.subscribe('queue', handlers);
Unsubscribe active handlers that are listening to a queue.
queue
- the name of the queue. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnyBus.unsubscribe('queue1');
Send a message directly to a specified queue.
When message.event
or options.routeKey
values are not provided for routeKey
addressing. The message will be lost when subcribe()
handles the queue because messages without a routeKey
are discarded.
message
- the content being sent directly to specfied queue. [string|Object|Buffer] Requiredevent
- override value for the route key. The value must be supplied here or inoptions.routeKey
. The value can be.
separated for namespacing. [string] Optional.queue
- the name of the queue. [string] Requiredoptions
- optional settings. [Object] OptionalrouteKey
- value for the route key to route the message with. The value must be supplied here or inmessage.event
. The value can be.
separated for namespacing. [string] OptionaltransactionId
- value attached to the header of the message for tracing. When one is not supplied, a random 40 character token is generated. [string] Optionalsource
- value attached to the header of the message to help with tracking the origination point of your application. For applications that leverage this plugin in multiple modules, each module can supply its own module name so a message can be tracked to the creator. [string] Optional- In addition to the above options, all of
amqplib
's configuration options (except forheaders
andimmediate
) from itssendToQueue
andpublish
methods can also be passed as top-level properties in thesend
options.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const message = {
// other stuff you want to send
}
await bunnyBus.send(message, 'queue1');
Pop a message directly off a queue. The payload returned is the RabbitMQ payload
with payload.properties
and payload.content
in its original form.
queue
- the name of the queue. [string] Requiredoptions
- optional settings. Settings are proxied through to amqplibget
. [Object] Optional
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const payload = await bunnyBus.get('queue1');
Pop all messages directly off of a queue until there are no more. Handler is called for each message that is popped.
queue
- the name of the queue. [string] Requiredhandler
- a handler reflects anAsyncFunction
asasync (message, [meta, [ack]]) => {}
. [AsyncFunction] Requiredoptions
- optional settings. [Object] Optionalget
- Settings are proxied through to amqplibget
. [Object] Optionalmeta
- allows for meta data regarding the payload to be returned. Headers like thecreatedAt
ISO string timestamp and thetransactionId
are included in themeta.headers
object. Turning this on will adjust the handler to be anAsyncFunction
asasync (message, meta, [ack]) => {}
. [boolean] Optional
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const handler = async (message, ack) => {
await ack();
}
await bunnyBus.getAll('queue1', handler);
The following methods are available in the public API, but manual use of them is highly discouraged.
Method handles the coordination for creating a connection and channel via the ConnectionManager
and ChannelManager
. This is also responsible for subscribing to error and close events available from the Connection
and Channel
context classes which proxy events from the corresponding underlying amqplib
objects.
channelName
- name of the channel to be created or fetched. [string] Requiredqueue
- name of queue that will be using the channel. Defaults tonull
. [string] Optional
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const channelContext = await bunnyBus._autoBuildChannelContext(channelForQueue1);
// output : { name, queue, connectionContext, channelOptions, lock, channel }
Auto retry mechanism to restore all channels and connection that were closed which should still remain active. This method primarily loops against all active subscribed queues to try and recover them. When failures happens, an invocation to process.exit(1)
will be done. This is invoked internally through event handlers listening to connection and channel events.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
// something bad happened
await bunnyBus._recoverConnection();
Auto retry mechanism to restore a specific channel and attached connection that was closed. When failure happens, an invocation to process.exit(1)
will be done. This is invoked internally through event handlers listening to channel events. This will not revive subscribed queues that are in block state registered through the SubscriptionManager
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
// something bad happened
await bunnyBus._recoverChannel(channelName);
The acknowledge method for removing a message off the queue. Mainly used in handlers through bind()
parameter injection for methods like getAll()
and subscribe
.
payload
- raw payload from an AMQP result message response. [Object] RequiredchannelName
- the originating channel the payload came from. [string] Requiredoptions
- not currently used.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const payload = await bunnyBus.getAll('queue1');
await bunnyBus.ack(payload, 'channelForQueue1');
Requeues message to any queue while it acknowledges the payload off of the original. This method does not push the message back to the original queue in the front position. It will put the message to any desired queue in the back position. Mainly used in handlers through bind()
parameter injection for methods like getAll()
and subscribe()
.
payload
- raw payload from an AMQP result message response. [Object] RequiredchannelName
- the originating channel the payload came from. [string] Requiredqueue
- the destination queue to push to. [string] Requiredoptions
- can supply AMQP specific values which is just proxied tosentToQueue
[Object] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const payload = await bunnyBus.getAll('queue1');
await bunnyBus.requeue(payload, 'channelForQueue1', 'queue1');
Rejects a message by acknowledging off the originating queue and sending to an error queue of choice. Mainly used in handlers through bind()
parameter injection for methods like getAll()
and subscribe()
.
payload
- raw payload from an AMQP result message response. [Object] RequiredchannelName
- the originating channel the payload came from. [string] RequirederrorQueue
- the destination error queue to push to. Defaults to a queue defined inconfig
[string] Optionaloptions
- can supply AMQP specific values which is just proxied tosentToQueue
for the destination error queue. A property ofreason
can be supplied which will be caught and added to the message header. The property ofreason
is used uniformally within all rejection paths in the BunnyBus code base. [Object] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const payload = await bunnyBus.getAll('queue1');
await bunnyBus.reject(payload, 'channelForQueue1', 'queue1_error', { reason: 'some unforeseen failure' });
BunnyBus
extends EventEmitter
for emitting logs and system specific events. Subscription to these events is optional. BunnyBus
class also exposes static Getter properties for the name of these public events.
log.debug
- debug level logging message.
...message
- log parameter of n-arity sent. [any]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.LOG_DEBUG_EVENT', console.log);
log.info
- info level logging message.
...message
- log parameter of n-arity sent. [any]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.LOG_INFO_EVENT', console.log);
log.warn
- warn level logging message.
...message
- log parameter of n-arity sent. [any]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.LOG_WARN_EVENT', console.log);
log.error
- error level logging message.
...message
- log parameter of n-arity sent. [any]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.LOG_ERROR_EVENT', console.log);
log.fatal
- fatal level logging message.
...message
- log parameter of n-arity sent. [any]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.LOG_FATAL_EVENT', console.log);
bunnybus.published
- emitted whenpublish()
is successfully called.
publishOptions
- option sent along with the message header/fields [Object]message
- original payload published. [string|Object|Buffer]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.PUBLISHED_EVENT', (options, message) => {
//do work
});
bunnybus.message-dispatched
- emitted when subscribing handlers for a queue is about to be called.
metaData
- option sent along with the message header/fields [Object]message
- the parsed version of thecontent
property from the original payload. [string|Object|Buffer]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.MESSAGE_DISPATCHED_EVENT', (metaData, message) => {
//do work
});
bunnybus.message-acked
- emitted when_ack()
is called succesfully.
metaData
- option sent along with the message header/fields [Object]message
- the parsed version of thecontent
property from the original payload. [string|Object|Buffer]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.MESSAGE_ACKED_EVENT', (metaData, message) => {
//do work
});
bunnybus.message-requeued
- emitted when_requeue()
is called succesfully.
metaData
- option sent along with the message header/fields [Object]message
- the parsed version of thecontent
property from the original payload. [string|Object|Buffer]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.MESSAGE_REQUEUED_EVENT', (metaData, message) => {
//do work
});
bunnybus.message-rejected
- emitted when_reject()
is called succesfully.
metaData
- option sent along with the message header/fields [Object]message
- the parsed version of thecontent
property from the original payload. [string|Object|Buffer]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.MESSAGE_REJECTED_EVENT', (metaData, message) => {
//do work
});
bunnybus.subscribed
- emitted whensubcribe()
is successfully called.
queue
- name of queue subcribed for. [string]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.SUBSCRIBED_EVENT', (queue) => {
console.log(queue);
// output : 'queue1'
});
bunnybus.unsubscribed
- emitted whenunsubcribe()
is successfully called.
queue
- name of queue unsubscribed from. [string]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.UNSUBSCRIBED_EVENT', (queue) => {
console.log(queue);
// output : 'queue1'
});
bunnybus.recovering-connection
- emitted whenAMQP_CONNECTION_CLOSE_EVENT
is invoked.
connectionName
- name of the connection involved with the recovery event.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.RECOVERING_CONNECTION_EVENT', (connectionName) => {
// do work to handle the case when a connection or channel is having a failure
});
bunnybus.recovered-connection
- emitted when the corresponding recovering connection event is restored
connectionName
- name of the connection involved with the recovery event.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.RECOVERED_CONNECTION_EVENT', (connectionName) => {
// do work to handle the case when a connection or channel is having a failure
});
bunnybus.recovering-channel
- emitted whenAMQP_CHANNEL_CLOSE_EVENT
is invoked.
channelName
- name of the channel involved with the recovery event.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.RECOVERING_CHANNEL_EVENT', (channelName) => {
// do work to handle the case when a connection or channel is having a failure
});
bunnybus.recovered-channel
- emitted when the corresponding recovering channel event is restored
channelName
- name of the channel involved with the recovery event.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.RECOVERED_CHANNEL_EVENT', (channelName) => {
// do work to handle the case when a connection or channel is having a failure
});
bunnybus.recovery-failed
- emitted when recovery efforts leads to a failed state.
err
- a error object of typeError
[Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.on('BunnyBus.RECOVERY_FAILED_EVENT', (err) => {
// do work to handle the case when a connection or channel is having a failure
});
This class contains the actual amqplib
connection objet along with contextual properties like name and options that were used to create the connection. The Connection
is also an EventEmitter
to support event proxying from the underlying amqplib
connection object.
Getter for connection name. Value used for futher operation and identification of a connection.
Getter for connection options supplied to amqplib.connect()
interface. See config
for allowed options. Only relevant subset is used.
Getter for socket / tls options supplied to amqplib.connect()
interface that is then proxied to the underling net
and tls
libraries.
Setter and Getter for mutual-exclusion lock for the instantiated object. Used to ensure operations for connection creation is done single file sequentially.
Setter and Getter for connection block signaling from RabbitMQ for cases of server resource starvation.
Setter and Getter for the amqplib
connection object.
amqp.connection.error
- emitted when theamqplib
connection errors.
err
- a error object of typeError
[Object]connectionContext
- connection context that is theConnecton
class [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.connections.get('connectionName').on(ConnectionManager.AMQP_CONNECTION_ERROR_EVENT, (err, context) => {
console.error(err);
console.log(context);
// output : { name, connectionOptions, socketOptions, lock, blocked, connection }
});
amqp.connection.close
- emitted when theamqplib
connection closes.
connectionContext
- connection context that is theConnecton
class [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.connections.get('connectionName').on(ConnectionManager.AMQP_CONNECTION_CLOSE_EVENT, (context) => {
console.log(context);
// output : { name, connectionOptions, socketOptions, lock, blocked, connection }
});
amqp.connection.blocked
- emitted when theamqplib
connection is blocked to signal no more send/publish operations should be invoked.
connectionContext
- connection context that is theConnecton
class [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.connections.get('connectionName').on(ConnectionManager.AMQP_CONNECTION_BLOCKED_EVENT, (context) => {
console.log(context);
// output : { name, connectionOptions, socketOptions, lock, blocked, connection }
});
amqp.connection.unblocked
- emitted when theamqplib
connection is unblocked.
connectionContext
- connection context that is theConnecton
class [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.connections.get('connectionName').on(ConnectionManager.AMQP_CONNECTION_UNBLOCKED_EVENT, (context) => {
console.log(context);
// output : { name, connectionOptions, socketOptions, lock, blocked, connection }
});
connectionManager.removed
- emitted when the connection context is removed byclose()
.
connectionContext
- connection context that is theConnecton
class [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.connections.get('connectionName').on(ConnectionManager.CONNECTION_REMOVED, (context) => {
console.log(context);
// output : { name, connectionOptions, socketOptions, lock, blocked, connection }
});
This class manages the collection of all connections created within BunnyBus. The ConnectionManager
is also an EventEmitter
so when actions like remove
is called, events are emitted.
Creates an amqplib
connection.
name
- name of the connection. [string] RequiredconnectionOptions
- options used to create theamqplib
connection. Seeconfig
for allowed options. Only relevant subset is used. [Object] RequiredsocketOptions
- options used to configure the underlying socket/tls behavior. Refer tonet
/ `tls' modules for configuration values. [Object] Optional
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const connectionContext = await bunnybus.connections.create('defaultConnection', { hostname, username, password });
Checks if a connection context exist with the specified name.
name
- name of the connection. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const exist = bunnybus.connections.contains('defaultConnection');
// exist : boolean
Retrieves a connection context with the specified name.
name
- name of the connection. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const connectionContext = bunnybus.connections.get('defaultConnection');
Returns all connections registered that are in any state of operability.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const connectionContexts = bunnybus.connections.list();
Checks if an amqplib
connection exist with the specified name.
name
- name of the connection. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const exist = bunnybus.connections.hasConnection('defaultConnection');
// exist : boolean
Retrieves an amqplib
connection with the specified name.
name
- name of the connection. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const connection = bunnybus.connections.getConnection('defaultConnection');
// connection : amqplib connecton object
Removes the connection context with the specified name from the ConnectionManager
. Closes the underlying connection.
name
- name of the connection. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnybus.connections.remove('defaultConnection');
Closes the amqplib
connection the specified name.
name
- name of the connection. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnybus.connections.close('defaultConnection');
connectionManager.removed
- emitted when the connection context is removed byclose()
.
connectionContext
- connection context that is theConnecton
class [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.connections.on(ConnectionManager.CONNECTION_REMOVED, (context) => {
console.log(context);
// output : { name, connectionOptions, socketOptions, lock, blocked, connection }
});
This class contains the actual amqplib
channel object along with contextual properties like name, connection context and otions that were used to create the channel. The Channel
is also an EventEmitter
to support event proxying from the underlying amqplib
channel object.
Getter for channel name. Value used for futher operation and identification of a channel.
Getter for connection context. The connection context contains the amqplib
connection object that is used to create a channel from.
Getter for channel options supplied to amqplib.createConfirmChannel()
interface. See config
for allowed options. Only relevant subset is used like prefetch
Setter and Getter for mutual-exclusion lock for the instantiated object. Used to ensure operations for channel creation is done single file sequentially.
Setter and Getter for the amqplib
channel object.
amqp.channel.error
- emitted when theamqplib
channel errors.
err
- a error object of typeError
[Object]channelContext
- channel context that is theChannel
class [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.channels.get('channelName').on(ChannelManager.AMQP_CHANNEL_ERROR_EVENT, (err, context) => {
console.error(err);
console.log(context);
// output : { name, queue, connectionContext, channelOptions, lock, channel }
});
amqp.channel.close
- emitted when theamqplib
channel closes.
channelContext
- channel context that is theChannel
class [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.channels.get('channelName').on(ChannelManager.AMQP_CHANNEL_CLOSE_EVENT, (context) => {
console.log(context);
// output : { name, queue, connectionContext, channelOptions, lock, channel }
});
amqp.channel.return
- emitted when theamqplib
channel returns a message that had no route recipient when published to an exchange.
payload
- The message that was sent with no matching route recipient. [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.channels.get('channelName').on(ChannelManager.AMQP_CHANNEL_RETURN_EVENT, (payload) => {
console.log(payload);
// output : { properties, content }
});
amqp.channel.drain
- emitted when theamqplib
channel signals resource capacity recovery allowing for more messages to be sent.
channelContext
- channel context that is theChannel
class [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.channels.get('channelName').on(ChannelManager.AMQP_CHANNEL_DRAIN_EVENT, (context) => {
console.log(context);
// output : { name, queue, connectionContext, channelOptions, lock, channel }
});
channelManager.removed
- emitted when the channel context is removed byclose()
.
channelContext
- channel context that is theChannel
class [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.connections.get('connectionName').on(ChannelManager.CHANNEL_REMOVED, (context) => {
console.log(context);
// output : { name, queue, connectionContext, channelOptions, lock, channel }
});
This class manages the collection of all connections created within BunnyBus. The ConnectionManager
is also an EventEmitter
so when actions like remove
is called, events are emitted.
Creates an amqplib
channel.
name
- name of the channel. [string] Requiredqueue
- name of the queue the channel is supporting. Used primarily as a label to use for filtering and identification. Defaults tonull
. [string] OptionalconnectionContext
- the connection context to use for instantiation of a channel from. [Object] RequiredchannelOptions
- options used to create theamqplib
connection. Seeconfig
for allowed options. Only relevant subset is used likeprefetch
[Object] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const channelContext = await bunnybus.channels.create('channelForQueue1', 'queue1', connectionContext, { prefetch });
Checks if a channel context exist with the specified name.
name
- name of the channel. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const exist = bunnybus.channels.contains('channelForQueue1');
// exist : boolean
Retrieves a channel context with the specified name.
name
- name of the channel. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const channelContext = bunnybus.channels.get('channelForQueue1');
Returns all channels registered that are in any state of operability.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const channelContexts = bunnybus.channels.list();
Checks if an amqplib
channel exist with the specified name.
name
- name of the channel. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const exist = bunnybus.channels.hasChannel('channelForQueue1');
// exist : boolean
Retrieves an amqplib
channel with the specified name.
name
- name of the channel. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
const channel = bunnybus.channels.getConnection('channelForQueue1');
// connection : amqplib channel object
Removes the channel context with the specified name from the ChannelManager
. Closes the underlying channel.
name
- name of the channel. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnybus.channels.remove('channelForQueue1');
Closes the amqplib
channel the specified name.
name
- name of the channel. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
await bunnybus.connections.close('channelForQueue1');
channelManager.removed
- emitted when the channel context is removed byremove()
.
channelContext
- channel context that is theChannel
class [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.channels.on(ChannelManager.AMQP_CHANNEL_DRAIN_EVENT, (context) => {
console.log(context);
// output : { name, queue, connectionContext, channelOptions, lock, channel }
});
This class manages the state for all subscriptions registered with queues. A subscription is an association between a queue and handlers associated with it. A subscription is created when subscribe()
is invoked succesfully. The SubscriptionManager
is also an EventEmitter
so when actions like create
, clear
and remove
are called, events are emitted so BunnyBus
can apply the corresponding behavior to meet the desired state.
Checks if a queue has a subscription.
queue
- the name of the queue. [string] RequiredwithConsumerTag
- requires the condition of a subscription to be active. Defaults totrue
. [boolean] Optional
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnybus.subscriptions.contains('queue1');
Creates a subscription.
queue
- the name of the queue. [string] Requiredhandlers
- handlers parameter passed through thesubscribe()
method. [Object] Requiredoptions
- options parameter passed through thesubscribe()
method. [Object] Optional
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnybus.subscriptions.create('queue1');
}
Tag a subscription.
queue
- the name of the queue. [string] RequiredconsumerTag
- a value returned from theconsume()
method of amqplib. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnybus.subscriptions.tag('queue1', 'abcd1234');
}
Returns a clone of the subscription if the queue exists. Returns undefined
when it does not exist.
queue
- the name of the queue. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnybus.subscriptions.get('queue1');
}
Clears a subscription of the consumerTag
. Returns true
when successful and false
when not.
queue
- the name of the queue. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnybus.subscriptions.clear('queue1');
}
Clears all subscriptions of the consumerTag
.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnybus.subscriptions.clearAll();
}
Removes a subscription from the registrar. Returns true
when successful and false
when not.
queue
- the name of the queue. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnybus.subscriptions.remove('queue1');
}
Returns a list of cloned subscriptions in the registrar.
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnybus.subscriptions.list();
//output : [ subscriptions ]
}
Adds a queue to the ban list. Queues in this list live in the desired state. Once a queue name is added to this list, BunnyBus
will try to unsubscribe any active consumed queues.
queue
- the name of the queue. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnybus.subscriptions.block('queue1');
}
Removes a queue from the ban list. Queues in this list live in the desired state. Once a queue name is removed from this list, BunnyBus
will try to re-subscribe any unactive queues.
queue
- the name of the queue. [string] Required
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnybus.subscriptions.unblock('queue1');
}
subscription.created
- emitted whencreate()
is succesfully called.
subscription
- subscription context that was created [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.subscriptions.on(SubscriptionMananger.CREATED_EVENT, (context) => {
console.log(context);
// output : { queue, handlers, options, consumerTag }
});
subscription.tagged
- emitted whentag()
is succesfully called.
subscription
- subscription context that was tagged [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.subscriptions.on(SubscriptionMananger.TAGGED_EVENT, (context) => {
console.log(context);
// output : { queue, handlers, options, consumerTag }
});
subscription.cleared
- emitted whenclear()
is succesfully called.
subscription
- subscription context that had its consumer tag removed [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.subscriptions.on(SubscriptionMananger.CLEARED_EVENT, (context) => {
console.log(context);
// output : { queue, handlers, options, consumerTag }
});
subscription.removed
- emitted whenremove()
is succesfully called.
subscription
- subscription context that was removed [Object]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.subscriptions.on(SubscriptionMananger.REMOVED_EVENT, (context) => {
console.log(context);
// output : { queue, handlers, options, consumerTag }
});
subscription.blocked
- emitted whenblock()
is succesfully called.
queue
- queue that was added to the block list [string]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.subscriptions.on(SubscriptionMananger.BLOCKED_EVENT, (queue) => {
console.log(queue);
// output : 'queue1'
});
subscription.unblocked
- emitted whenunblock()
is succesfully called.
queue
- queue that was removed from the block list [string]
const BunnyBus = require('bunnybus');
const bunnyBus = new BunnyBus();
bunnyBus.subscriptions.on(SubscriptionMananger.UNBLOCKED_EVENT, (queue) => {
console.log(queue);
// output : 'queue1'
});
All BunnyBus
errors are extended from the native Error
class.
IncompatibleLoggerError
- thrown when the logger interface contract is not met wheninstance.logger
is set.NoConnectionError
- thrown when no connection existNoChannelError
- thrown when no channel existNoHeaderFieldError
- thrown when an incoming message lacks a header fieldNoRouteKeyError
- thrown when no route key can be found. Lookup is done againstpayload.properties.headers.routeKey
,options.routeKey
,message.event
andpayload.fields.routingKey
in that order.SubscriptionExistError
- thrown whensubscribe()
is called and handlers have already been registered against the queueSubscriptionBlockedError
- thrown whensubscribe()
is called and the queue is in a desired state of blocked. The handlers would still have registered, but it would take anunblock()
call to allow for the handlers to continue its subscriptions.