From 7918fc5494fa9b8333d27e9de80b731382e8eb03 Mon Sep 17 00:00:00 2001 From: Todd Anderson Date: Wed, 23 Sep 2026 17:33:55 -0400 Subject: [PATCH] feat: allow a custom retry delay strategy to be provided --- README.md | 10 +++ lib/eventsource.js | 32 ++++++--- test/eventsource_test.js | 150 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 184 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 5bfde79..ceab01f 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,16 @@ var eventSourceInitDict = { }; ``` +### Providing a custom retry delay strategy + +Instead of configuring the built-in behavior, an application can take full control of retry timing by providing a `retryDelayStrategy` object in the init options. The object must implement three methods: + +* `nextRetryDelay(currentTimeMillis)`: called when a reconnection is about to be scheduled; returns the delay in milliseconds to wait before the next attempt. +* `setGoodSince(goodSinceTimeMillis)`: called when the first event is received on a connection, indicating that the connection is delivering data. +* `setBaseDelay(delayMillis)`: called when the server sends a `retry:` field; the value has already been validated and capped at one hour. + +When `retryDelayStrategy` is provided it fully replaces the built-in delay behavior, so `initialRetryDelayMillis`, `maxBackoffMillis`, `jitterRatio`, and `retryResetIntervalMillis` have no effect. Most applications should use the built-in options instead. + ### Configuring error retry behavior By default, to mimic the behavior of built-in browser `EventSource` implementations, `EventSource` will retry if a connection cannot be made or if the connection is broken (using whatever retry behavior you have configured, as described above)-- but if it connects and receives an HTTP error status, it will only retry for statuses 500, 502, 503, or 504; otherwise it will just raise an `error` event and disconnect, so the application is responsible for starting a new connection. diff --git a/lib/eventsource.js b/lib/eventsource.js index 4e68569..816440d 100644 --- a/lib/eventsource.js +++ b/lib/eventsource.js @@ -21,6 +21,10 @@ var carriageReturn = 13 const MAX_OVER_ALLOCATION = 1024 * 1024 // 1 MiB +// A server-directed retry: value larger than this is treated as this value; anything +// larger would be indistinguishable from the connection never resuming. +const MAX_SERVER_DIRECTED_RETRY_DELAY_MILLIS = 60 * 60 * 1000 // 1 hour + function hasBom (buf) { return bom.every(function (charCode, index) { return buf[index] === charCode @@ -76,12 +80,17 @@ function EventSource (url, eventSourceInitDict) { var data, eventName, eventId var reconnectUrl = null - var retryDelayStrategy = new retryDelay.RetryDelayStrategy( - config.initialRetryDelayMillis !== null && config.initialRetryDelayMillis !== undefined ? config.initialRetryDelayMillis : 1000, - config.retryResetIntervalMillis, - config.maxBackoffMillis ? retryDelay.defaultBackoff(config.maxBackoffMillis) : null, - config.jitterRatio ? retryDelay.defaultJitter(config.jitterRatio) : null - ) + var retryDelayStrategy + if (config.retryDelayStrategy) { + retryDelayStrategy = config.retryDelayStrategy + } else { + retryDelayStrategy = new retryDelay.RetryDelayStrategy( + config.initialRetryDelayMillis !== null && config.initialRetryDelayMillis !== undefined ? config.initialRetryDelayMillis : 1000, + config.retryResetIntervalMillis, + config.maxBackoffMillis ? retryDelay.defaultBackoff(config.maxBackoffMillis) : null, + config.jitterRatio ? retryDelay.defaultJitter(config.jitterRatio) : null + ) + } var goodSinceAnchored = false @@ -438,8 +447,14 @@ function EventSource (url, eventSourceInitDict) { eventId = value } } else if (field === 'retry') { - var retry = parseInt(value, 10) - if (!Number.isNaN(retry)) { + // The SSE specification only allows this field to contain ASCII digits; any other + // value is ignored. The accepted value is capped so that a huge reconnection time + // cannot act as a permanent stop. + if (/^\d+$/.test(value)) { + var retry = parseInt(value, 10) + if (retry > MAX_SERVER_DIRECTED_RETRY_DELAY_MILLIS) { + retry = MAX_SERVER_DIRECTED_RETRY_DELAY_MILLIS + } self.reconnectInterval = retry retryDelayStrategy.setBaseDelay(retry) } @@ -506,6 +521,7 @@ var supportedOptions = [ 'maxBackoffMillis', 'method', 'proxy', + 'retryDelayStrategy', 'retryResetIntervalMillis', 'skipDefaultHeaders', 'withCredentials' diff --git a/test/eventsource_test.js b/test/eventsource_test.js index 17203a5..1a527a6 100644 --- a/test/eventsource_test.js +++ b/test/eventsource_test.js @@ -854,6 +854,155 @@ describe('retry delay', () => { } ) }) + + it('applies a valid retry: value to subsequent reconnect delays', async () => { + await withServer(async server => { + let connection = 0 + server.byDefault((req, res) => { + connection++ + res.writeHead(200, { 'Content-Type': 'text/event-stream' }) + if (connection === 1) { + res.write('retry: 25\ndata: x\n\n') + } + setTimeout(() => res.destroy(), 30) + }) + + await withEventSource(server, { initialRetryDelayMillis: 1 }, async es => { + const delays = new AsyncQueue() + es.onretrying = event => delays.add(event.delayMillis) + assert.equal(await delays.take(), 25) + }) + }) + }) +}) + +describe('custom retry delay strategy', () => { + function stubStrategy (fixedDelay) { + return { + nextRetryDelayCalls: [], + goodSinceCalls: [], + baseDelayCalls: [], + nextRetryDelay: function (now) { + this.nextRetryDelayCalls.push(now) + return fixedDelay + }, + setGoodSince: function (t) { + this.goodSinceCalls.push(t) + }, + setBaseDelay: function (ms) { + this.baseDelayCalls.push(ms) + } + } + } + + it('is used for reconnect delays in place of the built-in behavior', async () => { + const strategy = stubStrategy(7) + await withServer(async server => { + server.byDefault(TestHttpHandlers.respond(500)) + + await withEventSource(server, { retryDelayStrategy: strategy }, async es => { + const delays = new AsyncQueue() + es.onretrying = event => delays.add(event.delayMillis) + + assert.equal(await delays.take(), 7) + assert.equal(await delays.take(), 7) + assert.ok(strategy.nextRetryDelayCalls.length >= 2) + }) + }) + }) + + it('ignores the built-in retry delay options when a strategy is provided', async () => { + const strategy = stubStrategy(7) + await withServer(async server => { + server.byDefault(TestHttpHandlers.respond(500)) + + await withEventSource(server, { retryDelayStrategy: strategy, initialRetryDelayMillis: 500, jitterRatio: 0.5 }, async es => { + const delays = new AsyncQueue() + es.onretrying = event => delays.add(event.delayMillis) + assert.equal(await delays.take(), 7) + assert.equal(await delays.take(), 7) + }) + }) + }) + + it('receives the good-since time once per connection, on the first event', async () => { + const strategy = stubStrategy(1) + await withServer(async server => { + let connection = 0 + server.byDefault((req, res) => { + connection++ + res.writeHead(200, { 'Content-Type': 'text/event-stream' }) + res.write('data: a\n\n') + if (connection === 1) { + res.write('data: b\n\n') + } + setTimeout(() => res.destroy(), 50) + }) + + await withEventSource(server, { retryDelayStrategy: strategy }, async es => { + const messages = startMessageQueue(es) + await messages.take() + await messages.take() + await messages.take() + assert.equal(strategy.goodSinceCalls.length, 2) + }) + }) + }) + + it('records exactly one failure when a read timeout is followed by the connection dropping', async () => { + const strategy = stubStrategy(10000) + await withServer(async server => { + server.byDefault((req, res) => { + // A stream that never sends anything, so the read timeout elapses. The timeout + // handler destroys the request, which produces a second failure signal from the + // closing connection; only one of the two may reach the strategy. + res.writeHead(200, { 'Content-Type': 'text/event-stream' }) + }) + + await withEventSource(server, { retryDelayStrategy: strategy, readTimeoutMillis: 50 }, async es => { + const retries = new AsyncQueue() + es.onretrying = event => retries.add(event.delayMillis) + + assert.equal(await retries.take(), 10000) + await sleepAsync(100) + assert.ok(retries.isEmpty()) + assert.equal(strategy.nextRetryDelayCalls.length, 1) + }) + }) + }) + + it('receives a valid retry: value through setBaseDelay', async () => { + const strategy = stubStrategy(1) + await withServer(async server => { + server.byDefault(writeEvents(['retry: 3000\ndata: x\n\n'])) + await withEventSource(server, { retryDelayStrategy: strategy }, async es => { + await shouldReceiveMessages(es, [ { data: 'x' } ]) + assert.deepEqual(strategy.baseDelayCalls, [ 3000 ]) + }) + }) + }) + + it('ignores retry: values that are not entirely digits', async () => { + const strategy = stubStrategy(1) + await withServer(async server => { + server.byDefault(writeEvents(['retry: -5000\nretry: 12abc\nretry: 1e3\ndata: x\n\n'])) + await withEventSource(server, { retryDelayStrategy: strategy }, async es => { + await shouldReceiveMessages(es, [ { data: 'x' } ]) + assert.deepEqual(strategy.baseDelayCalls, []) + }) + }) + }) + + it('caps retry: values at one hour', async () => { + const strategy = stubStrategy(1) + await withServer(async server => { + server.byDefault(writeEvents(['retry: 7200000\ndata: x\n\n'])) + await withEventSource(server, { retryDelayStrategy: strategy }, async es => { + await shouldReceiveMessages(es, [ { data: 'x' } ]) + assert.deepEqual(strategy.baseDelayCalls, [ 3600000 ]) + }) + }) + }) }) describe('readyState', function () { @@ -1275,6 +1424,7 @@ describe('EventSource object', function () { assert.equal(true, EventSource.supportedOptions.https) assert.equal(true, EventSource.supportedOptions.method) assert.equal(true, EventSource.supportedOptions.proxy) + assert.equal(true, EventSource.supportedOptions.retryDelayStrategy) assert.equal(true, EventSource.supportedOptions.skipDefaultHeaders) assert.equal(true, EventSource.supportedOptions.withCredentials) })