diff --git a/.changeset/clamp-retry-interval.md b/.changeset/clamp-retry-interval.md new file mode 100644 index 0000000..d4ffc3a --- /dev/null +++ b/.changeset/clamp-retry-interval.md @@ -0,0 +1,5 @@ +--- +"eventsource": patch +--- + +Clamp the server-sent `retry` value to the maximum timer delay, so a very large value no longer causes a reconnect attempt every millisecond diff --git a/src/EventSource.ts b/src/EventSource.ts index 4f6eac6..31ae1ea 100644 --- a/src/EventSource.ts +++ b/src/EventSource.ts @@ -656,7 +656,8 @@ class EventSourceImpl extends EventTarget implements EventSource { * @internal */ #onRetryChange = (value: number) => { - this.#reconnectInterval = value + // Timers treat delays above 2^31-1 ms as 1ms, so clamp to avoid a tight reconnect loop + this.#reconnectInterval = Math.min(value, 2147483647) } /** diff --git a/test/client.test.ts b/test/client.test.ts index 797a169..e362cca 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -1122,6 +1122,41 @@ test('[NON-SPEC] custom `maxBufferSize` fails connection on parser buffer overfl await deferClose(es) }) +test('[NON-SPEC] clamps an oversized `retry` value so the reconnection delay does not overflow', async () => { + const url = `${serverUrl}/` + let fetchCount = 0 + + const retryFetch: FetchLike = async () => { + fetchCount++ + return { + body: new ReadableStream({ + start(controller) { + const encoder = new TextEncoder() + // Larger than the 2^31-1 ms maximum that timers accept, which would otherwise be + // treated as a 1ms delay and cause a tight reconnect loop + controller.enqueue(encoder.encode('retry: 2147483648\n')) + controller.enqueue(encoder.encode('data: hello\n\n')) + controller.close() + }, + }), + redirected: false, + status: 200, + headers: new Headers({'content-type': 'text/event-stream'}), + url, + } + } + + const onError = getCallCounter({name: 'onError'}) + const es = new OurEventSource(url, {fetch: retryFetch}) + + es.addEventListener('error', onError.listener) + await onError.waitForCallCount(1) + + await new Promise((resolve) => setTimeout(resolve, 250)) + expect(fetchCount, 'reconnect attempts').toBe(1) + await deferClose(es) +}) + test('[NON-SPEC] unrefs the reconnection timer where supported, so it does not keep the event loop alive', async () => { // Browsers return numeric timer handles, so there is nothing to unref there. const probe = setTimeout(() => {}, 0)