Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple sequential errors cause multiple reconnection attempts #125

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion lib/eventsource.js
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
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