Skip to content

Commit

Permalink
Prevent sequential errors from attempting multiple reconnections (#125)
Browse files Browse the repository at this point in the history
* prevent sequential errors from attempting multiple reconnections.

* clean up test

Co-authored-by: davidpatty <dpatty@qualtrics.com>
  • Loading branch information
2 people authored and rexxars committed Jan 25, 2020
1 parent 82d38b0 commit 7a4627a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/eventsource.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ function EventSource (url, eventSourceInitDict) {

var self = this
self.reconnectInterval = 1000
self.connectionInProgress = false

function onConnectionClosed (message) {
if (readyState === EventSource.CLOSED) return
Expand All @@ -58,9 +59,10 @@ function EventSource (url, eventSourceInitDict) {
reconnectUrl = null
}
setTimeout(function () {
if (readyState !== EventSource.CONNECTING) {
if (readyState !== EventSource.CONNECTING || self.connectionInProgress) {
return
}
self.connectionInProgress = true
connect()
}, self.reconnectInterval)
}
Expand Down Expand Up @@ -131,6 +133,7 @@ function EventSource (url, eventSourceInitDict) {
}

req = (isSecure ? https : http).request(options, function (res) {
self.connectionInProgress = false
// Handle HTTP errors
if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
_emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))
Expand Down
30 changes: 30 additions & 0 deletions test/eventsource_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -873,6 +873,36 @@ describe('Reconnection', function () {
}
})
})

it('attempts to reconnect are deduplicated on sequential erorrs', function (done) {
createServer(function (err, server) {
if (err) return done(err)
var events = ['data: Hello']
var eventsSent = 0
var errorOccurred = false
server.on('request', function (req, res) {
if (eventsSent === 0) {
var fn = writeEvents(events)
fn(req, res)
eventsSent++
// now cause a few errors
fn(req, res)
eventsSent++
} else {
assert.equal(EventSource.CONNECTING, es.readyState)
assert.ok(errorOccurred)
server.close(done)
}
})

var es = new EventSource(server.url)
assert.equal(EventSource.CONNECTING, es.readyState)
es.reconnectInterval = 0
es.onerror = function (err) {
errorOccurred = !!(errorOccurred || err)
}
})
})
})

describe('readyState', function () {
Expand Down

0 comments on commit 7a4627a

Please sign in to comment.