import type { FastifyInstance } from "fastify"; import { logInfo, type SseEvent, type SseService } from "@dpu/shared"; import { randomUUID } from "node:crypto"; export async function sseRoutes( fastify: FastifyInstance, { sseService, }: { sseService: SseService; }, ) { fastify.get( "/dpu/events", { schema: { description: "Register for WebSocket events", tags: ["ws"], hide: true, }, websocket: true, }, (socket, _request) => { const clientId = randomUUID(); const sendEvent = (event: SseEvent) => { if (socket.readyState === socket.OPEN) { socket.send(JSON.stringify({ event: event.type, data: event.data })); } }; sseService.addClient({ id: clientId, send: sendEvent }); socket.send(JSON.stringify({ event: "connected", data: "Connected" })); logInfo(`Connection for client ${clientId} established`); socket.on("close", () => { sseService.removeClient(clientId); logInfo(`Connection for client ${clientId} closed`); }); }, ); }