Skip to content

Commit 7a4627a

Browse files
dpattydavidpatty
authored andcommitted
Prevent sequential errors from attempting multiple reconnections (#125)
* prevent sequential errors from attempting multiple reconnections. * clean up test Co-authored-by: davidpatty <[email protected]>
1 parent 82d38b0 commit 7a4627a

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

lib/eventsource.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ function EventSource (url, eventSourceInitDict) {
4545

4646
var self = this
4747
self.reconnectInterval = 1000
48+
self.connectionInProgress = false
4849

4950
function onConnectionClosed (message) {
5051
if (readyState === EventSource.CLOSED) return
@@ -58,9 +59,10 @@ function EventSource (url, eventSourceInitDict) {
5859
reconnectUrl = null
5960
}
6061
setTimeout(function () {
61-
if (readyState !== EventSource.CONNECTING) {
62+
if (readyState !== EventSource.CONNECTING || self.connectionInProgress) {
6263
return
6364
}
65+
self.connectionInProgress = true
6466
connect()
6567
}, self.reconnectInterval)
6668
}
@@ -131,6 +133,7 @@ function EventSource (url, eventSourceInitDict) {
131133
}
132134

133135
req = (isSecure ? https : http).request(options, function (res) {
136+
self.connectionInProgress = false
134137
// Handle HTTP errors
135138
if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
136139
_emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))

test/eventsource_test.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -873,6 +873,36 @@ describe('Reconnection', function () {
873873
}
874874
})
875875
})
876+
877+
it('attempts to reconnect are deduplicated on sequential erorrs', function (done) {
878+
createServer(function (err, server) {
879+
if (err) return done(err)
880+
var events = ['data: Hello']
881+
var eventsSent = 0
882+
var errorOccurred = false
883+
server.on('request', function (req, res) {
884+
if (eventsSent === 0) {
885+
var fn = writeEvents(events)
886+
fn(req, res)
887+
eventsSent++
888+
// now cause a few errors
889+
fn(req, res)
890+
eventsSent++
891+
} else {
892+
assert.equal(EventSource.CONNECTING, es.readyState)
893+
assert.ok(errorOccurred)
894+
server.close(done)
895+
}
896+
})
897+
898+
var es = new EventSource(server.url)
899+
assert.equal(EventSource.CONNECTING, es.readyState)
900+
es.reconnectInterval = 0
901+
es.onerror = function (err) {
902+
errorOccurred = !!(errorOccurred || err)
903+
}
904+
})
905+
})
876906
})
877907

878908
describe('readyState', function () {

0 commit comments

Comments
 (0)