fix: add safeWrite guard and error handler for SSE socket
This commit is contained in:
@@ -104,22 +104,37 @@ export async function registerSseRoutes(fastify) {
|
||||
'X-Accel-Buffering': 'no',
|
||||
})
|
||||
|
||||
let closed = false
|
||||
|
||||
function safeWrite(chunk) {
|
||||
if (closed) return
|
||||
try {
|
||||
reply.raw.write(chunk)
|
||||
} catch {
|
||||
closed = true
|
||||
cleanUp()
|
||||
}
|
||||
}
|
||||
|
||||
const userId = request.user.sub
|
||||
const admin = isAdminUser(request.user)
|
||||
|
||||
reply.raw.write(formatHeartbit())
|
||||
safeWrite(formatHeartbit())
|
||||
|
||||
const heartbitTimer = setInterval(() => {
|
||||
reply.raw.write(formatHeartbit())
|
||||
safeWrite(formatHeartbit())
|
||||
}, 30_000)
|
||||
|
||||
const cleanup = buildSseListeners(userId, admin, fastify.eventBus, (chunk) => {
|
||||
reply.raw.write(chunk)
|
||||
})
|
||||
const removeListeners = buildSseListeners(userId, admin, fastify.eventBus, safeWrite)
|
||||
|
||||
request.raw.on('close', () => {
|
||||
function cleanUp() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
clearInterval(heartbitTimer)
|
||||
cleanup()
|
||||
})
|
||||
removeListeners()
|
||||
}
|
||||
|
||||
request.raw.on('close', cleanUp)
|
||||
request.raw.on('error', cleanUp)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user