Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
pm2-axon is a high-performance inter-process messaging library for Node.js, designed to facilitate communication between different processes or services. It provides various messaging patterns such as push/pull, pub/sub, and req/rep, making it suitable for building scalable and distributed systems.
Push/Pull
The push/pull pattern is used for distributing tasks among multiple workers. The push socket sends messages to connected pull sockets in a round-robin fashion.
const axon = require('pm2-axon');
const push = axon.socket('push');
const pull = axon.socket('pull');
push.bind(3000);
pull.connect(3000);
pull.on('message', function(msg){
console.log('received: %s', msg);
});
push.send('hello');
Pub/Sub
The pub/sub pattern is used for broadcasting messages to multiple subscribers. The pub socket sends messages to all connected sub sockets.
const axon = require('pm2-axon');
const pub = axon.socket('pub');
const sub = axon.socket('sub');
pub.bind(4000);
sub.connect(4000);
sub.on('message', function(msg){
console.log('received: %s', msg);
});
pub.send('hello world');
Req/Rep
The req/rep pattern is used for request/response communication. The req socket sends a request and waits for a response from the rep socket.
const axon = require('pm2-axon');
const req = axon.socket('req');
const rep = axon.socket('rep');
req.bind(5000);
rep.connect(5000);
rep.on('message', function(msg, reply){
console.log('received: %s', msg);
reply('pong');
});
req.send('ping', function(res){
console.log('reply: %s', res);
});
ZeroMQ is a high-performance asynchronous messaging library aimed at use in scalable distributed or concurrent applications. It provides similar messaging patterns like push/pull, pub/sub, and req/rep. Compared to pm2-axon, ZeroMQ is more mature and widely used in various languages, not just Node.js.
AMQP (Advanced Message Queuing Protocol) is a protocol for message-oriented middleware. The 'amqp' npm package allows Node.js applications to communicate with AMQP brokers like RabbitMQ. It supports various messaging patterns and is more feature-rich compared to pm2-axon, but it requires a message broker to function.
Redis is an in-memory data structure store that can be used as a message broker. The 'redis' npm package allows Node.js applications to use Redis for pub/sub messaging. While Redis is not specifically designed for inter-process communication, it provides robust pub/sub capabilities and can be used for similar purposes as pm2-axon.
Axon is a message-oriented socket library for node.js heavily inspired by zeromq. For a light-weight UDP alternative you may be interested in punt.
$ npm install axon
close
when server or connection is closederror
(err) when an un-handled socket error occursignored error
(err) when an axon-handled socket error occurs, but is ignoredsocket error
(err) emitted regardless of handling, for logging purposesreconnect attempt
when a reconnection attempt is madeconnect
when connected to the peer, or a peer connection is accepteddisconnect
when an accepted peer disconnectsbind
when the server is bounddrop
(msg) when a message is dropped due to the HWMflush
(msgs) queued when messages are flushed on connectionBacked by node-amp-message you may pass strings, objects, and buffers as arguments.
push.send('image', { w: 100, h: 200 }, imageBuffer);
pull.on('message', function(type, size, img){});
PushSocket
s distribute messages round-robin:
var axon = require('axon');
var sock = axon.socket('push');
sock.bind(3000);
console.log('push server started');
setInterval(function(){
sock.send('hello');
}, 150);
Receiver of PushSocket
messages:
var axon = require('axon');
var sock = axon.socket('pull');
sock.connect(3000);
sock.on('message', function(msg){
console.log(msg.toString());
});
Both PushSocket
s and PullSocket
s may .bind()
or .connect()
. In the
following configuration the push socket is bound and pull "workers" connect
to it to receive work:
This configuration shows the inverse, where workers connect to a "sink" to push results:
PubSocket
s send messages to all subscribers without queueing. This is an
important difference when compared to a PushSocket
, where the delivery of
messages will be queued during disconnects and sent again upon the next connection.
var axon = require('axon');
var sock = axon.socket('pub');
sock.bind(3000);
console.log('pub server started');
setInterval(function(){
sock.send('hello');
}, 500);
SubSocket
simply receives any messages from a PubSocket
:
var axon = require('axon');
var sock = axon.socket('sub');
sock.connect(3000);
sock.on('message', function(msg){
console.log(msg.toString());
});
SubSocket
s may optionally .subscribe()
to one or more "topics" (the first multipart value),
using string patterns or regular expressions:
var axon = require('axon');
var sock = axon.socket('sub');
sock.connect(3000);
sock.subscribe('user:login');
sock.subscribe('upload:*:progress');
sock.on('message', function(topic, msg){
});
ReqSocket
is similar to a PushSocket
in that it round-robins messages
to connected RepSocket
s, however it differs in that this communication is
bi-directional, every req.send()
must provide a callback which is invoked
when the RepSocket
replies.
var axon = require('axon');
var sock = axon.socket('req');
sock.bind(3000);
sock.send(img, function(res){
});
RepSocket
s receive a reply
callback that is used to respond to the request,
you may have several of these nodes.
var axon = require('axon');
var sock = axon.socket('rep');
sock.connect(3000);
sock.on('message', function(img, reply){
// resize the image
reply(img);
});
Like other sockets you may provide multiple arguments or an array of arguments, followed by the callbacks. For example here we provide a task name of "resize" to facilitate multiple tasks over a single socket:
var axon = require('axon');
var sock = axon.socket('req');
sock.bind(3000);
sock.send('resize', img, function(res){
});
Respond to the "resize" task:
var axon = require('axon');
var sock = axon.socket('rep');
sock.connect(3000);
sock.on('message', function(task, img, reply){
switch (task) {
case 'resize':
// resize the image
reply(img);
break;
}
});
PubEmitter
and SubEmitter
are higher-level Pub
/ Sub
sockets, using the "json" codec to behave much like node's EventEmitter
. When a SubEmitter
's .on()
method is invoked, the event name is .subscribe()
d for you. Each wildcard (*
) or regexp capture group is passed to the callback along with regular message arguments.
app.js:
var axon = require('axon');
var sock = axon.socket('pub-emitter');
sock.connect(3000);
setInterval(function(){
sock.emit('login', { name: 'tobi' });
}, 500);
logger.js:
var axon = require('axon');
var sock = axon.socket('sub-emitter');
sock.bind(3000);
sock.on('user:login', function(user){
console.log('%s signed in', user.name);
});
sock.on('user:*', function(action, user){
console.log('%s %s', user.name, action);
});
sock.on('*', function(event){
console.log(arguments);
});
Every socket has associated options that can be configured via get/set
.
identity
- the "name" of the socket that uniqued identifies it.retry timeout
- connection retry timeout in milliseconds [100] (0 = do not reconnect)retry max timeout
- the cap for retry timeout length in milliseconds [5000]hwm
- the high water mark threshold for queues [Infinity]In addition to passing a portno, binding to INADDR_ANY by default, you
may also specify the hostname via .bind(port, host)
, another alternative
is to specify the url much like zmq via tcp://<hostname>:<portno>
, thus
the following are equivalent:
sock.bind(3000)
sock.bind(3000, '0.0.0.0')
sock.bind('tcp://0.0.0.0:3000')
sock.connect(3000)
sock.connect(3000, '0.0.0.0')
sock.connect('tcp://0.0.0.0:3000')
You may also use unix domain sockets:
sock.bind('unix:///some/path')
sock.connect('unix:///some/path')
Axon 2.x uses the extremely simple AMP protocol to send messages on the wire. Codecs are no longer required as they were in Axon 1.x.
Preliminary benchmarks on my Macbook Pro based on 10 messages per tick as a realistic production application would likely have even less than this. "better" numbers may be acheived with batching and a larger messages/tick count however this is not realistic.
64 byte messages:
min: 47,169 ops/s
mean: 465,127 ops/s
median: 500,000 ops/s
total: 2,325,636 ops in 5s
through: 28.39 mb/s
1k messages:
min: 48,076 ops/s
mean: 120,253 ops/s
median: 121,951 ops/s
total: 601,386 ops in 5.001s
through: 117.43 mb/s
8k messages:
min: 36,496 ops/s
mean: 53,194 ops/s
median: 50,505 ops/s
total: 266,506 ops in 5.01s
through: 405.84 mb/s
32k messages:
min: 12,077 ops/s
mean: 14,792 ops/s
median: 16,233 ops/s
total: 74,186 ops in 5.015s
through: 462.28 mb/s
Axon are not meant to combat zeromq nor provide feature parity, but provide a nice solution when you don't need the insane nanosecond latency or language interoperability that zeromq provides as axon do not rely on any third-party compiled libraries.
$ npm install
$ make test
MIT
FAQs
High-level messaging & socket patterns implemented in pure js
We found that pm2-axon demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.