Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
32 changes: 24 additions & 8 deletions lib/eventsource.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -506,6 +521,7 @@ var supportedOptions = [
'maxBackoffMillis',
'method',
'proxy',
'retryDelayStrategy',
'retryResetIntervalMillis',
'skipDefaultHeaders',
'withCredentials'
Expand Down
150 changes: 150 additions & 0 deletions test/eventsource_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down Expand Up @@ -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)
})
Expand Down
Loading