@fastify/sse 0.1.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/.claude/settings.local.json +9 -0
- package/.gitattributes +2 -0
- package/.github/.stale.yml +21 -0
- package/.github/dependabot.yml +13 -0
- package/.github/tests_checker.yml +8 -0
- package/.github/workflows/ci.yml +28 -0
- package/.github/workflows/package-manager-ci.yml +24 -0
- package/.prettierignore +1 -0
- package/README.md +391 -0
- package/docs/.gitkeep +0 -0
- package/eslint.config.js +3 -0
- package/examples/.gitkeep +0 -0
- package/examples/basic.js +121 -0
- package/index.js +342 -0
- package/package.json +50 -0
- package/test/.gitkeep +0 -0
- package/test/basic.test.js +311 -0
- package/test/lifecycle.test.js +197 -0
- package/test-types/index.test-d.ts +192 -0
- package/types/.gitkeep +0 -0
- package/types/index.d.ts +105 -0
package/.gitattributes
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Number of days of inactivity before an issue becomes stale
|
|
2
|
+
daysUntilStale: 15
|
|
3
|
+
# Number of days of inactivity before a stale issue is closed
|
|
4
|
+
daysUntilClose: 7
|
|
5
|
+
# Issues with these labels will never be considered stale
|
|
6
|
+
exemptLabels:
|
|
7
|
+
- "discussion"
|
|
8
|
+
- "feature request"
|
|
9
|
+
- "bug"
|
|
10
|
+
- "help wanted"
|
|
11
|
+
- "plugin suggestion"
|
|
12
|
+
- "good first issue"
|
|
13
|
+
# Label to use when marking an issue as stale
|
|
14
|
+
staleLabel: stale
|
|
15
|
+
# Comment to post when marking an issue as stale. Set to `false` to disable
|
|
16
|
+
markComment: >
|
|
17
|
+
This issue has been automatically marked as stale because it has not had
|
|
18
|
+
recent activity. It will be closed if no further activity occurs. Thank you
|
|
19
|
+
for your contributions.
|
|
20
|
+
# Comment to post when closing a stale issue. Set to `false` to disable
|
|
21
|
+
closeComment: false
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
version: 2
|
|
2
|
+
updates:
|
|
3
|
+
- package-ecosystem: "github-actions"
|
|
4
|
+
directory: "/"
|
|
5
|
+
schedule:
|
|
6
|
+
interval: "monthly"
|
|
7
|
+
open-pull-requests-limit: 10
|
|
8
|
+
|
|
9
|
+
- package-ecosystem: "npm"
|
|
10
|
+
directory: "/"
|
|
11
|
+
schedule:
|
|
12
|
+
interval: "monthly"
|
|
13
|
+
open-pull-requests-limit: 10
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches:
|
|
6
|
+
- main
|
|
7
|
+
- next
|
|
8
|
+
- 'v*'
|
|
9
|
+
paths-ignore:
|
|
10
|
+
- 'docs/**'
|
|
11
|
+
- '*.md'
|
|
12
|
+
pull_request:
|
|
13
|
+
paths-ignore:
|
|
14
|
+
- 'docs/**'
|
|
15
|
+
- '*.md'
|
|
16
|
+
|
|
17
|
+
permissions:
|
|
18
|
+
contents: read
|
|
19
|
+
|
|
20
|
+
jobs:
|
|
21
|
+
test:
|
|
22
|
+
permissions:
|
|
23
|
+
contents: write
|
|
24
|
+
pull-requests: write
|
|
25
|
+
uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5
|
|
26
|
+
with:
|
|
27
|
+
license-check: true
|
|
28
|
+
lint: true
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
name: package-manager-ci
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches:
|
|
6
|
+
- main
|
|
7
|
+
- next
|
|
8
|
+
- 'v*'
|
|
9
|
+
paths-ignore:
|
|
10
|
+
- 'docs/**'
|
|
11
|
+
- '*.md'
|
|
12
|
+
pull_request:
|
|
13
|
+
paths-ignore:
|
|
14
|
+
- 'docs/**'
|
|
15
|
+
- '*.md'
|
|
16
|
+
|
|
17
|
+
permissions:
|
|
18
|
+
contents: read
|
|
19
|
+
|
|
20
|
+
jobs:
|
|
21
|
+
test:
|
|
22
|
+
permissions:
|
|
23
|
+
contents: read
|
|
24
|
+
uses: fastify/workflows/.github/workflows/plugins-ci-package-manager.yml@v5
|
package/.prettierignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
*
|
package/README.md
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
# @fastify/sse
|
|
2
|
+
|
|
3
|
+
[](https://npmjs.org/package/@fastify/sse)
|
|
4
|
+
[](https://github.com/fastify/fastify-sse/actions)
|
|
5
|
+
|
|
6
|
+
Server-Sent Events plugin for Fastify. Provides first-class SSE support with clean API integration, session management, and streaming capabilities.
|
|
7
|
+
|
|
8
|
+
## Features
|
|
9
|
+
|
|
10
|
+
- 🚀 **Clean API**: Route-level SSE support with `{ sse: true }`
|
|
11
|
+
- 📡 **Streaming**: Native support for Node.js streams and async iterators
|
|
12
|
+
- 🔄 **Reconnection**: Built-in message replay with `Last-Event-ID`
|
|
13
|
+
- 💓 **Heartbeat**: Configurable keep-alive mechanism
|
|
14
|
+
- 🎯 **Lifecycle**: Full integration with Fastify hooks and error handling
|
|
15
|
+
- 📝 **TypeScript**: Complete type definitions included
|
|
16
|
+
- ⚡ **Performance**: Efficient backpressure handling
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm i @fastify/sse
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Quick Start
|
|
25
|
+
|
|
26
|
+
```js
|
|
27
|
+
const fastify = require('fastify')({ logger: true })
|
|
28
|
+
|
|
29
|
+
// Register the plugin
|
|
30
|
+
await fastify.register(require('@fastify/sse'))
|
|
31
|
+
|
|
32
|
+
// Create an SSE endpoint
|
|
33
|
+
fastify.get('/events', { sse: true }, async (request, reply) => {
|
|
34
|
+
// Send a message
|
|
35
|
+
await reply.sse.send({ data: 'Hello SSE!' })
|
|
36
|
+
|
|
37
|
+
// Send with full options
|
|
38
|
+
await reply.sse.send({
|
|
39
|
+
id: '123',
|
|
40
|
+
event: 'update',
|
|
41
|
+
data: { message: 'Hello World' },
|
|
42
|
+
retry: 1000
|
|
43
|
+
})
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
await fastify.listen({ port: 3000 })
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## API
|
|
50
|
+
|
|
51
|
+
### Plugin Registration
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
await fastify.register(require('@fastify/sse'), {
|
|
55
|
+
// Optional: heartbeat interval in milliseconds (default: 30000)
|
|
56
|
+
heartbeatInterval: 30000,
|
|
57
|
+
|
|
58
|
+
// Optional: default serializer (default: JSON.stringify)
|
|
59
|
+
serializer: (data) => JSON.stringify(data)
|
|
60
|
+
})
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Route Configuration
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
// Enable SSE for a route
|
|
67
|
+
fastify.get('/events', { sse: true }, handler)
|
|
68
|
+
|
|
69
|
+
// With options
|
|
70
|
+
fastify.get('/events', {
|
|
71
|
+
sse: {
|
|
72
|
+
heartbeat: false, // Disable heartbeat for this route
|
|
73
|
+
serializer: customSerializer // Custom serializer for this route
|
|
74
|
+
}
|
|
75
|
+
}, handler)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### reply.sse.send(source)
|
|
79
|
+
|
|
80
|
+
Send SSE messages. Accepts various source types:
|
|
81
|
+
|
|
82
|
+
#### Single Message
|
|
83
|
+
|
|
84
|
+
```js
|
|
85
|
+
// Simple data
|
|
86
|
+
await reply.sse.send({ data: 'hello' })
|
|
87
|
+
|
|
88
|
+
// Full SSE message
|
|
89
|
+
await reply.sse.send({
|
|
90
|
+
id: '123',
|
|
91
|
+
event: 'update',
|
|
92
|
+
data: { message: 'Hello' },
|
|
93
|
+
retry: 1000
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
// Plain string
|
|
97
|
+
await reply.sse.send('plain text message')
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
#### Streaming Sources
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
// Async generator
|
|
104
|
+
async function* generateEvents() {
|
|
105
|
+
for (let i = 0; i < 10; i++) {
|
|
106
|
+
yield { id: i, data: `Event ${i}` }
|
|
107
|
+
await sleep(1000)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
await reply.sse.send(generateEvents())
|
|
111
|
+
|
|
112
|
+
// Node.js Readable stream
|
|
113
|
+
const stream = fs.createReadStream('data.jsonl')
|
|
114
|
+
await reply.sse.send(stream)
|
|
115
|
+
|
|
116
|
+
// Transform existing stream
|
|
117
|
+
const transformStream = new Transform({
|
|
118
|
+
transform(chunk, encoding, callback) {
|
|
119
|
+
callback(null, { data: chunk.toString() })
|
|
120
|
+
}
|
|
121
|
+
})
|
|
122
|
+
someSource.pipe(transformStream)
|
|
123
|
+
await reply.sse.send(transformStream)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### reply.sse.stream()
|
|
127
|
+
|
|
128
|
+
Create a transform stream for use in pipeline operations:
|
|
129
|
+
|
|
130
|
+
```js
|
|
131
|
+
// Use with pipeline for efficient streaming
|
|
132
|
+
const { pipeline } = require('stream/promises')
|
|
133
|
+
const fs = require('fs')
|
|
134
|
+
|
|
135
|
+
fastify.get('/file-stream', { sse: true }, async (request, reply) => {
|
|
136
|
+
const fileStream = fs.createReadStream('data.jsonl')
|
|
137
|
+
|
|
138
|
+
// Parse each line as JSON and convert to SSE format
|
|
139
|
+
const parseTransform = new Transform({
|
|
140
|
+
transform(chunk, encoding, callback) {
|
|
141
|
+
const lines = chunk.toString().split('\n').filter(Boolean)
|
|
142
|
+
for (const line of lines) {
|
|
143
|
+
try {
|
|
144
|
+
const data = JSON.parse(line)
|
|
145
|
+
this.push({ id: data.id, data })
|
|
146
|
+
} catch (err) {
|
|
147
|
+
// Skip invalid JSON lines
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
callback()
|
|
151
|
+
}
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
// Stream file data through SSE
|
|
155
|
+
await pipeline(
|
|
156
|
+
fileStream,
|
|
157
|
+
parseTransform,
|
|
158
|
+
reply.sse.stream(),
|
|
159
|
+
reply.raw,
|
|
160
|
+
{ end: false }
|
|
161
|
+
)
|
|
162
|
+
})
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### Connection Management
|
|
166
|
+
|
|
167
|
+
```js
|
|
168
|
+
fastify.get('/live', { sse: true }, async (request, reply) => {
|
|
169
|
+
// Keep connection alive (prevents automatic close)
|
|
170
|
+
reply.sse.keepAlive()
|
|
171
|
+
|
|
172
|
+
// Send initial message
|
|
173
|
+
await reply.sse.send({ data: 'Connected' })
|
|
174
|
+
|
|
175
|
+
// Set up periodic updates
|
|
176
|
+
const interval = setInterval(async () => {
|
|
177
|
+
if (reply.sse.isConnected) {
|
|
178
|
+
await reply.sse.send({ data: 'ping' })
|
|
179
|
+
} else {
|
|
180
|
+
clearInterval(interval)
|
|
181
|
+
}
|
|
182
|
+
}, 1000)
|
|
183
|
+
|
|
184
|
+
// Clean up when connection closes
|
|
185
|
+
reply.sse.onClose(() => {
|
|
186
|
+
clearInterval(interval)
|
|
187
|
+
console.log('Connection closed')
|
|
188
|
+
})
|
|
189
|
+
})
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
### Message Replay
|
|
193
|
+
|
|
194
|
+
Handle client reconnections with `Last-Event-ID`:
|
|
195
|
+
|
|
196
|
+
```js
|
|
197
|
+
const messageHistory = []
|
|
198
|
+
|
|
199
|
+
fastify.get('/events', { sse: true }, async (request, reply) => {
|
|
200
|
+
// Handle replay on reconnection
|
|
201
|
+
await reply.sse.replay(async (lastEventId) => {
|
|
202
|
+
// Find messages after the last received ID
|
|
203
|
+
const startIndex = messageHistory.findIndex(msg => msg.id === lastEventId)
|
|
204
|
+
const messagesToReplay = startIndex !== -1
|
|
205
|
+
? messageHistory.slice(startIndex + 1)
|
|
206
|
+
: messageHistory
|
|
207
|
+
|
|
208
|
+
// Send missed messages
|
|
209
|
+
for (const message of messagesToReplay) {
|
|
210
|
+
await reply.sse.send(message)
|
|
211
|
+
}
|
|
212
|
+
})
|
|
213
|
+
|
|
214
|
+
// Send new message
|
|
215
|
+
const newMessage = { id: Date.now(), data: 'New event' }
|
|
216
|
+
messageHistory.push(newMessage)
|
|
217
|
+
await reply.sse.send(newMessage)
|
|
218
|
+
})
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### Properties and Methods
|
|
222
|
+
|
|
223
|
+
- `reply.sse.lastEventId`: Client's last received event ID
|
|
224
|
+
- `reply.sse.isConnected`: Connection status (boolean)
|
|
225
|
+
- `reply.sse.keepAlive()`: Prevent connection from auto-closing
|
|
226
|
+
- `reply.sse.close()`: Manually close the connection
|
|
227
|
+
- `reply.sse.replay(callback)`: Handle message replay
|
|
228
|
+
- `reply.sse.onClose(callback)`: Register close callback
|
|
229
|
+
|
|
230
|
+
## Advanced Usage
|
|
231
|
+
|
|
232
|
+
### Fallback to Regular Responses
|
|
233
|
+
|
|
234
|
+
Routes with `{ sse: true }` automatically fall back to regular handlers when the client doesn't request SSE:
|
|
235
|
+
|
|
236
|
+
```js
|
|
237
|
+
fastify.get('/data', { sse: true }, async (request, reply) => {
|
|
238
|
+
const data = await getData()
|
|
239
|
+
|
|
240
|
+
// Check if this is an SSE request
|
|
241
|
+
if (request.headers.accept?.includes('text/event-stream')) {
|
|
242
|
+
// SSE client - stream the data
|
|
243
|
+
await reply.sse.send({ data })
|
|
244
|
+
} else {
|
|
245
|
+
// Regular client - return JSON
|
|
246
|
+
return { data }
|
|
247
|
+
}
|
|
248
|
+
})
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
### Error Handling
|
|
252
|
+
|
|
253
|
+
```js
|
|
254
|
+
fastify.get('/stream', { sse: true }, async (request, reply) => {
|
|
255
|
+
try {
|
|
256
|
+
async function* riskyGenerator() {
|
|
257
|
+
yield { data: 'before error' }
|
|
258
|
+
throw new Error('Something went wrong')
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
await reply.sse.send(riskyGenerator())
|
|
262
|
+
} catch (error) {
|
|
263
|
+
// Handle errors gracefully
|
|
264
|
+
await reply.sse.send({
|
|
265
|
+
event: 'error',
|
|
266
|
+
data: { message: 'Stream error occurred' }
|
|
267
|
+
})
|
|
268
|
+
}
|
|
269
|
+
})
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
### Custom Serialization
|
|
273
|
+
|
|
274
|
+
```js
|
|
275
|
+
// Plugin-level serializer
|
|
276
|
+
await fastify.register(require('@fastify/sse'), {
|
|
277
|
+
serializer: (data) => {
|
|
278
|
+
// Custom serialization logic
|
|
279
|
+
return typeof data === 'string' ? data : JSON.stringify(data)
|
|
280
|
+
}
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
// Route-level serializer
|
|
284
|
+
fastify.get('/custom', {
|
|
285
|
+
sse: {
|
|
286
|
+
serializer: (data) => `CUSTOM:${JSON.stringify(data)}`
|
|
287
|
+
}
|
|
288
|
+
}, async (request, reply) => {
|
|
289
|
+
await reply.sse.send({ data: 'test' }) // Outputs: "CUSTOM:\"test\""
|
|
290
|
+
})
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
## Testing
|
|
294
|
+
|
|
295
|
+
Testing SSE endpoints is simplified with standard Fastify injection:
|
|
296
|
+
|
|
297
|
+
```js
|
|
298
|
+
const response = await fastify.inject({
|
|
299
|
+
method: 'GET',
|
|
300
|
+
url: '/events',
|
|
301
|
+
headers: {
|
|
302
|
+
accept: 'text/event-stream'
|
|
303
|
+
}
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
assert.strictEqual(response.statusCode, 200)
|
|
307
|
+
assert.strictEqual(response.headers['content-type'], 'text/event-stream')
|
|
308
|
+
assert.ok(response.body.includes('data: "Hello SSE!"'))
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
## Client-Side Usage
|
|
312
|
+
|
|
313
|
+
```html
|
|
314
|
+
<!DOCTYPE html>
|
|
315
|
+
<html>
|
|
316
|
+
<head>
|
|
317
|
+
<title>SSE Client</title>
|
|
318
|
+
</head>
|
|
319
|
+
<body>
|
|
320
|
+
<div id="messages"></div>
|
|
321
|
+
|
|
322
|
+
<script>
|
|
323
|
+
const eventSource = new EventSource('/events')
|
|
324
|
+
const messagesDiv = document.getElementById('messages')
|
|
325
|
+
|
|
326
|
+
eventSource.onmessage = function(event) {
|
|
327
|
+
const data = JSON.parse(event.data)
|
|
328
|
+
messagesDiv.innerHTML += '<div>' + JSON.stringify(data) + '</div>'
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
eventSource.addEventListener('update', function(event) {
|
|
332
|
+
console.log('Update event:', JSON.parse(event.data))
|
|
333
|
+
})
|
|
334
|
+
|
|
335
|
+
eventSource.onerror = function(event) {
|
|
336
|
+
console.error('SSE error:', event)
|
|
337
|
+
}
|
|
338
|
+
</script>
|
|
339
|
+
</body>
|
|
340
|
+
</html>
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
## TypeScript
|
|
344
|
+
|
|
345
|
+
Full TypeScript support included:
|
|
346
|
+
|
|
347
|
+
```typescript
|
|
348
|
+
import fastify from 'fastify'
|
|
349
|
+
import fastifySSE, { SSEMessage } from '@fastify/sse'
|
|
350
|
+
|
|
351
|
+
const app = fastify()
|
|
352
|
+
await app.register(fastifySSE)
|
|
353
|
+
|
|
354
|
+
app.get('/events', { sse: true }, async (request, reply) => {
|
|
355
|
+
const message: SSEMessage = {
|
|
356
|
+
id: '123',
|
|
357
|
+
event: 'test',
|
|
358
|
+
data: { hello: 'world' }
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
await reply.sse.send(message)
|
|
362
|
+
|
|
363
|
+
// TypeScript knows about SSE properties
|
|
364
|
+
console.log(reply.sse.isConnected) // boolean
|
|
365
|
+
console.log(reply.sse.lastEventId) // string | null
|
|
366
|
+
})
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
## Examples
|
|
370
|
+
|
|
371
|
+
See the [examples](examples/) directory for complete working examples:
|
|
372
|
+
|
|
373
|
+
- [Basic Usage](examples/basic.js) - Simple SSE endpoints
|
|
374
|
+
- More examples coming soon...
|
|
375
|
+
|
|
376
|
+
## Comparison with fastify-sse-v2
|
|
377
|
+
|
|
378
|
+
| Feature | fastify-sse-v2 | @fastify/sse |
|
|
379
|
+
|---------|---------------|--------------|
|
|
380
|
+
| Basic SSE | ✅ | ✅ |
|
|
381
|
+
| Async Iterators | ✅ | ✅ |
|
|
382
|
+
| Stream Support | ✅ | ✅ Enhanced |
|
|
383
|
+
| Session Management | ❌ | ✅ |
|
|
384
|
+
| Last-Event-ID | ❌ | ✅ |
|
|
385
|
+
| Connection Health | ❌ | ✅ |
|
|
386
|
+
| Fastify Integration | ⚠️ Limited | ✅ Full |
|
|
387
|
+
| Testing Support | ❌ | ✅ |
|
|
388
|
+
|
|
389
|
+
## License
|
|
390
|
+
|
|
391
|
+
[MIT](LICENSE)
|
package/docs/.gitkeep
ADDED
|
File without changes
|
package/eslint.config.js
ADDED
|
File without changes
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const fastify = require('fastify')({ logger: true })
|
|
4
|
+
|
|
5
|
+
// Register the SSE plugin
|
|
6
|
+
fastify.register(require('../index.js'))
|
|
7
|
+
|
|
8
|
+
// Basic SSE endpoint
|
|
9
|
+
fastify.get('/events', { sse: true }, async (request, reply) => {
|
|
10
|
+
// Send a simple message
|
|
11
|
+
await reply.sse.send({ data: 'Hello SSE!' })
|
|
12
|
+
|
|
13
|
+
// Send multiple events
|
|
14
|
+
for (let i = 0; i < 5; i++) {
|
|
15
|
+
await reply.sse.send({
|
|
16
|
+
id: String(i),
|
|
17
|
+
event: 'counter',
|
|
18
|
+
data: { count: i, timestamp: Date.now() }
|
|
19
|
+
})
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Connection will close automatically when handler ends
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
// Stream endpoint with async generator
|
|
26
|
+
fastify.get('/stream', { sse: true }, async (request, reply) => {
|
|
27
|
+
async function * generateEvents () {
|
|
28
|
+
for (let i = 0; i < 10; i++) {
|
|
29
|
+
await new Promise(resolve => setTimeout(resolve, 1000))
|
|
30
|
+
yield {
|
|
31
|
+
id: String(i),
|
|
32
|
+
event: 'tick',
|
|
33
|
+
data: { tick: i, time: new Date().toISOString() }
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
await reply.sse.send(generateEvents())
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
// Persistent connection with keepAlive
|
|
42
|
+
fastify.get('/live', { sse: true }, async (request, reply) => {
|
|
43
|
+
// Keep connection alive
|
|
44
|
+
reply.sse.keepAlive()
|
|
45
|
+
|
|
46
|
+
// Send initial event
|
|
47
|
+
await reply.sse.send({ data: 'Connected to live stream' })
|
|
48
|
+
|
|
49
|
+
// Send periodic updates
|
|
50
|
+
const interval = setInterval(async () => {
|
|
51
|
+
try {
|
|
52
|
+
if (reply.sse.isConnected) {
|
|
53
|
+
await reply.sse.send({
|
|
54
|
+
event: 'heartbeat',
|
|
55
|
+
data: { timestamp: Date.now() }
|
|
56
|
+
})
|
|
57
|
+
} else {
|
|
58
|
+
clearInterval(interval)
|
|
59
|
+
}
|
|
60
|
+
} catch (error) {
|
|
61
|
+
clearInterval(interval)
|
|
62
|
+
}
|
|
63
|
+
}, 2000)
|
|
64
|
+
|
|
65
|
+
// Clean up on close
|
|
66
|
+
reply.sse.onClose(() => {
|
|
67
|
+
clearInterval(interval)
|
|
68
|
+
console.log('Live stream connection closed')
|
|
69
|
+
})
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
// Replay functionality
|
|
73
|
+
const messageHistory = []
|
|
74
|
+
let eventId = 0
|
|
75
|
+
|
|
76
|
+
fastify.get('/replay', { sse: true }, async (request, reply) => {
|
|
77
|
+
// Handle replay if client reconnects
|
|
78
|
+
await reply.sse.replay(async (lastEventId) => {
|
|
79
|
+
const startIndex = messageHistory.findIndex(msg => msg.id === lastEventId)
|
|
80
|
+
const messagesToReplay = startIndex !== -1
|
|
81
|
+
? messageHistory.slice(startIndex + 1)
|
|
82
|
+
: messageHistory
|
|
83
|
+
|
|
84
|
+
for (const message of messagesToReplay) {
|
|
85
|
+
await reply.sse.send(message)
|
|
86
|
+
}
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
// Send new message
|
|
90
|
+
const newMessage = {
|
|
91
|
+
id: String(++eventId),
|
|
92
|
+
data: { message: `New event ${eventId}`, timestamp: Date.now() }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
messageHistory.push(newMessage)
|
|
96
|
+
|
|
97
|
+
// Keep only last 100 messages
|
|
98
|
+
if (messageHistory.length > 100) {
|
|
99
|
+
messageHistory.shift()
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
await reply.sse.send(newMessage)
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
// Start the server
|
|
106
|
+
const start = async () => {
|
|
107
|
+
try {
|
|
108
|
+
await fastify.listen({ port: 3000, host: '0.0.0.0' })
|
|
109
|
+
console.log('Server listening on http://localhost:3000')
|
|
110
|
+
console.log('Try these endpoints:')
|
|
111
|
+
console.log(' GET /events - Basic SSE messages')
|
|
112
|
+
console.log(' GET /stream - Streaming with async generator')
|
|
113
|
+
console.log(' GET /live - Persistent connection with heartbeat')
|
|
114
|
+
console.log(' GET /replay - Messages with replay support')
|
|
115
|
+
} catch (err) {
|
|
116
|
+
fastify.log.error(err)
|
|
117
|
+
process.exit(1)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
start()
|