• Stars
    star
    121
  • Rank 293,924 (Top 6 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 13 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Wormwhole is a streaming message queue system for Node.JS focused on performance.

Wormhole

About

Wormhole is a message passing stream parser for Node.JS.

Wormhole is extremely simple and only has 1 main exported function. Once a stream has been passed to Wormhole, it takes over all data events and updates the write function to automatically encode all data given to it.

Install

Wormhole is ready to be installed from NPM, but may also be manually added to your project with git submodules. First CD to your project root. Ensure a directory named node_modules exists.

  • Install with NPM:

    • npm install wormhole
  • Install with GIT:

    • As a submodule:
      • git submodule add git://github.com/aikar/wormhole node_modules/wormhole
      • git submodule update --init --recursive

Update from 2.x to 3.x

If your coming from 2.x, part of the 2.x update added error as the first param to the callbacks.

This has been reverted in 3.x due to the introduction of channels, and now errors fire on the '__error__' channel.

You also now need to pass a channel to Wormhole init call, AND to write() calls, see below.

Usage

Wormhole(stream, channel, callback)

To use Wormhole, simply require it and pass it an instance of net.Stream, a channel to receive events on (call Wormhole multiple times to specify multiple channels) and what function to execute for that channel.

and a callback for messages with function fn(message).

var Wormhole = require('wormhole');
var stdin = process.stdin;
stdin.resume();
Wormhole(stdin, 'channelToReceiveOn', function(msg, fd) {
  // Messages here
});

stream.write(channel, message)

To write data, pass a channel and the message (objects is fine)

var Wormhole = require('wormhole');

net.createServer(function (client) {
    Wormhole(client, 'chat', function (msg) {
        // All messages received from client over chat channel, such as
        // {hello: 'World'}
    });
    
    Wormhole(client, 'auth', function (msg) {
        // All messages received from client, such as
        // {hello: 'World'}
        if (msg.user == 'foo' && msg.pass == 'bar') {
           client.write('auth', {auth: 'Thank you for logging in'});
        }
    });
    
    // client.write now overloaded to encode data.
    client.write('auth', {auth: 'Please login!'});
    client.write('chat', {greet: 'Welcome to our server!'});
}).listen(2122);
var client = net.createConnection(2122, function() {
    Wormhole(client, 'chat', function (err, msg) {
        // Messages received from server, such as
        // {greet: 'Welcome to our server!'}
    });
    Wormhole(client, 'auth', function (err, msg) {
        // Messages received from server on auth channel, such as
        // {auth: 'Please login!'}
        // {auth: 'Thank you for logging in!'}
    });
    client.write('auth', {user: 'foo', pass: 'bar'});
    client.write('chat', {hello: 'World'});
});

If you do not expect to receive messages, you still must call Wormhole with the net.Stream but you do not need to pass it a callback or channel, like so:

var Wormhole = require('wormhole');
var client = net.Stream(1); // stream to STDOUT;
Wormhole(client);
client.write('foobar', {foo: 'bar'});

The Wormhole function overwrites the .write function to encode the data.

stream.writeFd(channel, data, fd)

You may also send a file descriptor over a unix socket. This is the same as write(), except that your callback will have a 2nd argument

process.stdin.resume();
var Wormhole = require('wormhole');
Wormhole(process.stdin, "clients", function(msg, fd) {
    console.log("Info about this client:", conn);
    var conn = new net.Socket(fd);
    conn.resume();
    Wormhole(conn);
    conn.write('foo', 'bar');
});

Now you can do this in a parent process

var net = require('net');
var netb = process.binding('net');
var pair = netb.socketpair();
var cp = require('child_process');
var child = cp.spawn(process.execPath,
    ['foo.js'],  // filename for above.
    {
        customFds: [pair[1], -1, -1]
    }
);

child.stdin = new net.Stream(pair[0], 'unix');
child.stdin.resume();

Wormhole(child.stdin);

child.stdin.write("fdchannel", {foo:'bar'}, )

net.createServer(function(conn) {
    child.stdin.write("clients", conn, conn.fd);
}).listen(1020);

Now anytime someone connects to port 1020 on the parent process, the CHILD will receive the FD and be able to send messages directly over the connection without having to do IPC to the parent.

Multiple Receiving Callbacks

Wormhole also has the ability to register more than 1 function per channel. It will execute them in the order they were defined, and stop if any function returns a truthy value.

Wormhole(recv, 'foo', function(msg) {
    console.log("msg handler 1")
});

Wormhole(recv, 'foo', function(msg) {
    console.log("msg handler 2")
    return 1;
});

Wormhole(recv, 'foo', function(msg) {
    console.log("msg handler 3")
});


// send some data to recv on channel foo

This will print msg handler 1, msg handler 2, but not print msg handler 3.

you will likely always want to return true if you know youve processed the message.

Special Channels

__error__

2.x introduced the node style fn(err, ...) callback style. This has been removed in 3.x and gone back to fn(msg) style, with errors now firing on their own channel.

All errors will fire on the __error__ channel, so listen like this:

Wormhole(stream, '__error__', function(err) {
    console.error("Error received: ", err.msg);
    console.error(err.stack);
});

__unknown__

If you receive data on a channel you have not set up a callback function for, it will be sent to the __unknown__ channel. It acts as a catch all for unknows.

To better debug what channel was sent, the channel is passed as the 3rd argument

Wormhole(stream, '__unknown__', function(msg, fd, channel) {
    console.log("Received message on unknown channel", channel,":", msg);
});

*

If you pass * as a channel name, this function will catch ALL messages, including ones already processed by another function or __unknown__ channel!

As stated above in the "Multiple Receive Callbacks" section, return true from a function to not execute any more functions if the data is truely processed!

Tests

Wormhole uses the Vows test suite, but is designed to be triggered with my test runner.

npm install testrunner -g then type runtest

Benchmarks

There is a benchmark script in the examples folder to benchmark receiving messages.

Sending bottlenecks the current benchmark, but on a 3.4ghz CPU using 3 cores (2 sending, 1 receiving), with a small message I was able to get up to 310k messages per second.

Contributing

If you would like to contribute, please fork the project on github, make changes and submit pull requests back to me.

Please follow my same coding styles (spaces, no tabs!) and add new test for new functionality.

Please note, that changes may not affect the performance of Wormhole or it will not be accepted!

License

The MIT License

Copyright (c) 2011 Daniel Ennis [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

commands

Java Command Dispatch Framework - (Bukkit, Spigot, Paper, Sponge, Bungee, JDA, Velocity supported, generically usable anywhere)
Java
557
star
2

TaskChain

TaskChain Control Flow framework. Helps facilitate running tasks on an application's "Main Thread" (such as a game), and tasks off the main (async).
Java
202
star
3

timings

Source to the Aikar's Minecraft Timings Viewer
JavaScript
197
star
4

db

Aikar's Intuitive JDBC Database Wrapper - A clean and intuitive API for Java to remove JDBC boilerplate.
Java
65
star
5

autoloader

A Node.JS Module Autoloader
JavaScript
30
star
6

traceur

Traceur support for Node.JS
JavaScript
27
star
7

minecraft-timings

A Library to implement against Minecraft Timings - [V1 (Spigot), V2 (Paper)], and gracefully do nothing if no timings is supported.
Java
23
star
8

SigScan

Old project used for Final Fantasy XI Windower project. Allows you to use byte signatures to dynamically locate memory addresses during program runtime. Note: This is no longer maintained and is only here for reference. Please fork if you have improvements
C++
19
star
9

fastutil-lite

minimal fastutil classes
Java
16
star
10

paratask

Java Parallel Task Manager
Java
15
star
11

AdvancementCommand

Run commands (with potentially elevated permissions) on earning an advancement
Java
13
star
12

locales

A Java Locale Manager that supports managing multiple languages and contextual locale preference (IE: Different players on a multiplayer game server)
Java
12
star
13

magic

Magic is a utility library for Node.JS to provide V8 Interceptor objects in order to get the same functionality as PHP's __get and __set. Magic is designed to let developers write promise based functionality in a better syntax without function calls.
JavaScript
11
star
14

Bukkit

Java
10
star
15

nova

Nova templating engine for Node.JS
JavaScript
8
star
16

streamchat

Aikar's stream chat bridge - NGINX RTMP Split Stream conf: https://gist.github.com/aikar/937ae21ad9bc9600269cfbb4a1b1e96f
JavaScript
8
star
17

FairNaturalSpawns

Improves natural spawning behavior on Paper by also reducing spawns for farms to give everyone a fair shot at monsters.
Java
7
star
18

util

A collection of Java Classes and Utils I have wrote
Java
7
star
19

cosmos

A distributed event driven and RPC based application framework for Node.JS
6
star
20

objectsm

JS Object Serializer/Deserializer to convert raw JS objects back into class/constructor form
JavaScript
5
star
21

webpack-auto-clean-build-plugin

Automatically remove old assets after each build in webpack watch mode
JavaScript
5
star
22

nope

Node.JS OOP System
JavaScript
4
star
23

aurora

A beautiful JavaScript Environment... Traceur + Streamline. Aurora is a development tool to compile your Traceur and Streamline syntax quickly for you in an easy to manage way, and the users of your code do not depend on installing either module.
JavaScript
4
star
24

FixDoubleLogins

Should fix double login issues on Minecraft 1.8
Java
4
star
25

cleaner

Abstraction around sun.misc.Cleaner and java.lang.ref.Cleaner so you can support Java 8 and 9+ without worry.
Java
4
star
26

apatch

Apply Patch super script - uses git am -3 with wiggle fallback to best apply a patch file to source code
Shell
4
star
27

barenpm

An alternative npm modules installer that provides clean unsymlinked installations. Also is designed to target installing into a projects library folder instead of as a global module.
JavaScript
4
star
28

node-markov

Generate markov chains for chatbots in node
JavaScript
3
star
29

ProfileCache

Cache Mojang Profile API calls to a shared cache so multiple servers on same machine don't get rate limited
Java
3
star
30

ffxiv-tex-converter

Python
2
star
31

create-flow-pkg

Create a Facebook Flow ready skeleton library or application with Babel
JavaScript
2
star
32

bufferlog

Maintain a log of binary buffers to disk that can be replayed on demand. Similar technique used by MySQL BinLogs and Apache Kafka.
JavaScript
2
star
33

nodeib

Node.JS IRC Bot System
JavaScript
1
star
34

react-parent-context

Access the context of parent React Components
JavaScript
1
star
35

testrunner

Runs test...
JavaScript
1
star
36

postfix-manager

Web based admin panel for managing aliases, allowing domain level delegation.
PHP
1
star
37

node-beam

Fork of NPM node-beam - couldn't find a repo for this. Uses WS 0.8 for node 4. --- NOT AFFILIATED WITH IFDevelopment
JavaScript
1
star
38

aikar

1
star
39

inthashmap

place to store this minimal int hashmap incase i ever want to just publish an artifact
Java
1
star
40

objectproxy

Enables you to have a proxy object that lets you call an object/function over a TCP stream.
JavaScript
1
star