learning_ai_common_plat/packages/fastify-sse/src/per-request.ts
saravanakumardb1 e6ccaec2fe fix(fastify-sse): add X-Accel-Buffering header to per-request startSSE
Aligns with hub.ts which already includes this header. Prevents
nginx/Traefik from buffering SSE chunks behind a reverse proxy.
2026-03-29 12:47:13 -07:00

33 lines
1005 B
TypeScript

/**
* Per-request SSE helpers — single-request streaming pattern.
* Used by chat streaming and model comparison endpoints where
* one route handler streams SSE to one client.
*/
import type { FastifyReply } from 'fastify';
export function startSSE(reply: FastifyReply): void {
reply.raw.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
reply.hijack();
}
export function sendSSEEvent(reply: FastifyReply, event: string, data: unknown): void {
const payload = typeof data === 'string' ? data : JSON.stringify(data);
reply.raw.write(`event: ${event}\ndata: ${payload}\n\n`);
}
export function sendSSEData(reply: FastifyReply, data: unknown): void {
const payload = typeof data === 'string' ? data : JSON.stringify(data);
reply.raw.write(`data: ${payload}\n\n`);
}
export function endSSE(reply: FastifyReply): void {
reply.raw.write('data: [DONE]\n\n');
reply.raw.end();
}