/** * events.routes.ts * * Endpoint SSE (Server-Sent Events). * Mantém a conexão aberta e repassa eventos do `fastify.events` para o cliente. */ import fp from 'fastify-plugin'; import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; async function eventsRoutes(fastify: FastifyInstance): Promise { fastify.get('/', { schema: { tags: ['Dashboard'], summary: 'Stream de eventos em tempo real (SSE)', }, preHandler: [fastify.authenticate], handler: (request: FastifyRequest, reply: FastifyReply) => { // 1. Configura os headers para SSE reply.raw.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', }); reply.raw.write('\n'); // Garante envio do header imediato // Helper para formatar pacote SSE const sendEvent = (event: string, data: any) => { reply.raw.write(`event: ${event}\n`); reply.raw.write(`data: ${JSON.stringify(data)}\n\n`); }; // 2. Registra os listeners const onTicketCreated = (data: any) => sendEvent('ticket.created', data); const onTicketUpdated = (data: any) => sendEvent('ticket.updated', data); const onCommentAdded = (data: any) => sendEvent('comment.added', data); fastify.events.on('ticket.created', onTicketCreated); fastify.events.on('ticket.updated', onTicketUpdated); fastify.events.on('comment.added', onCommentAdded); // Ping a cada 30s para manter a conexão ativa (evitar timeout do LB/Nginx) const pingInterval = setInterval(() => { reply.raw.write(':\n\n'); // SSE comment block serve como heartbeat }, 30000); // 3. Limpeza quando o cliente desconecta request.raw.on('close', () => { clearInterval(pingInterval); fastify.events.off('ticket.created', onTicketCreated); fastify.events.off('ticket.updated', onTicketUpdated); fastify.events.off('comment.added', onCommentAdded); }); }, }); } export default eventsRoutes;