@fastify/sse 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/dependabot.yml +42 -2
- package/.github/workflows/ci.yml +6 -1
- package/.github/workflows/lock-threads.yml +19 -0
- package/LICENSE +22 -0
- package/README.md +149 -40
- package/bench/accept-header.js +344 -0
- package/bench/in-context.js +210 -0
- package/benching.md +106 -0
- package/eslint.config.js +5 -2
- package/examples/basic.js +130 -88
- package/examples/manual-streaming.js +81 -0
- package/index.js +355 -84
- package/package.json +13 -12
- package/test/basic.test.js +264 -16
- package/test/custom-headers.test.js +0 -6
- package/test/imports.test.js +50 -0
- package/test/lifecycle.test.js +0 -10
- package/test/manual.test.js +205 -0
- package/test/send-headers.test.js +263 -0
- package/types/index.d.ts +56 -11
- package/types/index.tst.ts +233 -0
- package/.github/.stale.yml +0 -21
- package/.github/tests_checker.yml +0 -8
- package/.github/workflows/package-manager-ci.yml +0 -24
- package/test-types/index.test-d.ts +0 -192
package/index.js
CHANGED
|
@@ -1,11 +1,239 @@
|
|
|
1
1
|
'use strict'
|
|
2
2
|
|
|
3
3
|
const fp = require('fastify-plugin')
|
|
4
|
+
const createError = require('@fastify/error')
|
|
4
5
|
const { Readable, Transform } = require('stream')
|
|
5
6
|
const { pipeline } = require('stream/promises')
|
|
6
7
|
|
|
7
|
-
const
|
|
8
|
-
|
|
8
|
+
const FST_ERR_SSE_UNKNOWN_KIND = createError(
|
|
9
|
+
'FST_ERR_SSE_UNKNOWN_KIND',
|
|
10
|
+
"@fastify/sse: unknown sse kind '%s'. Use 'only' (SSE-only route), 'dual' (route serves both SSE and non-SSE), 'manual' (handler decides at runtime, no Accept negotiation), or omit for back-compat."
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
const FST_ERR_SSE_INVALID_OPTION = createError(
|
|
14
|
+
'FST_ERR_SSE_INVALID_OPTION',
|
|
15
|
+
"@fastify/sse: unsupported value for route option 'sse': %s. Use true, 'dual', 'only', 'manual', or an options object."
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
const FST_ERR_SSE_LEGACY_MISUSE = createError(
|
|
19
|
+
'FST_ERR_SSE_LEGACY_MISUSE',
|
|
20
|
+
"@fastify/sse: route registered with { sse: true } received Accept '%s' (no explicit 'text/event-stream') " +
|
|
21
|
+
'and the handler then tried to use reply.sse. If this route only serves SSE, ' +
|
|
22
|
+
"register it with { sse: 'only' } so ambiguous Accept headers admit SSE per " +
|
|
23
|
+
'RFC 9110. If it serves both SSE and a non-SSE representation, register with ' +
|
|
24
|
+
"{ sse: 'dual' } and branch on the Accept header in the handler. " +
|
|
25
|
+
'(Underlying error: %s)'
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
const FST_ERR_SSE_CONNECTION_CLOSED = createError(
|
|
29
|
+
'FST_ERR_SSE_CONNECTION_CLOSED',
|
|
30
|
+
'SSE connection is closed'
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
// Character codes used by the Accept-header scanner. Hoisted to module scope
|
|
34
|
+
// so V8 treats them as constants and the tight loops below stay monomorphic.
|
|
35
|
+
const CC_SP = 32
|
|
36
|
+
const CC_HT = 9
|
|
37
|
+
const CC_COMMA = 44
|
|
38
|
+
const CC_SEMI = 59
|
|
39
|
+
const CC_EQ = 61
|
|
40
|
+
const CC_DOT = 46
|
|
41
|
+
const CC_ZERO = 48
|
|
42
|
+
const CC_LOWER_Q = 113
|
|
43
|
+
const CC_UPPER_Q = 81
|
|
44
|
+
|
|
45
|
+
function ciEqualsAt (s, start, end, lower) {
|
|
46
|
+
if (end - start !== lower.length) return false
|
|
47
|
+
for (let j = 0; j < lower.length; j++) {
|
|
48
|
+
let c = s.charCodeAt(start + j)
|
|
49
|
+
if (c >= 65 && c <= 90) c |= 32
|
|
50
|
+
if (c !== lower.charCodeAt(j)) return false
|
|
51
|
+
}
|
|
52
|
+
return true
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function isQValueZero (s, start, end) {
|
|
56
|
+
if (end <= start) return false
|
|
57
|
+
if (s.charCodeAt(start) !== CC_ZERO) return false
|
|
58
|
+
let i = start + 1
|
|
59
|
+
if (i < end && s.charCodeAt(i) === CC_DOT) {
|
|
60
|
+
i++
|
|
61
|
+
while (i < end) {
|
|
62
|
+
if (s.charCodeAt(i) !== CC_ZERO) return false
|
|
63
|
+
i++
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return i === end
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Determine whether the client's Accept header admits `text/event-stream`.
|
|
71
|
+
*
|
|
72
|
+
* Implements the RFC 9110 §12.5.1 precedence model for the media ranges that
|
|
73
|
+
* are relevant to SSE — `text/event-stream`, `text/*`, and `*\/*`. Other
|
|
74
|
+
* media-type parameters are ignored; only the `q` parameter is honored, and
|
|
75
|
+
* only the binary distinction `q=0` (explicit refuse) vs `q>0` (admit) is
|
|
76
|
+
* preserved. Fractional qvalues like `q=0.5` are treated identically to
|
|
77
|
+
* `q=1`: observably equivalent here because the function picks the winning
|
|
78
|
+
* media range by specificity, not by comparing fractional qvalues.
|
|
79
|
+
*
|
|
80
|
+
* Default (lenient) returns true when the header is missing, empty, or
|
|
81
|
+
* contains a matching range with quality > 0. The most specific matching
|
|
82
|
+
* range wins, so `*\/*, text/event-stream;q=0` correctly returns false.
|
|
83
|
+
*
|
|
84
|
+
* Pass `{ strict: true }` to require an explicit `text/event-stream` token
|
|
85
|
+
* with quality > 0; ambiguous headers (`*\/*`, `text/*`, missing) return
|
|
86
|
+
* false in strict mode.
|
|
87
|
+
*
|
|
88
|
+
* Hot paths (`text/event-stream`, `*\/*`, `text/*`) short-circuit before any
|
|
89
|
+
* scanning, so the common case is a single string-equality compare.
|
|
90
|
+
*
|
|
91
|
+
* @param {string|undefined} acceptHeader
|
|
92
|
+
* @param {{ strict?: boolean }} [options]
|
|
93
|
+
* @returns {boolean}
|
|
94
|
+
*/
|
|
95
|
+
function clientAcceptsSSE (acceptHeader, options) {
|
|
96
|
+
const strict = options !== undefined && options.strict === true
|
|
97
|
+
if (!acceptHeader) return !strict
|
|
98
|
+
|
|
99
|
+
// Hot path: the literal values that EventSource and common HTTP clients
|
|
100
|
+
// actually emit. Caught with a single ===, no allocation.
|
|
101
|
+
if (acceptHeader === 'text/event-stream') return true
|
|
102
|
+
if (!strict && (acceptHeader === '*/*' || acceptHeader === 'text/*')) return true
|
|
103
|
+
|
|
104
|
+
// Slow path: walk the header in place via charCodeAt. No .split(),
|
|
105
|
+
// no .toLowerCase(), no .trim(), no substrings allocated.
|
|
106
|
+
const len = acceptHeader.length
|
|
107
|
+
let bestSpec = -1
|
|
108
|
+
let bestRefused = false
|
|
109
|
+
let i = 0
|
|
110
|
+
|
|
111
|
+
while (i < len) {
|
|
112
|
+
while (i < len) {
|
|
113
|
+
const c = acceptHeader.charCodeAt(i)
|
|
114
|
+
if (c !== CC_SP && c !== CC_HT) break
|
|
115
|
+
i++
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const typeStart = i
|
|
119
|
+
while (i < len) {
|
|
120
|
+
const c = acceptHeader.charCodeAt(i)
|
|
121
|
+
if (c === CC_SEMI || c === CC_COMMA) break
|
|
122
|
+
i++
|
|
123
|
+
}
|
|
124
|
+
let typeEnd = i
|
|
125
|
+
while (typeEnd > typeStart) {
|
|
126
|
+
const c = acceptHeader.charCodeAt(typeEnd - 1)
|
|
127
|
+
if (c !== CC_SP && c !== CC_HT) break
|
|
128
|
+
typeEnd--
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
let spec = -1
|
|
132
|
+
if (ciEqualsAt(acceptHeader, typeStart, typeEnd, 'text/event-stream')) spec = 3
|
|
133
|
+
else if (!strict && ciEqualsAt(acceptHeader, typeStart, typeEnd, 'text/*')) spec = 2
|
|
134
|
+
else if (!strict && ciEqualsAt(acceptHeader, typeStart, typeEnd, '*/*')) spec = 1
|
|
135
|
+
|
|
136
|
+
let refused = false
|
|
137
|
+
if (spec === -1) {
|
|
138
|
+
// Non-matching entry: skip its parameters in one jump.
|
|
139
|
+
while (i < len && acceptHeader.charCodeAt(i) !== CC_COMMA) i++
|
|
140
|
+
} else {
|
|
141
|
+
// Spec note: per RFC 9110 §5.6.6, `parameter = parameter-name "="
|
|
142
|
+
// parameter-value` permits no OWS inside the parameter — only around
|
|
143
|
+
// the `;` separator. We honor the OWS-around-`;` case (which browsers
|
|
144
|
+
// emit as `; q=0.8`) but do not handle OWS adjacent to `=` or
|
|
145
|
+
// trailing OWS on the value/key (which would be malformed input
|
|
146
|
+
// anyway). Node's HTTP parser also strips leading + trailing OWS
|
|
147
|
+
// from the whole header value, so the only WS we see in production
|
|
148
|
+
// is OWS after `,` and after `;`.
|
|
149
|
+
while (i < len && acceptHeader.charCodeAt(i) === CC_SEMI) {
|
|
150
|
+
i++
|
|
151
|
+
while (i < len) {
|
|
152
|
+
const c = acceptHeader.charCodeAt(i)
|
|
153
|
+
if (c !== CC_SP && c !== CC_HT) break
|
|
154
|
+
i++
|
|
155
|
+
}
|
|
156
|
+
const keyStart = i
|
|
157
|
+
while (i < len) {
|
|
158
|
+
const c = acceptHeader.charCodeAt(i)
|
|
159
|
+
if (c === CC_EQ || c === CC_SEMI || c === CC_COMMA) break
|
|
160
|
+
i++
|
|
161
|
+
}
|
|
162
|
+
const keyEnd = i
|
|
163
|
+
|
|
164
|
+
if (i < len && acceptHeader.charCodeAt(i) === CC_EQ) {
|
|
165
|
+
i++
|
|
166
|
+
const valStart = i
|
|
167
|
+
while (i < len) {
|
|
168
|
+
const c = acceptHeader.charCodeAt(i)
|
|
169
|
+
if (c === CC_SEMI || c === CC_COMMA) break
|
|
170
|
+
i++
|
|
171
|
+
}
|
|
172
|
+
const valEnd = i
|
|
173
|
+
|
|
174
|
+
if (keyEnd - keyStart === 1) {
|
|
175
|
+
const kc = acceptHeader.charCodeAt(keyStart)
|
|
176
|
+
if ((kc === CC_LOWER_Q || kc === CC_UPPER_Q) &&
|
|
177
|
+
isQValueZero(acceptHeader, valStart, valEnd)) {
|
|
178
|
+
refused = true
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// text/event-stream with a non-refused qvalue has the maximum
|
|
186
|
+
// specificity; nothing later in the list can outrank it.
|
|
187
|
+
if (spec === 3 && !refused) return true
|
|
188
|
+
|
|
189
|
+
if (spec > bestSpec) {
|
|
190
|
+
bestSpec = spec
|
|
191
|
+
bestRefused = refused
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (i < len && acceptHeader.charCodeAt(i) === CC_COMMA) i++
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return bestSpec >= 0 && !bestRefused
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Resolve the `sse` field on route options into a normalized shape.
|
|
202
|
+
*
|
|
203
|
+
* - `sse: true` → kind 'legacy' (back-compat, strict gate + clearer
|
|
204
|
+
* error if the handler tries to use reply.sse on the
|
|
205
|
+
* fallback path)
|
|
206
|
+
* - `sse: 'dual'` → kind 'dual' (explicit dual-mode: strict gate, the
|
|
207
|
+
* handler is expected to serve a non-SSE response when
|
|
208
|
+
* reply.sse is undefined)
|
|
209
|
+
* - `sse: 'only'` → kind 'only' (SSE-only: lenient gate, returns 406
|
|
210
|
+
* Not Acceptable to clients that explicitly refuse SSE)
|
|
211
|
+
* - `sse: 'manual'` → kind 'manual' (no Accept negotiation: `reply.sse` is
|
|
212
|
+
* always attached and the handler decides at runtime
|
|
213
|
+
* whether to stream — by calling `reply.sse.*` — or to
|
|
214
|
+
* return a normal response. The connection is closed
|
|
215
|
+
* automatically when the handler resolves or throws.)
|
|
216
|
+
* - `sse: { ... }` → object form; same kinds via
|
|
217
|
+
* `kind: 'dual' | 'only' | 'manual'`, or `kind` omitted
|
|
218
|
+
* = 'legacy' for back-compat with existing
|
|
219
|
+
* `{ heartbeat, serializer, ... }` shapes
|
|
220
|
+
*/
|
|
221
|
+
function resolveSSEConfig (sseField) {
|
|
222
|
+
if (sseField === true) return { kind: 'legacy', options: {} }
|
|
223
|
+
if (sseField === 'dual') return { kind: 'dual', options: {} }
|
|
224
|
+
if (sseField === 'only') return { kind: 'only', options: {} }
|
|
225
|
+
if (sseField === 'manual') return { kind: 'manual', options: {} }
|
|
226
|
+
if (typeof sseField === 'object' && sseField !== null) {
|
|
227
|
+
const kind = sseField.kind ?? 'legacy'
|
|
228
|
+
if (kind !== 'legacy' && kind !== 'dual' && kind !== 'only' && kind !== 'manual') {
|
|
229
|
+
throw new FST_ERR_SSE_UNKNOWN_KIND(kind)
|
|
230
|
+
}
|
|
231
|
+
return { kind, options: sseField }
|
|
232
|
+
}
|
|
233
|
+
throw new FST_ERR_SSE_INVALID_OPTION(JSON.stringify(sseField))
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const MISSING_SSE_ERROR_PATTERN = /Cannot read prop(?:erties)? of undefined.*'(?:send|stream|keepAlive|close|sendHeaders|replay|onClose)'/
|
|
9
237
|
|
|
10
238
|
/**
|
|
11
239
|
* Format an SSE message according to the specification
|
|
@@ -84,35 +312,36 @@ function createSSETransformStream (options = {}) {
|
|
|
84
312
|
* SSE Context class for managing connection state
|
|
85
313
|
*/
|
|
86
314
|
class SSEContext {
|
|
315
|
+
#lastEventId
|
|
316
|
+
#isConnected
|
|
317
|
+
#keepAlive
|
|
318
|
+
#headersSent
|
|
319
|
+
|
|
87
320
|
constructor (options) {
|
|
88
321
|
this.reply = options.reply
|
|
89
|
-
this
|
|
90
|
-
this
|
|
91
|
-
this
|
|
92
|
-
this
|
|
322
|
+
this.#lastEventId = options.lastEventId || null
|
|
323
|
+
this.#isConnected = true
|
|
324
|
+
this.#keepAlive = false
|
|
325
|
+
this.#headersSent = false
|
|
93
326
|
this.heartbeatTimer = null
|
|
327
|
+
this.heartbeatInterval = options.heartbeatInterval
|
|
94
328
|
this.closeCallbacks = []
|
|
95
329
|
this.serializer = options.serializer
|
|
96
330
|
|
|
97
331
|
// Set up connection close handler
|
|
98
332
|
this.reply.raw.on('close', () => {
|
|
99
|
-
this
|
|
333
|
+
this.#isConnected = false
|
|
100
334
|
this.cleanup()
|
|
101
335
|
})
|
|
102
336
|
|
|
103
337
|
// Handle errors on the raw response to prevent uncaught exceptions
|
|
104
338
|
this.reply.raw.on('error', (error) => {
|
|
105
339
|
// Client disconnection is expected behavior, handle gracefully
|
|
106
|
-
this
|
|
340
|
+
this.#isConnected = false
|
|
107
341
|
this.cleanup()
|
|
108
342
|
// Log as info since client disconnections are normal
|
|
109
343
|
this.reply.log.info({ err: error }, 'SSE connection closed')
|
|
110
344
|
})
|
|
111
|
-
|
|
112
|
-
// Start heartbeat if enabled
|
|
113
|
-
if (options.heartbeatInterval > 0) {
|
|
114
|
-
this.startHeartbeat(options.heartbeatInterval)
|
|
115
|
-
}
|
|
116
345
|
}
|
|
117
346
|
|
|
118
347
|
/**
|
|
@@ -120,7 +349,7 @@ class SSEContext {
|
|
|
120
349
|
* @returns {string|null} The last event ID or null if not present
|
|
121
350
|
*/
|
|
122
351
|
get lastEventId () {
|
|
123
|
-
return this
|
|
352
|
+
return this.#lastEventId
|
|
124
353
|
}
|
|
125
354
|
|
|
126
355
|
/**
|
|
@@ -128,7 +357,15 @@ class SSEContext {
|
|
|
128
357
|
* @returns {boolean} True if connected, false otherwise
|
|
129
358
|
*/
|
|
130
359
|
get isConnected () {
|
|
131
|
-
return this
|
|
360
|
+
return this.#isConnected
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Checks if the connection should be kept alive after handler completion.
|
|
365
|
+
* @returns {boolean} True if connection should be kept alive
|
|
366
|
+
*/
|
|
367
|
+
get shouldKeepAlive () {
|
|
368
|
+
return this.#keepAlive
|
|
132
369
|
}
|
|
133
370
|
|
|
134
371
|
/**
|
|
@@ -136,19 +373,25 @@ class SSEContext {
|
|
|
136
373
|
* Without calling this, the connection will close after the handler returns.
|
|
137
374
|
*/
|
|
138
375
|
keepAlive () {
|
|
139
|
-
this
|
|
376
|
+
this.#keepAlive = true
|
|
140
377
|
}
|
|
141
378
|
|
|
142
379
|
/**
|
|
143
380
|
* Closes the SSE connection and performs cleanup.
|
|
144
381
|
* Safe to call multiple times.
|
|
382
|
+
*
|
|
383
|
+
* If no SSE data was ever written (i.e., headers were never committed as
|
|
384
|
+
* SSE), the raw response is left open so Fastify can serialize the
|
|
385
|
+
* handler's return value normally.
|
|
145
386
|
*/
|
|
146
387
|
close () {
|
|
147
|
-
if (!this
|
|
388
|
+
if (!this.#isConnected) return
|
|
148
389
|
|
|
149
|
-
this
|
|
390
|
+
this.#isConnected = false
|
|
150
391
|
this.cleanup()
|
|
151
|
-
this
|
|
392
|
+
if (this.#headersSent) {
|
|
393
|
+
this.reply.raw.end()
|
|
394
|
+
}
|
|
152
395
|
}
|
|
153
396
|
|
|
154
397
|
/**
|
|
@@ -165,28 +408,45 @@ class SSEContext {
|
|
|
165
408
|
* @param {Function} callback - Async function that receives the last event ID
|
|
166
409
|
*/
|
|
167
410
|
async replay (callback) {
|
|
168
|
-
if (!this
|
|
411
|
+
if (!this.#lastEventId) return
|
|
169
412
|
|
|
170
|
-
await callback(this
|
|
413
|
+
await callback(this.#lastEventId)
|
|
171
414
|
}
|
|
172
415
|
|
|
173
416
|
/**
|
|
174
417
|
* Sends HTTP headers for the SSE response if not already sent.
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
*
|
|
418
|
+
* Applies the SSE-specific response headers, transfers any headers set
|
|
419
|
+
* via reply.header(), and calls writeHead(200). Called automatically
|
|
420
|
+
* before the first SSE data is sent, but can also be called manually.
|
|
421
|
+
*
|
|
422
|
+
* Until this fires, the response is not yet committed as SSE — a handler
|
|
423
|
+
* that never writes SSE data will return through Fastify's normal
|
|
424
|
+
* serialization path.
|
|
179
425
|
*/
|
|
180
426
|
sendHeaders () {
|
|
181
|
-
if (!this
|
|
182
|
-
|
|
427
|
+
if (!this.#headersSent) {
|
|
428
|
+
this.reply.raw.setHeader('Content-Type', 'text/event-stream')
|
|
429
|
+
this.reply.raw.setHeader('Cache-Control', 'no-cache')
|
|
430
|
+
this.reply.raw.setHeader('Connection', 'keep-alive')
|
|
431
|
+
this.reply.raw.setHeader('X-Accel-Buffering', 'no') // Disable Nginx buffering
|
|
432
|
+
|
|
433
|
+
// Transfer headers set via reply.header() to the raw response
|
|
183
434
|
const replyHeaders = this.reply.getHeaders()
|
|
184
435
|
for (const [name, value] of Object.entries(replyHeaders)) {
|
|
185
436
|
this.reply.raw.setHeader(name, value)
|
|
186
437
|
}
|
|
187
438
|
|
|
188
439
|
this.reply.raw.writeHead(200)
|
|
189
|
-
this
|
|
440
|
+
this.#headersSent = true
|
|
441
|
+
|
|
442
|
+
// Start the heartbeat only once the response is committed as SSE.
|
|
443
|
+
// Deferring it until here means a handler that decorates reply.sse
|
|
444
|
+
// but ultimately returns a non-SSE response (e.g. a 'manual' route
|
|
445
|
+
// that branches on the request body) is never interrupted by a
|
|
446
|
+
// heartbeat write corrupting its payload.
|
|
447
|
+
if (this.heartbeatInterval > 0) {
|
|
448
|
+
this.startHeartbeat(this.heartbeatInterval)
|
|
449
|
+
}
|
|
190
450
|
}
|
|
191
451
|
}
|
|
192
452
|
|
|
@@ -197,8 +457,8 @@ class SSEContext {
|
|
|
197
457
|
* @throws {TypeError} If source type is invalid
|
|
198
458
|
*/
|
|
199
459
|
async send (source) {
|
|
200
|
-
if (!this
|
|
201
|
-
throw new
|
|
460
|
+
if (!this.#isConnected) {
|
|
461
|
+
throw new FST_ERR_SSE_CONNECTION_CLOSED()
|
|
202
462
|
}
|
|
203
463
|
|
|
204
464
|
// Handle single message
|
|
@@ -217,7 +477,7 @@ class SSEContext {
|
|
|
217
477
|
await pipeline(source, transform, this.reply.raw, { end: false })
|
|
218
478
|
} catch (error) {
|
|
219
479
|
// Distinguish between expected disconnection errors and unexpected errors
|
|
220
|
-
this
|
|
480
|
+
this.#isConnected = false
|
|
221
481
|
this.cleanup()
|
|
222
482
|
if (error && (error.code === 'ECONNRESET' || error.code === 'EPIPE')) {
|
|
223
483
|
this.reply.log.info({ err: error }, 'SSE stream ended (client disconnected)')
|
|
@@ -232,7 +492,7 @@ class SSEContext {
|
|
|
232
492
|
// Handle AsyncIterable
|
|
233
493
|
if (this.isAsyncIterable(source)) {
|
|
234
494
|
for await (const chunk of source) {
|
|
235
|
-
if (!this
|
|
495
|
+
if (!this.#isConnected) break
|
|
236
496
|
const formatted = formatSSEMessage(chunk, this.serializer)
|
|
237
497
|
await this.writeToStream(formatted)
|
|
238
498
|
}
|
|
@@ -249,8 +509,8 @@ class SSEContext {
|
|
|
249
509
|
* @throws {Error} If connection is closed
|
|
250
510
|
*/
|
|
251
511
|
stream () {
|
|
252
|
-
if (!this
|
|
253
|
-
throw new
|
|
512
|
+
if (!this.#isConnected) {
|
|
513
|
+
throw new FST_ERR_SSE_CONNECTION_CLOSED()
|
|
254
514
|
}
|
|
255
515
|
|
|
256
516
|
const transform = createSSETransformStream({ serializer: this.serializer })
|
|
@@ -273,7 +533,7 @@ class SSEContext {
|
|
|
273
533
|
*/
|
|
274
534
|
writeToStream (data) {
|
|
275
535
|
return new Promise((resolve, reject) => {
|
|
276
|
-
if (!this
|
|
536
|
+
if (!this.#isConnected) {
|
|
277
537
|
reject(new Error('SSE connection is closed'))
|
|
278
538
|
return
|
|
279
539
|
}
|
|
@@ -295,7 +555,7 @@ class SSEContext {
|
|
|
295
555
|
const onError = (err) => {
|
|
296
556
|
this.reply.raw.off('drain', onDrain)
|
|
297
557
|
// Handle all errors gracefully - client disconnection is normal
|
|
298
|
-
this
|
|
558
|
+
this.#isConnected = false
|
|
299
559
|
this.cleanup()
|
|
300
560
|
this.reply.log.info({ err }, 'SSE write ended')
|
|
301
561
|
resolve() // Resolve instead of reject for graceful handling
|
|
@@ -314,7 +574,7 @@ class SSEContext {
|
|
|
314
574
|
*/
|
|
315
575
|
startHeartbeat (interval) {
|
|
316
576
|
this.heartbeatTimer = setInterval(() => {
|
|
317
|
-
if (this
|
|
577
|
+
if (this.#isConnected) {
|
|
318
578
|
this.sendHeaders()
|
|
319
579
|
this.reply.raw.write(': heartbeat\n\n')
|
|
320
580
|
} else {
|
|
@@ -392,24 +652,58 @@ async function fastifySSE (fastify, opts) {
|
|
|
392
652
|
fastify.addHook('onRoute', (routeOptions) => {
|
|
393
653
|
if (!routeOptions.sse) return
|
|
394
654
|
|
|
655
|
+
const { kind, options: sseOptions } = resolveSSEConfig(routeOptions.sse)
|
|
395
656
|
const originalHandler = routeOptions.handler
|
|
396
|
-
const sseOptions = typeof routeOptions.sse === 'object' ? routeOptions.sse : {}
|
|
397
657
|
|
|
398
658
|
routeOptions.handler = async function sseHandler (request, reply) {
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
659
|
+
const acceptHeader = request.headers.accept
|
|
660
|
+
|
|
661
|
+
// Kind-specific gate.
|
|
662
|
+
// 'only' — SSE-only route. Lenient gate: any spec-compliant Accept
|
|
663
|
+
// admits SSE. Clients that explicitly refuse SSE get 406.
|
|
664
|
+
// 'dual' — Route serves both SSE and non-SSE on the same handler.
|
|
665
|
+
// Strict gate: only an explicit `text/event-stream` token
|
|
666
|
+
// admits SSE; everything else falls through to the
|
|
667
|
+
// handler, which is expected to serve a non-SSE response.
|
|
668
|
+
// 'legacy' — `sse: true` back-compat. Same routing as 'dual'. If
|
|
669
|
+
// the fallback handler then tries to use `reply.sse`
|
|
670
|
+
// (which is undefined because the gate refused), the
|
|
671
|
+
// plugin rethrows with a message that names
|
|
672
|
+
// `sse: 'only'` as the likely fix.
|
|
673
|
+
// 'manual' — No Accept negotiation at all. `reply.sse` is always
|
|
674
|
+
// attached and the handler decides at runtime whether to
|
|
675
|
+
// stream. This supports clients (OpenAI-style streaming
|
|
676
|
+
// APIs and other LLM endpoints) that signal streaming via
|
|
677
|
+
// the request body rather than the Accept header.
|
|
678
|
+
if (kind === 'only') {
|
|
679
|
+
if (!clientAcceptsSSE(acceptHeader)) {
|
|
680
|
+
return reply.code(406).type('application/json').send({
|
|
681
|
+
statusCode: 406,
|
|
682
|
+
error: 'Not Acceptable',
|
|
683
|
+
message: "This endpoint only produces 'text/event-stream'."
|
|
684
|
+
})
|
|
685
|
+
}
|
|
686
|
+
// Fall through to SSE setup.
|
|
687
|
+
} else if (kind === 'dual' || kind === 'legacy') {
|
|
688
|
+
if (!clientAcceptsSSE(acceptHeader, { strict: true })) {
|
|
689
|
+
if (kind === 'legacy') {
|
|
690
|
+
try {
|
|
691
|
+
return await originalHandler.call(this, request, reply)
|
|
692
|
+
} catch (err) {
|
|
693
|
+
if (err instanceof TypeError && MISSING_SSE_ERROR_PATTERN.test(err.message)) {
|
|
694
|
+
throw new FST_ERR_SSE_LEGACY_MISUSE(acceptHeader || '<missing>', err.message)
|
|
695
|
+
}
|
|
696
|
+
throw err
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
// 'dual' — handler intentionally handles the fallback.
|
|
700
|
+
return await originalHandler.call(this, request, reply)
|
|
701
|
+
}
|
|
702
|
+
// Fall through to SSE setup.
|
|
404
703
|
}
|
|
704
|
+
// 'manual' — skip negotiation entirely and fall through to SSE setup.
|
|
405
705
|
|
|
406
|
-
// Set up SSE
|
|
407
|
-
reply.raw.setHeader('Content-Type', 'text/event-stream')
|
|
408
|
-
reply.raw.setHeader('Cache-Control', 'no-cache')
|
|
409
|
-
reply.raw.setHeader('Connection', 'keep-alive')
|
|
410
|
-
reply.raw.setHeader('X-Accel-Buffering', 'no') // Disable Nginx buffering
|
|
411
|
-
|
|
412
|
-
// Create SSE context
|
|
706
|
+
// Set up SSE context. Headers are written lazily on the first send.
|
|
413
707
|
const context = new SSEContext({
|
|
414
708
|
reply,
|
|
415
709
|
lastEventId: request.headers['last-event-id'],
|
|
@@ -418,48 +712,23 @@ async function fastifySSE (fastify, opts) {
|
|
|
418
712
|
})
|
|
419
713
|
|
|
420
714
|
// Store context on reply
|
|
421
|
-
reply
|
|
422
|
-
|
|
423
|
-
// Decorate reply with SSE interface
|
|
424
|
-
const sseInterface = {}
|
|
425
|
-
|
|
426
|
-
// Add SSE methods
|
|
427
|
-
Object.defineProperty(sseInterface, 'lastEventId', {
|
|
428
|
-
get: () => context.lastEventId
|
|
429
|
-
})
|
|
430
|
-
|
|
431
|
-
sseInterface.send = (source) => context.send(source)
|
|
432
|
-
sseInterface.stream = () => context.stream()
|
|
433
|
-
sseInterface.keepAlive = () => context.keepAlive()
|
|
434
|
-
sseInterface.close = () => context.close()
|
|
435
|
-
sseInterface.replay = (callback) => context.replay(callback)
|
|
436
|
-
sseInterface.onClose = (callback) => context.onClose(callback)
|
|
437
|
-
|
|
438
|
-
Object.defineProperty(sseInterface, 'isConnected', {
|
|
439
|
-
get: () => context.isConnected
|
|
440
|
-
})
|
|
715
|
+
reply.sse = context
|
|
441
716
|
|
|
442
|
-
|
|
443
|
-
Object.defineProperty(reply, 'sse', {
|
|
444
|
-
get () { return this[SSE_DECORATOR] }
|
|
445
|
-
})
|
|
446
|
-
|
|
447
|
-
// Call original handler with SSE-enabled reply
|
|
448
|
-
// Note: Headers will be sent on first SSE send
|
|
717
|
+
let res
|
|
449
718
|
try {
|
|
450
|
-
await originalHandler.call(this, request, reply)
|
|
719
|
+
res = await originalHandler.call(this, request, reply)
|
|
451
720
|
} catch (error) {
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
reply[SSE_CONTEXT]?.close()
|
|
721
|
+
if (!context.shouldKeepAlive) {
|
|
722
|
+
context.close()
|
|
455
723
|
}
|
|
456
724
|
throw error
|
|
457
725
|
}
|
|
458
726
|
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
reply[SSE_CONTEXT]?.close()
|
|
727
|
+
if (!context.shouldKeepAlive) {
|
|
728
|
+
context.close()
|
|
462
729
|
}
|
|
730
|
+
|
|
731
|
+
return res
|
|
463
732
|
}
|
|
464
733
|
})
|
|
465
734
|
}
|
|
@@ -468,3 +737,5 @@ module.exports = fp(fastifySSE, {
|
|
|
468
737
|
fastify: '5.x',
|
|
469
738
|
name: '@fastify/sse'
|
|
470
739
|
})
|
|
740
|
+
module.exports.default = fastifySSE
|
|
741
|
+
module.exports.fastifySSE = fastifySSE
|
package/package.json
CHANGED
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fastify/sse",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Server-Sent Events plugin for Fastify",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "types/index.d.ts",
|
|
7
7
|
"scripts": {
|
|
8
|
-
"test": "
|
|
9
|
-
"test:
|
|
8
|
+
"test": "npm run test:unit && npm run test:typescript && npm run test:attw",
|
|
9
|
+
"test:unit": "node --test",
|
|
10
|
+
"test:typescript": "tstyche",
|
|
11
|
+
"test:attw": "attw --pack .",
|
|
10
12
|
"lint": "eslint .",
|
|
11
13
|
"lint:fix": "eslint . --fix"
|
|
12
14
|
},
|
|
13
|
-
"tsd": {
|
|
14
|
-
"directory": "test-types"
|
|
15
|
-
},
|
|
16
15
|
"keywords": [
|
|
17
16
|
"fastify",
|
|
18
17
|
"sse",
|
|
@@ -34,18 +33,20 @@
|
|
|
34
33
|
"fastify": "^5.x"
|
|
35
34
|
},
|
|
36
35
|
"dependencies": {
|
|
37
|
-
"fastify
|
|
36
|
+
"@fastify/error": "^4.2.0",
|
|
37
|
+
"fastify-plugin": "^6.0.0"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
|
-
"@
|
|
40
|
+
"@arethetypeswrong/cli": "^0.18.2",
|
|
41
|
+
"@types/node": "^26.0.0",
|
|
41
42
|
"eslint": "^9.0.0",
|
|
42
43
|
"fastify": "^5.0.0",
|
|
43
|
-
"neostandard": "^0.
|
|
44
|
-
"
|
|
45
|
-
"typescript": "
|
|
44
|
+
"neostandard": "^0.13.0",
|
|
45
|
+
"tstyche": "^7.1.0",
|
|
46
|
+
"typescript": "~6.0.2",
|
|
46
47
|
"undici": "^7.15.0"
|
|
47
48
|
},
|
|
48
49
|
"engines": {
|
|
49
|
-
"node": ">=20"
|
|
50
|
+
"node": ">=20.20.2"
|
|
50
51
|
}
|
|
51
52
|
}
|