From f4161b4f470d640960b3ea880bbd1746436553a3 Mon Sep 17 00:00:00 2001 From: CyberL1 Date: Tue, 14 Jan 2025 17:08:12 -0500 Subject: [PATCH] fix(server): container stats sending --- src/routes/containers/_id/stats.ts | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/routes/containers/_id/stats.ts b/src/routes/containers/_id/stats.ts index d514118..39acc2b 100644 --- a/src/routes/containers/_id/stats.ts +++ b/src/routes/containers/_id/stats.ts @@ -3,8 +3,27 @@ import { getContainer } from "#src/utils/containers.ts"; import type { FastifyInstance, FastifyRequest } from "fastify"; export default (fastify: FastifyInstance) => { - fastify.get("/", (req: FastifyRequest<{ Params: Container }>) => { - const container = getContainer(req.params.id); - return container.stats(); - }); + fastify.get( + "/", + async (req: FastifyRequest<{ Params: Container }>, reply) => { + const container = getContainer(req.params.id); + + reply.header("Content-Type", "text/event-stream"); + reply.header("Cache-Control", "no-cache"); + reply.header("Connection", "keep-alive"); + + const stream = await container.stats({ stream: true }); + + if (!stream) { + reply.status(500).send("Error fetching stats"); + return; + } + stream.on("data", (chunk) => { + reply.raw.write(`data: ${chunk.toString()}\n\n`); + }); + + stream.on("end", () => reply.raw.end()); + return stream; + }, + ); };