Skip to content

Commit 5074934

Browse files
Refactor SSE to use Hono's built-in streamSSE
1 parent e1bd93c commit 5074934

1 file changed

Lines changed: 8 additions & 21 deletions

File tree

backend/src/routes/sse.ts

Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Hono } from 'hono'
2-
import { stream } from 'hono/streaming'
2+
import { streamSSE } from 'hono/streaming'
33
import { sseAggregator } from '../services/sse-aggregator'
44
import { SSESubscribeSchema } from '@opencode-manager/shared/schemas'
55
import { logger } from '../utils/logger'
@@ -15,45 +15,32 @@ export function createSSERoutes() {
1515
const directories = directoriesParam ? directoriesParam.split(',').filter(Boolean) : []
1616
const clientId = `client_${Date.now()}_${Math.random().toString(36).slice(2)}`
1717

18-
c.header('Content-Type', 'text/event-stream')
19-
c.header('Cache-Control', 'no-cache, no-store, no-transform')
20-
c.header('Connection', 'keep-alive')
2118
c.header('X-Accel-Buffering', 'no')
2219

23-
return stream(c, async (writer) => {
24-
const encoder = new TextEncoder()
25-
const writeSSE = (event: string, data: string) => {
26-
const lines = []
27-
if (event) lines.push(`event: ${event}`)
28-
lines.push(`data: ${data}`)
29-
lines.push('')
30-
lines.push('')
31-
writer.write(encoder.encode(lines.join('\n')))
32-
}
33-
20+
return streamSSE(c, async (stream) => {
3421
const cleanup = sseAggregator.addClient(
3522
clientId,
36-
(event, data) => {
37-
writeSSE(event, data)
23+
async (event, data) => {
24+
await stream.writeSSE({ event, data })
3825
},
3926
directories
4027
)
4128

42-
const heartbeatInterval = setInterval(() => {
29+
const heartbeatInterval = setInterval(async () => {
4330
try {
44-
writeSSE('heartbeat', JSON.stringify({ timestamp: Date.now() }))
31+
await stream.writeSSE({ event: 'heartbeat', data: JSON.stringify({ timestamp: Date.now() }) })
4532
} catch {
4633
clearInterval(heartbeatInterval)
4734
}
4835
}, HEARTBEAT_INTERVAL_MS)
4936

50-
writer.onAbort(() => {
37+
stream.onAbort(() => {
5138
clearInterval(heartbeatInterval)
5239
cleanup()
5340
})
5441

5542
try {
56-
writeSSE('connected', JSON.stringify({ clientId, directories, ...sseAggregator.getConnectionStatus() }))
43+
await stream.writeSSE({ event: 'connected', data: JSON.stringify({ clientId, directories, ...sseAggregator.getConnectionStatus() }) })
5744
} catch (err) {
5845
logger.error(`Failed to send SSE connected event for ${clientId}:`, err)
5946
}

0 commit comments

Comments
 (0)