Skip to content

Commit e2f02a7

Browse files
committed
fix: eventsource does not reconnect on network error
1 parent edf9b3f commit e2f02a7

File tree

3 files changed

+21
-6
lines changed

3 files changed

+21
-6
lines changed

lib/web/eventsource/eventsource.js

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -231,12 +231,9 @@ class EventSource extends EventTarget {
231231

232232
// 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection.
233233
const processEventSourceEndOfBody = (response) => {
234-
if (isNetworkError(response)) {
235-
this.dispatchEvent(new Event('error'))
236-
this.close()
234+
if (!isNetworkError(response)) {
235+
return this.#reconnect()
237236
}
238-
239-
this.#reconnect()
240237
}
241238

242239
// 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody...

lib/web/eventsource/util.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ function isASCIINumber (value) {
2626
// https://github.com/nodejs/undici/issues/2664
2727
function delay (ms) {
2828
return new Promise((resolve) => {
29-
setTimeout(resolve, ms).unref()
29+
setTimeout(resolve, ms)
3030
})
3131
}
3232

test/eventsource/eventsource-connect.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const events = require('node:events')
55
const http = require('node:http')
66
const { test, describe } = require('node:test')
77
const { EventSource } = require('../../lib/web/eventsource/eventsource')
8+
const { randomInt } = require('node:crypto')
89

910
describe('EventSource - sending correct request headers', () => {
1011
test('should send request with connection keep-alive', async () => {
@@ -181,4 +182,21 @@ describe('EventSource - received response must have content-type to be text/even
181182
server.close()
182183
}
183184
})
185+
186+
test('should try to connect again if server is unreachable', async () => {
187+
const domain = 'bad.n' + randomInt(1e10).toString(36) + '.proxy'
188+
189+
const eventSourceInstance = new EventSource(`http://${domain}`)
190+
191+
const onerrorCalls = []
192+
eventSourceInstance.onerror = (error) => {
193+
onerrorCalls.push(error)
194+
}
195+
196+
await new Promise(resolve => setTimeout(resolve, 8000))
197+
198+
eventSourceInstance.close()
199+
200+
assert.strictEqual(onerrorCalls.length, 3)
201+
})
184202
})

0 commit comments

Comments
 (0)