Turn any duplex stream into an actor
Actors are similar to traditional RPC however they are isolated units of communication, an actor receives and sends zero or more messages to and from its peer with bi-directional messaging. Typical RPC is done at the process-level, meaning in order to work with data coupled with an identifier such as a user id that the id must be passed each request, whereas an actor may retain this state.
$ npm install actorify
Simple hello world PING/PONG example:
var net = require'net';var actorify = require'actorify';// servernetcreateServervar actor = actorifysock;actoron'ping'console.log'PING';actorsend'pong';;listen3000;// clientvar sock = netconnect3000;var actor = actorifysock;setIntervalactorsend'ping';actoronce'pong'console.log'PONG';;300;
Sending a single request with multiple async responses, also illustrates how arguments may be primitives, json objects, or opaque binary such as sending an image over the wire for resizing, receiving multiple thumbnail blobs and their respective size:
var net = require'net';var actorify = require'actorify';// clientnetcreateServervar actor = actorifysock;var img = 'faux data';actoron'image thumbnails'console.log'%s byte image -> %s' imglength sizesjoin', ';sizesforEachactorsend'thumb' size 'thumb data';;;listen3000;// clientsetIntervalvar sock = netconnect3000;var actor = actorifysock;console.log'send image for thumbs';var img = 'faux image';actorsend'image thumbnails' img '150x150' '300x300';actoron'thumb'console.log'thumb: %s' size;;500;
You may also associate callbacks with an actor message, effectively turning it into a traditional RPC call:
actorsend'get user' 'tobi';actoron'get user'getUsernamereplyerr user;;;
When performing a request you may optionally timeout the response,
after which an
Error will be passed to the callback and any subsequent
response will be ignored.
The argument may be numeric milliseconds or represented as a string such as "5s", "10m", "1 minute", "30 seconds", etc. By default there is no timeout.
Stream errors are not handled, you must add an "error" listener
stream passed to actorify().
Benchmarks on my first generation MBP Retina with node 0.11.x. Real results are likely higher since having the producer on the same machine as the consumer makes results misleading.
With 64b messages:
min: 56,818 ops/smean: 159,207 ops/smedian: 138,888 ops/stotal: 1,376,188 ops in 8.644sthrough: 1.52 mb/s
With 1kb messages:
min: 56,179 ops/smean: 153,919 ops/smedian: 142,857 ops/stotal: 909,974 ops in 5.912sthrough: 150.31 mb/s
With 10kb messages:
min: 11,389 ops/smean: 64,167 ops/smedian: 64,102 ops/stotal: 352,025 ops in 5.486sthrough: 626.64 mb/s
With 32kb messages:
min: 7,032 ops/smean: 14,269 ops/smedian: 23,584 ops/stotal: 86,329 ops in 6.05sthrough: 445.91 mb/s