Coder Social home page Coder Social logo

reconnect-core's Introduction

reconnect-core

Generic stream reconnection module.

build status downloads

testling badge

Usage

Create a reconnect instance that keeps reconnecting over tcp:

var inject = require('reconnect-core');
var net = require('net');

// build you own reconnect module
var reconnect = inject(function () {
  // arguments are what you passed to .connect
  // this is the reconnect instance
  return net.connect.apply(null, arguments);
});

var re = reconnect({
  // all options are optional
  initialDelay: 1e3,
  maxDelay: 30e3,
  strategy: 'fibonacci',      // available: fibonacci, exponential, or a custom backoff instance (see below)
  failAfter: Infinity,
  randomisationFactor: 0,
  immediate: false
}, function (stream) {
  // stream = the stream you should consume
})
.on('connect', function (con) {
  // con = underlying connection  
})
.on('reconnect', function (n, delay) {
  // n = current number of reconnect  
  // delay = delay used before reconnect
})
.on('disconnect', function (err) {
  // err = possible error  
})
.on('error', function (err) {
  // never forget
})
.connect(port)

// disconnect
re.disconnect();

// ...or prevent reconnecting
re.reconnect = false;

// reset the internal backoff timer
re.reset();

Strategies

reconnect utilises the backoff library to control backoff behaviour. There are 2 options for choosing a strategy for your reconnect instance, pass one of the following to the strategy key when creating your instance:

  • Pass the string "fibonacci" or "exponential" to utilise these built-in backoff strategies, options passed to your reconnect instance will also be passed to these strategies.
  • Pass a Backoff instance, this allows you to customise your backoff strategy by implementing a Backoff Strategy.

An example using a custom strategy:

var inject = require('reconnect-core');
var backoff = require('backoff');
var net = require('net');

// build you own reconnect module
var reconnect = inject(function () {
  // arguments are what you passed to .connect
  // this is the reconnect instance
  return net.connect.apply(null, arguments);
});

// Reconnect every 10 seconds
var myStrategy = {
  next: function() { return 10e3; },
  reset: function() { }
}

var re = reconnect({
  strategy: new backoff.Backoff(myStrategy),
  failAfter: Infinity,
  immediate: false
}, function (stream) {
  // stream = the stream you should consume
})

Available implementations

Installation

With npm do:

npm install reconnect-core

Kudos

This has been refactored out of dominictarr's reconnect module.

License

(MIT)

Copyright (c) 2013 Julian Gruber <[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.

reconnect-core's People

Contributors

avvs avatar dominictarr avatar greenkeeperio-bot avatar juliangruber avatar piranna avatar ralphtheninja avatar rvagg avatar wayne-nlt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

reconnect-core's Issues

[docs] Why exposing the emitter to createConnection?

Hello,

Looking at index.js#L44, I was wondering why the emitter is passed as this to the createConnection method while calling it.

I have looked at both reconnect-net and reconnect-engine and I do not see when the this as an event emitter is used in both contexts.

It seems that exposing this inner emitter is intentional as it is tested here but the test does not tell much about its usage.

Can you please detail which use cases it pertains to?

what is reconnect module?

sorry for question to issue.
i'm using some node module(xmpp-core, xmpp-server, etc).
and these modules are use reconnect-core.

so, i setted up reconnect option true in server options.
and below is code

client.on("reconnect", function(dt1, dt2) {
    system.debug("reconnect", client.uid, client.name, dt1, dt2);
});
  • question
    reconnect event has fired after socket close. ( below is sample console )
    value 0 retrycount, value 1000 delay
close f5bdb812-70d4-11e5-87cf-08002784a403,test-01
reconnect f5bdb812-70d4-11e5-87cf-08002784a403,test-01, 0, 1000
  • question
  • sometimes client.uid, client.name is null. maybe i think, socket instance has changed.
reconnect null, null, 0, 1000
  • question
    when 'reconnect' event has fired exactly?

Infinite loop if no 'error' event is registered

In an error occurs on underlying transport, on line

emitter.emit('error', err)
it emits an 'error' event, but Node.js EventEmitter has the default behaviour that if an 'error' event is not registered it's thrown, so onDisconnect(err) on the next line is not being called. The error it's already being notified as the reason why it was disconnected so listening to the 'disconnect' event is just enought, so I think it's just enought to wrap the emitter.emit('error', err) on an empty try-catch and keep going.

Force Try Reconnect

Hi,

Maybe I'm just not understanding how to do it, but everything I've tried has resulted with multiple connections...

What I'm interested in is letting a connection back-off until it's only trying to reconnect every 30 secs or 5 mins or whatever - but have the option of forcing a reboot of that back-off at some point (i.e. not worry about the connection again until some user tries to connect to it).

I guess I could destroy & re-init the whole reconnect module, but I feel like this use case is/should be already taking care of by the module itself.

Am I missing something?

Thanks!
Al

An option to tell the module not the reconnect

This would be helpful if you know the server will close the connection and you don't want to reconnect anymore. Like assigning a property to the instance instead of the emitter. Unless the emitter will be exposed to set the connected property to false.

Write after end error when piping the stream you should consume

When I pipe the stream I should consume, I get an Error: write after end after a reconnect.

The problem can be replicated using the code below:

inject       = require "reconnect-core"
net          = require "net"
{ Writable } = require "stream"

class WS extends Writable
  constructor: ->
    super

  _write: (chunk, encoding, cb) ->
    console.log "chunk", chunk.toString()
    cb()

ws = new WS
ws.on "to-disk", (data) ->
  console.log data.toString()

server = net.createServer  (client) ->
  client.write "Hello?"

  setTimeout ->
    # kill the client here
    client.destroy()
  , 2000

server.listen 1337

reconnect = inject ->
  net.connect.apply null, arguments

re = reconnect {}, (stream) ->
  # consume the stream
  stream.pipe ws
  # stream.on "data", (data) -> console.log "data", data.toString()

re
  .on 'connect', (con) ->
    console.log 'connect'
  .on 'reconnect', (n, delay) ->
    console.log 'reconnect', n, delay
   .on 'disconnect', (error) ->
    console.log 'disconnect', error
  .connect 1337

When I change stream.pipe ws to stream.on "data", (data) -> console.log "data", data.toString() (stream fallback mode) it does reconnect.

Asynchronous connection procedures.

Hi. I want to have a reconnecting behaviour that uses Seaport as the middle man; I give it a seaport port and host and a service name and version and it will reconnect to the server over seaport using ports.get (so it waits for a network service to become available).

Only, the callback given to reconnect-core is synchronous, it expects a net.Socket (or the like?) to be returned.

Would it be possible to have e.g.

inject(function(port, host, cb) {
  doThings(function() {
    cb(null, net.connect(port, host));
  });
});

?

Cheers,

Tom

disconnect() call backoffMethod.backoff();

It might be practical for the emitter.disconnect() method to call backoff(). A use case might be that you want to teardown a test and disconnect all clients as well as close all servers they are connected to; If the server closes before the client, the client will get stuck trying to reconnect to it. Would you be open to a patch for this?

Unhandled "error" event

I'm trying to use the latest version of reconnect-core with tls, but keep getting an unhandled "error" event message.

When I try to use version ~0.0.1 of reconnect-core, it works. I also noticed that libraries such as reconnect-net use an earlier version of reconnect-core.

Here is my code:

var tls = require('tls');
var inject = require('reconnect-core');
var slice = [].slice;

module.exports = inject(function(){
    var args = slice.call(arguments);
    var tlsStream = tls.connect.apply(tls, args);
    tlsStream.on('secureConnect', function(){
        tlsStream.emit('connect');
    });
    return tlsStream;
});

And here is the error I get:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:904:11)
    at Object.afterConnect [as oncomplete] (net.js:895:19)

Allow custom backoff strategy

Hi There,
It would be really handy for our product if we could set a custom backoff strategy.
I'm thinking this should be pretty straight forward to implement, we could look at the type of the type option passed in, if it is a string, use one of the backoff built in strategies. If it is a function, assume it is a backoff strategy, and create a new backoff instance that utilises that.

I'm happy to help out with the code if you think this is a valid idea.
Thanks,
Wayne

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.