@fastify/sse 0.5.0 → 0.6.1

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.
@@ -0,0 +1,158 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('node:test')
4
+ const { strict: assert } = require('node:assert')
5
+ const Fastify = require('fastify')
6
+ const fastifySSE = require('../index.js')
7
+
8
+ test('SSE response should default to status 200', async (t) => {
9
+ const fastify = Fastify({ logger: false })
10
+
11
+ t.after(async () => {
12
+ await fastify.close()
13
+ })
14
+
15
+ await fastify.register(fastifySSE)
16
+
17
+ fastify.get('/events', { sse: 'only' }, async (request, reply) => {
18
+ await reply.sse.send({ data: 'hello' })
19
+ })
20
+
21
+ const response = await fastify.inject({
22
+ method: 'GET',
23
+ url: '/events',
24
+ headers: { accept: 'text/event-stream' }
25
+ })
26
+
27
+ assert.strictEqual(response.statusCode, 200)
28
+ assert.strictEqual(response.headers['content-type'], 'text/event-stream')
29
+ assert.ok(response.body.includes('data: "hello"'))
30
+ })
31
+
32
+ test('reply.code() before first SSE write should set the response status', async (t) => {
33
+ const fastify = Fastify({ logger: false })
34
+
35
+ t.after(async () => {
36
+ await fastify.close()
37
+ })
38
+
39
+ await fastify.register(fastifySSE)
40
+
41
+ fastify.get('/events', { sse: 'only' }, async (request, reply) => {
42
+ reply.code(201)
43
+ await reply.sse.send({ data: 'created' })
44
+ })
45
+
46
+ const response = await fastify.inject({
47
+ method: 'GET',
48
+ url: '/events',
49
+ headers: { accept: 'text/event-stream' }
50
+ })
51
+
52
+ assert.strictEqual(response.statusCode, 201)
53
+ assert.strictEqual(response.headers['content-type'], 'text/event-stream')
54
+ assert.ok(response.body.includes('data: "created"'))
55
+ })
56
+
57
+ test('reply.sse.sendHeaders(statusCode) should set the response status', async (t) => {
58
+ const fastify = Fastify({ logger: false })
59
+
60
+ t.after(async () => {
61
+ await fastify.close()
62
+ })
63
+
64
+ await fastify.register(fastifySSE)
65
+
66
+ fastify.get('/events', { sse: 'only' }, async (request, reply) => {
67
+ reply.sse.sendHeaders(202)
68
+ await reply.sse.send({ data: 'accepted' })
69
+ })
70
+
71
+ const response = await fastify.inject({
72
+ method: 'GET',
73
+ url: '/events',
74
+ headers: { accept: 'text/event-stream' }
75
+ })
76
+
77
+ assert.strictEqual(response.statusCode, 202)
78
+ assert.strictEqual(response.headers['content-type'], 'text/event-stream')
79
+ assert.ok(response.body.includes('data: "accepted"'))
80
+ })
81
+
82
+ test('explicit sendHeaders(statusCode) should take precedence over reply.code()', async (t) => {
83
+ const fastify = Fastify({ logger: false })
84
+
85
+ t.after(async () => {
86
+ await fastify.close()
87
+ })
88
+
89
+ await fastify.register(fastifySSE)
90
+
91
+ fastify.get('/events', { sse: 'only' }, async (request, reply) => {
92
+ reply.code(201)
93
+ reply.sse.sendHeaders(202)
94
+ await reply.sse.send({ data: 'accepted' })
95
+ })
96
+
97
+ const response = await fastify.inject({
98
+ method: 'GET',
99
+ url: '/events',
100
+ headers: { accept: 'text/event-stream' }
101
+ })
102
+
103
+ assert.strictEqual(response.statusCode, 202)
104
+ })
105
+
106
+ test('status changes after headers are committed should have no effect', async (t) => {
107
+ const fastify = Fastify({ logger: false })
108
+
109
+ t.after(async () => {
110
+ await fastify.close()
111
+ })
112
+
113
+ await fastify.register(fastifySSE)
114
+
115
+ fastify.get('/events', { sse: 'only' }, async (request, reply) => {
116
+ await reply.sse.send({ data: 'first' })
117
+ reply.sse.sendHeaders(500)
118
+ await reply.sse.send({ data: 'second' })
119
+ })
120
+
121
+ const response = await fastify.inject({
122
+ method: 'GET',
123
+ url: '/events',
124
+ headers: { accept: 'text/event-stream' }
125
+ })
126
+
127
+ assert.strictEqual(response.statusCode, 200)
128
+ assert.ok(response.body.includes('data: "first"'))
129
+ assert.ok(response.body.includes('data: "second"'))
130
+ })
131
+
132
+ async function buildApp (t, options = {}) {
133
+ const app = Fastify({ logger: false })
134
+
135
+ t.after(async () => {
136
+ await app.close()
137
+ })
138
+
139
+ await app.register(fastifySSE, options)
140
+ return app
141
+ }
142
+
143
+ test('falls back to status 200 when no response status is available', async (t) => {
144
+ const app = await buildApp(t, { heartbeatInterval: 0 })
145
+
146
+ app.get('/events', { sse: 'only' }, async (request, reply) => {
147
+ Object.defineProperty(reply.raw, 'statusCode', {
148
+ configurable: true,
149
+ writable: true,
150
+ value: undefined
151
+ })
152
+ reply.sse.sendHeaders()
153
+ })
154
+
155
+ const response = await app.inject({ url: '/events' })
156
+
157
+ assert.strictEqual(response.statusCode, 200)
158
+ })
@@ -0,0 +1,77 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('node:test')
4
+ const { strict: assert } = require('node:assert')
5
+ const { Readable } = require('node:stream')
6
+ const Fastify = require('fastify')
7
+ const fastifySSE = require('../index.js')
8
+
9
+ async function buildApp (t, options = {}) {
10
+ const app = Fastify({ logger: false })
11
+
12
+ t.after(async () => {
13
+ await app.close()
14
+ })
15
+
16
+ await app.register(fastifySSE, options)
17
+ return app
18
+ }
19
+
20
+ function createErrorStream (message, code) {
21
+ return new Readable({
22
+ read () {
23
+ const error = new Error(message)
24
+ if (code) error.code = code
25
+ this.destroy(error)
26
+ }
27
+ })
28
+ }
29
+
30
+ test('reports unexpected transform errors and ends the response', async (t) => {
31
+ const app = await buildApp(t, {
32
+ heartbeatInterval: 0,
33
+ serializer () {
34
+ throw new Error('serialization failed')
35
+ }
36
+ })
37
+ const errorLog = t.mock.fn()
38
+
39
+ app.get('/events', { sse: true }, async (request, reply) => {
40
+ reply.log.error = errorLog
41
+ await reply.sse.send(Readable.from([{ data: 'value' }]))
42
+ reply.raw.end()
43
+ })
44
+
45
+ await app.inject({
46
+ url: '/events',
47
+ headers: { accept: 'text/event-stream' }
48
+ })
49
+
50
+ assert.strictEqual(errorLog.mock.callCount(), 1)
51
+ assert.strictEqual(
52
+ errorLog.mock.calls[0].arguments[1],
53
+ 'Unexpected error in SSE stream'
54
+ )
55
+ })
56
+
57
+ test('reports expected readable stream errors and ends the response', async (t) => {
58
+ const app = await buildApp(t, { heartbeatInterval: 0 })
59
+ const infoLog = t.mock.fn()
60
+
61
+ app.get('/events', { sse: true }, async (request, reply) => {
62
+ reply.log.info = infoLog
63
+ await reply.sse.send(createErrorStream('client disconnected', 'EPIPE'))
64
+ reply.raw.end()
65
+ })
66
+
67
+ await app.inject({
68
+ url: '/events',
69
+ headers: { accept: 'text/event-stream' }
70
+ })
71
+
72
+ assert.strictEqual(infoLog.mock.callCount(), 1)
73
+ assert.strictEqual(
74
+ infoLog.mock.calls[0].arguments[1],
75
+ 'SSE stream ended (client disconnected)'
76
+ )
77
+ })
package/types/index.d.ts CHANGED
@@ -138,11 +138,14 @@ export interface SSEReplyInterface {
138
138
  /**
139
139
  * Send HTTP headers for the SSE response if not already sent.
140
140
  * This method ensures headers set via reply.header() are transferred
141
- * to the raw response before calling writeHead(200).
142
- * Called automatically before the first SSE data is sent, but can
143
- * also be called manually if needed.
144
- */
145
- sendHeaders(): void
141
+ * to the raw response before writing the response head. The status code
142
+ * is resolved in order: the explicit `statusCode` argument, then the
143
+ * value set via reply.code(), then 200.
144
+ * Called automatically (without arguments) before the first SSE data is
145
+ * sent, but can also be called manually — call it before any data is
146
+ * written for an explicit status to take effect.
147
+ */
148
+ sendHeaders(statusCode?: number): void
146
149
  }
147
150
 
148
151
  export declare const fastifySSE: FastifyPluginAsync<SSEPluginOptions>
@@ -1,344 +0,0 @@
1
- 'use strict'
2
-
3
- // Isolated micro-benchmark for clientAcceptsSSE (the gate function only,
4
- // no fastify request handling — see bench/in-context.js for that).
5
- //
6
- // Compares:
7
- // before — implementation as it existed before the optimization commit
8
- // (split / toLowerCase / trim / rest-params / parseFloat)
9
- // after — current optimized implementation (zero-alloc fast path +
10
- // char-walking slow path)
11
- // without — `() => true`, baseline showing the cost of not gating
12
- //
13
- // Methodology: for each impl × input combination, we
14
- // 1. warm up,
15
- // 2. calibrate iterations so a single sample takes ~CALIBRATION_TARGET_MS,
16
- // 3. collect SAMPLE_COUNT independent samples,
17
- // 4. report mean / median / p5 / p95 / stddev / RSD over the samples.
18
- //
19
- // Run with: `node bench/accept-header.js`
20
-
21
- const { performance } = require('perf_hooks')
22
-
23
- // =============================================================================
24
- // Implementations
25
- // =============================================================================
26
-
27
- // ---- main: substring gate as shipped on `main` before this PR ----
28
- // `acceptHeader.includes('text/event-stream')` — not spec-compliant (refuses
29
- // `*/*`, admits anything containing the substring even mid-token, ignores
30
- // q=0) but very cheap. Included for "what does the gate alone cost on main".
31
- function main (acceptHeader) {
32
- return (acceptHeader || '').includes('text/event-stream')
33
- }
34
-
35
- // ---- before: this branch's first iteration of spec-compliant parsing ----
36
- // Heavy: split / toLowerCase / trim / rest-params / parseFloat.
37
-
38
- function before (acceptHeader, options) {
39
- const strict = options?.strict === true
40
- if (!acceptHeader) return !strict
41
-
42
- let bestSpecificity = -1
43
- let bestQuality = 0
44
-
45
- for (const part of acceptHeader.split(',')) {
46
- const [rawType, ...params] = part.split(';')
47
- const type = rawType.trim().toLowerCase()
48
-
49
- let specificity
50
- if (type === 'text/event-stream') specificity = 3
51
- else if (!strict && type === 'text/*') specificity = 2
52
- else if (!strict && type === '*/*') specificity = 1
53
- else continue
54
-
55
- let quality = 1
56
- for (const p of params) {
57
- const eq = p.indexOf('=')
58
- if (eq === -1) continue
59
- const key = p.slice(0, eq).trim().toLowerCase()
60
- if (key !== 'q') continue
61
- const parsed = Number.parseFloat(p.slice(eq + 1).trim())
62
- if (Number.isFinite(parsed) && parsed >= 0 && parsed <= 1) {
63
- quality = parsed
64
- }
65
- }
66
-
67
- if (specificity > bestSpecificity) {
68
- bestSpecificity = specificity
69
- bestQuality = quality
70
- }
71
- }
72
-
73
- return bestSpecificity >= 0 && bestQuality > 0
74
- }
75
-
76
- // ---- after: current optimized implementation (mirrors index.js) ----
77
-
78
- const CC_SP = 32
79
- const CC_HT = 9
80
- const CC_COMMA = 44
81
- const CC_SEMI = 59
82
- const CC_EQ = 61
83
- const CC_DOT = 46
84
- const CC_ZERO = 48
85
- const CC_LOWER_Q = 113
86
- const CC_UPPER_Q = 81
87
-
88
- function ciEqualsAt (s, start, end, lower) {
89
- if (end - start !== lower.length) return false
90
- for (let j = 0; j < lower.length; j++) {
91
- let c = s.charCodeAt(start + j)
92
- if (c >= 65 && c <= 90) c |= 32
93
- if (c !== lower.charCodeAt(j)) return false
94
- }
95
- return true
96
- }
97
-
98
- function isQValueZero (s, start, end) {
99
- if (end <= start) return false
100
- if (s.charCodeAt(start) !== CC_ZERO) return false
101
- let i = start + 1
102
- if (i < end && s.charCodeAt(i) === CC_DOT) {
103
- i++
104
- while (i < end) {
105
- if (s.charCodeAt(i) !== CC_ZERO) return false
106
- i++
107
- }
108
- }
109
- return i === end
110
- }
111
-
112
- function after (acceptHeader, options) {
113
- const strict = options !== undefined && options.strict === true
114
- if (!acceptHeader) return !strict
115
-
116
- if (acceptHeader === 'text/event-stream') return true
117
- if (!strict && (acceptHeader === '*/*' || acceptHeader === 'text/*')) return true
118
-
119
- const len = acceptHeader.length
120
- let bestSpec = -1
121
- let bestRefused = false
122
- let i = 0
123
-
124
- while (i < len) {
125
- while (i < len) {
126
- const c = acceptHeader.charCodeAt(i)
127
- if (c !== CC_SP && c !== CC_HT) break
128
- i++
129
- }
130
-
131
- const typeStart = i
132
- while (i < len) {
133
- const c = acceptHeader.charCodeAt(i)
134
- if (c === CC_SEMI || c === CC_COMMA) break
135
- i++
136
- }
137
- let typeEnd = i
138
- while (typeEnd > typeStart) {
139
- const c = acceptHeader.charCodeAt(typeEnd - 1)
140
- if (c !== CC_SP && c !== CC_HT) break
141
- typeEnd--
142
- }
143
-
144
- let spec = -1
145
- if (ciEqualsAt(acceptHeader, typeStart, typeEnd, 'text/event-stream')) spec = 3
146
- else if (!strict && ciEqualsAt(acceptHeader, typeStart, typeEnd, 'text/*')) spec = 2
147
- else if (!strict && ciEqualsAt(acceptHeader, typeStart, typeEnd, '*/*')) spec = 1
148
-
149
- let refused = false
150
- if (spec === -1) {
151
- while (i < len && acceptHeader.charCodeAt(i) !== CC_COMMA) i++
152
- } else {
153
- while (i < len && acceptHeader.charCodeAt(i) === CC_SEMI) {
154
- i++
155
- while (i < len) {
156
- const c = acceptHeader.charCodeAt(i)
157
- if (c !== CC_SP && c !== CC_HT) break
158
- i++
159
- }
160
- const keyStart = i
161
- while (i < len) {
162
- const c = acceptHeader.charCodeAt(i)
163
- if (c === CC_EQ || c === CC_SEMI || c === CC_COMMA) break
164
- i++
165
- }
166
- const keyEnd = i
167
-
168
- if (i < len && acceptHeader.charCodeAt(i) === CC_EQ) {
169
- i++
170
- const valStart = i
171
- while (i < len) {
172
- const c = acceptHeader.charCodeAt(i)
173
- if (c === CC_SEMI || c === CC_COMMA) break
174
- i++
175
- }
176
- const valEnd = i
177
-
178
- if (keyEnd - keyStart === 1) {
179
- const kc = acceptHeader.charCodeAt(keyStart)
180
- if ((kc === CC_LOWER_Q || kc === CC_UPPER_Q) &&
181
- isQValueZero(acceptHeader, valStart, valEnd)) {
182
- refused = true
183
- }
184
- }
185
- }
186
- }
187
- }
188
-
189
- if (spec === 3 && !refused) return true
190
-
191
- if (spec > bestSpec) {
192
- bestSpec = spec
193
- bestRefused = refused
194
- }
195
-
196
- if (i < len && acceptHeader.charCodeAt(i) === CC_COMMA) i++
197
- }
198
-
199
- return bestSpec >= 0 && !bestRefused
200
- }
201
-
202
- // ---- without: baseline ----
203
-
204
- function without () { return true }
205
-
206
- // =============================================================================
207
- // Correctness sanity-check
208
- // =============================================================================
209
-
210
- const correctnessCases = [
211
- undefined,
212
- '',
213
- 'text/event-stream',
214
- '*/*',
215
- 'text/*',
216
- 'application/json',
217
- 'text/event-stream;q=0',
218
- '*/*, text/event-stream;q=0',
219
- 'text/event-stream, application/json;q=0.5',
220
- 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
221
- 'Text/Event-Stream',
222
- ' text/event-stream '
223
- ]
224
-
225
- for (const input of correctnessCases) {
226
- for (const opts of [undefined, { strict: true }]) {
227
- const b = before(input, opts)
228
- const a = after(input, opts)
229
- if (b !== a) {
230
- console.error(`DISAGREE on ${JSON.stringify(input)} strict=${!!opts?.strict}: before=${b}, after=${a}`)
231
- process.exit(1)
232
- }
233
- }
234
- }
235
- console.log('correctness: before and after agree on all sample inputs')
236
-
237
- // =============================================================================
238
- // Statistical bench harness
239
- // =============================================================================
240
-
241
- const WARMUP_ITER = 200_000
242
- const CALIBRATION_TARGET_MS = 8
243
- const SAMPLE_COUNT = 200
244
-
245
- function calibrateIterations (fn, input) {
246
- // Find how many iterations take ~CALIBRATION_TARGET_MS, given a quick probe.
247
- let iter = 10_000
248
- let elapsed = 0
249
- while (elapsed < 2) {
250
- const start = performance.now()
251
- for (let i = 0; i < iter; i++) fn(input)
252
- elapsed = performance.now() - start
253
- if (elapsed < 0.5) iter *= 10
254
- else break
255
- }
256
- // Scale iter to hit target.
257
- const scaled = Math.max(1000, Math.round(iter * (CALIBRATION_TARGET_MS / Math.max(elapsed, 0.001))))
258
- return scaled
259
- }
260
-
261
- function sample (fn, input, iterations) {
262
- const start = performance.now()
263
- for (let i = 0; i < iterations; i++) fn(input)
264
- return iterations / ((performance.now() - start) / 1000)
265
- }
266
-
267
- function stats (samples) {
268
- const sorted = samples.slice().sort((a, b) => a - b)
269
- const n = sorted.length
270
- const mean = samples.reduce((s, v) => s + v, 0) / n
271
- const variance = samples.reduce((s, v) => s + (v - mean) ** 2, 0) / n
272
- const stddev = Math.sqrt(variance)
273
- return {
274
- n,
275
- mean,
276
- median: sorted[Math.floor(n / 2)],
277
- p5: sorted[Math.floor(n * 0.05)],
278
- p95: sorted[Math.floor(n * 0.95)],
279
- min: sorted[0],
280
- max: sorted[n - 1],
281
- stddev,
282
- rsd: stddev / mean
283
- }
284
- }
285
-
286
- function bench (fn, input) {
287
- for (let i = 0; i < WARMUP_ITER; i++) fn(input)
288
- const iter = calibrateIterations(fn, input)
289
- // Extra warmup at the calibrated iteration count.
290
- sample(fn, input, iter)
291
- const samples = new Array(SAMPLE_COUNT)
292
- for (let s = 0; s < SAMPLE_COUNT; s++) {
293
- samples[s] = sample(fn, input, iter)
294
- }
295
- return { stats: stats(samples), iterPerSample: iter }
296
- }
297
-
298
- // =============================================================================
299
- // Run
300
- // =============================================================================
301
-
302
- const benchCases = [
303
- ['undefined', undefined],
304
- ['text/event-stream', 'text/event-stream'],
305
- ['*/*', '*/*'],
306
- ['text/event-stream;q=0', 'text/event-stream;q=0'],
307
- ['mixed q-values', 'text/event-stream, application/json;q=0.5'],
308
- ['browser-like', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8'],
309
- ['*/*, t/e-s;q=0', '*/*, text/event-stream;q=0']
310
- ]
311
-
312
- const impls = [
313
- ['without', without],
314
- ['main ', main],
315
- ['before ', before],
316
- ['after ', after]
317
- ]
318
-
319
- function fmtOps (n) { return Math.round(n).toLocaleString().padStart(15) }
320
- function fmtPct (n) { return (n * 100).toFixed(2) + '%' }
321
- function fmtNs (opsPerSec) { return (1e9 / opsPerSec).toFixed(1) + ' ns/op' }
322
-
323
- console.log(`\nsamples per case: ${SAMPLE_COUNT} target ~${CALIBRATION_TARGET_MS}ms/sample warmup: ${WARMUP_ITER.toLocaleString()} iter\n`)
324
- console.log('Each row: mean (median, p5..p95) ± stddev RSD ns/op (median) speedup-vs-before')
325
- console.log('─'.repeat(120))
326
-
327
- for (const [caseName, header] of benchCases) {
328
- console.log(`\n=== ${caseName} ===`)
329
- let beforeMedian = 0
330
- for (const [implName, fn] of impls) {
331
- const { stats: s, iterPerSample } = bench(fn, header)
332
- if (implName.trim() === 'before') beforeMedian = s.median
333
- const speedup = (implName.trim() === 'after' && beforeMedian > 0)
334
- ? ` ${(s.median / beforeMedian).toFixed(2)}x vs before`
335
- : ''
336
- console.log(
337
- ` ${implName} ${fmtOps(s.mean)} ` +
338
- `(med ${fmtOps(s.median)}, p5 ${fmtOps(s.p5)}, p95 ${fmtOps(s.p95)}) ` +
339
- `±${fmtOps(s.stddev)} RSD ${fmtPct(s.rsd).padStart(7)} ` +
340
- `${fmtNs(s.median).padStart(11)} iter/sample=${iterPerSample.toLocaleString()}${speedup}`
341
- )
342
- }
343
- }
344
- console.log()