Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: container stats not live updating (#139)
Kyle Mendelld4f773c6bf11
diff --git a/src/routes/api/containers/[id]/stats/stream/+server.ts b/src/routes/api/containers/[id]/stats/stream/+server.tsnew file mode 100644index 000000000..0aa748e63--- /dev/null+++ b/src/routes/api/containers/[id]/stats/stream/+server.ts@@ -0,0 +1,103 @@+import { getDockerClient } from '$lib/services/docker/core';+import { error } from '@sveltejs/kit';+import type { RequestHandler } from './$types';++export const GET: RequestHandler = async ({ params, request }) => {+ const { id } = params;+ const docker = getDockerClient();++ try {+ const container = docker.getContainer(id);+ const encoder = new TextEncoder();++ const stream = new ReadableStream({+ start(controller) {+ // Track if the controller is still active+ let isActive = true;+ let pollInterval: ReturnType<typeof setInterval>;+ let pingInterval: ReturnType<typeof setInterval>;++ // Clean up function to handle all interval clearing+ const cleanup = () => {+ isActive = false;+ clearInterval(pollInterval);+ clearInterval(pingInterval);+ };++ // Listen for client disconnects+ request.signal.addEventListener('abort', cleanup);++ // Poll container stats+ pollInterval = setInterval(async () => {+ if (!isActive) return;++ try {+ // Get container stats+ const stats = await container.stats({ stream: false });++ // Check if still active before sending+ if (!isActive) return;++ try {+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(stats)}\n\n`));+ } catch (err) {+ // Controller is closed+ if (err && typeof err === 'object' && 'code' in err && (err as any).code === 'ERR_INVALID_STATE') {+ cleanup();+ } else {+ console.error('Enqueue error:', err);+ }+ }+ } catch (err) {+ if (!isActive) return;++ if ((err as any).statusCode === 404) {+ try {+ controller.enqueue(encoder.encode(`data: ${JSON.stringify({ removed: true })}\n\n`));+ cleanup();+ controller.close();+ } catch (e) {+ // Ignore errors if controller is already closed+ cleanup();+ }+ } else {+ console.error('Container stats error:', err);+ }+ }+ }, 2000);++ // Keep-alive ping+ pingInterval = setInterval(() => {+ if (!isActive) return;++ try {+ controller.enqueue(encoder.encode(':\n\n'));+ } catch (err) {+ if (err && typeof err === 'object' && 'code' in err && (err as any).code === 'ERR_INVALID_STATE') {+ cleanup();+ }+ }+ }, 15000);++ // Return cleanup function+ return cleanup;+ },++ cancel() {+ // This is called when the client disconnects+ // Cleanup is handled by the return function from start()+ }+ });++ return new Response(stream, {+ headers: {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive'+ }+ });+ } catch (err) {+ console.error('Error streaming container stats:', err);+ throw error(500, 'Failed to stream container stats');+ }+};diff --git a/src/routes/containers/[id]/+page.svelte b/src/routes/containers/[id]/+page.svelteindex 88ac71080..b599f8fa3 100644--- a/src/routes/containers/[id]/+page.svelte+++ b/src/routes/containers/[id]/+page.svelte@@ -28,6 +28,7 @@let autoScrollLogs = $state(true);let logEventSource: EventSource | null = $state(null);+ let statsEventSource: EventSource | null = $state(null);function scrollLogsToBottom() {if (logsContainer) {@@ -89,8 +90,60 @@}}+ function startStatsStream() {+ if (statsEventSource || !container?.id || !container.state?.Running) return;++ try {+ const url = `/api/containers/${container.id}/stats/stream`;+ const eventSource = new EventSource(url);+ statsEventSource = eventSource;++ eventSource.onmessage = (event) => {+ if (!event.data) return;++ try {+ const statsData = JSON.parse(event.data);++ if (statsData.removed) {+ invalidateAll();+ return;+ }++ // Update stats in-place+ stats = statsData;+ } catch (err) {+ console.error('Error parsing stats data:', err);+ }+ };++ eventSource.onerror = (err) => {+ console.error('Stats EventSource error:', err);+ eventSource.close();+ statsEventSource = null;+ };+ } catch (error) {+ console.error('Failed to connect to stats stream:', error);+ }+ }++ function closeStatsStream() {+ if (statsEventSource) {+ statsEventSource.close();+ statsEventSource = null;+ }+ }++ $effect(() => {+ if (activeTab === 'stats' && container?.state?.Running) {+ startStatsStream();+ } else if (statsEventSource) {+ closeStatsStream();+ }+ });+onDestroy(() => {closeLogStream();+ closeStatsStream();});const calculateCPUPercent = (statsData: Docker.ContainerStats | null): number => {