Skip to content

Commit

Permalink
Fix #17 CouchDB disconnected gracefully error on inactivity_ms (#18)
Browse files Browse the repository at this point in the history
* fix retry

* calculate attempt.maxDelay based on heartbeat too

* move minDelay and maxDelay patch to reconnect (extend does not overwrite fields
  • Loading branch information
Vasiliy Mikhaylovsky authored and jcrugzz committed Dec 24, 2018
1 parent 28026a3 commit 4529243
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ function ChangesStream (options) {
// Time to wait for a new change before we jsut retry a brand new request
this.inactivity_ms = options.inactivity_ms || 60 * 60 * 1000;
this.reconnect = options.reconnect || { minDelay: 100, maxDelay: 30 * 1000, retries: 5 };

// Patch min and max delay using heartbeat
var minDelay = Math.max(this.reconnect.minDelay, (this.heartbeat || DEFAULT_HEARTBEAT) + 5000)
var maxDelay = Math.max(minDelay + (this.reconnect.maxDelay - this.reconnect.minDelay), this.reconnect.maxDelay)
this.reconnect.minDelay = minDelay
this.reconnect.maxDelay = maxDelay

this.db = typeof options === 'string'
? options
: options.db;
Expand Down Expand Up @@ -151,7 +158,7 @@ ChangesStream.prototype.request = function () {
//
// Set a timer for the initial request with some extra magic number
//
this.timer = setTimeout(this.onTimeout.bind(this), (this.heartbeat || 30 * 1000) + 5000)
this.timer = setTimeout(this.onTimeout.bind(this), (this.heartbeat || DEFAULT_HEARTBEAT) + 5000)

this.req = http.request(opts);
this.req.setSocketKeepAlive(true);
Expand Down Expand Up @@ -205,6 +212,7 @@ ChangesStream.prototype.onTimeout = function () {
//
ChangesStream.prototype._readData = function (data) {
debug('data event fired from the underlying _changes response');
this.attempt = null;

this._buffer += this._decoder.write(data);

Expand Down Expand Up @@ -278,6 +286,7 @@ ChangesStream.prototype._onChange = function (change) {
//
ChangesStream.prototype._onError = function (err) {
this.attempt = this.attempt || extend({}, this.reconnect);

return back(function (fail, opts) {
if (fail) {
this.attempt = null;
Expand Down

0 comments on commit 4529243

Please sign in to comment.