Skip to content

fix: container stats not live updating#139

Merged
kmendell merged 2 commits intomainfrom
fix/container-stats
May 9, 2025
Merged

fix: container stats not live updating#139
kmendell merged 2 commits intomainfrom
fix/container-stats

Conversation

@kmendell
Copy link
Member

@kmendell kmendell commented May 8, 2025

Summary by CodeRabbit

  • New Features
    • Introduced real-time streaming of Docker container statistics on the container details page, updating stats automatically when the "stats" tab is active and the container is running.
  • Improvements
    • Enhanced connection handling to ensure stats streaming starts and stops appropriately based on user interaction and container state.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 8, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

A new server-sent events (SSE) API endpoint is introduced to stream Docker container statistics, with a corresponding client-side implementation in the Svelte page. The client establishes and manages an EventSource connection to receive live container stats, updating the UI reactively and handling connection lifecycle and container removal events.

Changes

File(s) Change Summary
src/routes/api/containers/[id]/stats/stream/+server.ts Added a GET request handler that streams Docker container stats as SSE, including keep-alives and removal events.
src/routes/containers/[id]/+page.svelte Added logic to manage an EventSource for stats streaming: connection setup/teardown, message handling, and reactivity.

Sequence Diagram(s)

sequenceDiagram
    participant UserBrowser as User Browser
    participant SveltePage as Svelte +page.svelte
    participant APIServer as /api/containers/[id]/stats/stream
    participant DockerClient as Docker Client

    UserBrowser->>SveltePage: Activate "stats" tab
    SveltePage->>APIServer: Open EventSource connection (GET /stats/stream)
    APIServer->>DockerClient: Fetch container stats (every 2s)
    DockerClient-->>APIServer: Return stats
    APIServer-->>SveltePage: Send SSE data event (stats JSON)
    SveltePage-->>UserBrowser: Update stats UI
    APIServer-->>SveltePage: Send keep-alive ping (every 15s)
    APIServer-->>SveltePage: Send "removed" event if container is deleted
    SveltePage->>SveltePage: Close EventSource on tab change or container stop
    SveltePage->>APIServer: EventSource disconnects (on close/error)
Loading

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

start(controller) {
// Track if the controller is still active
let isActive = true;
let pollInterval: ReturnType<typeof setInterval>;

Check failure

Code scanning / ESLint

Require `const` declarations for variables that are never reassigned after declared Error

'pollInterval' is never reassigned. Use 'const' instead.
// Track if the controller is still active
let isActive = true;
let pollInterval: ReturnType<typeof setInterval>;
let pingInterval: ReturnType<typeof setInterval>;

Check failure

Code scanning / ESLint

Require `const` declarations for variables that are never reassigned after declared Error

'pingInterval' is never reassigned. Use 'const' instead.
} catch (err) {
if (!isActive) return;

if ((err as any).statusCode === 404) {

Check failure

Code scanning / ESLint

Disallow the `any` type Error

Unexpected any. Specify a different type.
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ removed: true })}\n\n`));
cleanup();
controller.close();
} catch (e) {

Check failure

Code scanning / ESLint

Disallow unused variables Error

'e' is defined but never used.
try {
controller.enqueue(encoder.encode(':\n\n'));
} catch (err) {
if (err && typeof err === 'object' && 'code' in err && (err as any).code === 'ERR_INVALID_STATE') {

Check failure

Code scanning / ESLint

Disallow the `any` type Error

Unexpected any. Specify a different type.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🔭 Outside diff range comments (1)
src/routes/containers/[id]/+page.svelte (1)

738-744: 🧹 Nitpick (assertive)

Don’t hard-code eth0; choose the first available interface

Containers can have arbitrary interface names (e.g. eth1, enp0s3, veth…).
Selecting the first key avoids silently showing “0 B” on systems where eth0 is absent.

-											<div class="text-sm font-medium mt-1">{formatBytes(stats.networks?.eth0?.rx_bytes || 0)}</div>
+											{@const ifaces = Object.keys(stats.networks || {})}
+											{@const first = ifaces[0]}
+											<div class="text-sm font-medium mt-1">
+												{formatBytes(first ? stats.networks[first]?.rx_bytes || 0 : 0)}
+											</div>

Apply the same pattern for tx_bytes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e5d9903 and b3ac946.

📒 Files selected for processing (2)
  • src/routes/api/containers/[id]/stats/stream/+server.ts (1 hunks)
  • src/routes/containers/[id]/+page.svelte (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/routes/api/containers/[id]/stats/stream/+server.ts (1)
src/lib/services/docker/core.ts (1)
  • getDockerClient (24-32)
🪛 Biome (1.9.4)
src/routes/api/containers/[id]/stats/stream/+server.ts

[error] 17-17: This let declares a variable that is only assigned once.

'pollInterval' is only assigned here.

(lint/style/useConst)


[error] 18-18: This let declares a variable that is only assigned once.

'pingInterval' is only assigned here.

(lint/style/useConst)

🪛 GitHub Check: ESLint
src/routes/api/containers/[id]/stats/stream/+server.ts

[failure] 17-17: Require const declarations for variables that are never reassigned after declared
'pollInterval' is never reassigned. Use 'const' instead.


[failure] 18-18: Require const declarations for variables that are never reassigned after declared
'pingInterval' is never reassigned. Use 'const' instead.


[failure] 54-54: Disallow the any type
Unexpected any. Specify a different type.


[failure] 59-59: Disallow unused variables
'e' is defined but never used.


[failure] 76-76: Disallow the any type
Unexpected any. Specify a different type.

🪛 GitHub Actions: Svelte Check
src/routes/api/containers/[id]/stats/stream/+server.ts

[error] 45-45: 'err' is of type 'unknown'. This causes a type error when accessing 'err.code'.

Comment on lines +5 to +11
export const GET: RequestHandler = async ({ params, request }) => {
const { id } = params;
const docker = getDockerClient();

try {
const container = docker.getContainer(id);
const encoder = new TextEncoder();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Validate id parameter early to avoid empty-ID look-ups

If id is missing or an empty string, docker.getContainer(id) will return a stub that later throws a 404.
Returning a 400 response early makes the failure explicit and saves unnecessary work.

+	if (!id) {
+		throw error(400, 'Container id is required');
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const GET: RequestHandler = async ({ params, request }) => {
const { id } = params;
const docker = getDockerClient();
try {
const container = docker.getContainer(id);
const encoder = new TextEncoder();
export const GET: RequestHandler = async ({ params, request }) => {
const { id } = params;
if (!id) {
throw error(400, 'Container id is required');
}
const docker = getDockerClient();
try {
const container = docker.getContainer(id);
const encoder = new TextEncoder();
🤖 Prompt for AI Agents (early access)
In src/routes/api/containers/[id]/stats/stream/+server.ts around lines 5 to 11,
the code does not validate the `id` parameter before using it to get a Docker
container, which can lead to unnecessary work and a less clear 404 error later.
Add an early check to verify that `id` is present and not an empty string; if it
is invalid, immediately return a 400 Bad Request response to explicitly indicate
the client error and avoid calling `docker.getContainer` with an empty or
missing ID.

Comment on lines +17 to +18
let pollInterval: ReturnType<typeof setInterval>;
let pingInterval: ReturnType<typeof setInterval>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Use const for non-reassigned interval handles

pollInterval and pingInterval are never reassigned after their initial setInterval call, so const is the correct declaration and satisfies Biome / ESLint.

-				let pollInterval: ReturnType<typeof setInterval>;
-				let pingInterval: ReturnType<typeof setInterval>;
+				const pollInterval: ReturnType<typeof setInterval> = setInterval(async () => { /* … */ }, 2000);
+				const pingInterval: ReturnType<typeof setInterval> = setInterval(() => { /* … */ }, 15000);

You can then delete the later assignments, only keeping the clearInterval calls.

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (1.9.4)

[error] 17-17: This let declares a variable that is only assigned once.

'pollInterval' is only assigned here.

(lint/style/useConst)


[error] 18-18: This let declares a variable that is only assigned once.

'pingInterval' is only assigned here.

(lint/style/useConst)

🪛 GitHub Check: ESLint

[failure] 17-17: Require const declarations for variables that are never reassigned after declared
'pollInterval' is never reassigned. Use 'const' instead.


[failure] 18-18: Require const declarations for variables that are never reassigned after declared
'pingInterval' is never reassigned. Use 'const' instead.

🤖 Prompt for AI Agents (early access)
In src/routes/api/containers/[id]/stats/stream/+server.ts around lines 17 to 18,
change the declarations of pollInterval and pingInterval from let to const since
they are assigned once and never reassigned. Remove any subsequent reassignments
to these variables, keeping only the clearInterval calls to properly clear the
intervals.

Comment on lines +54 to +66
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);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Eliminate any casts and unused variable

The (err as any).statusCode cast and unused catch variable e both violate the lint rules.

-					} catch (e) {
-						// Ignore errors if controller is already closed
-						cleanup();
-					}
+					} catch {
+						// Ignore errors if controller is already closed
+						cleanup();
+					}-						if ((err as any).statusCode === 404) {
+						if (typeof err === 'object' && err !== null && 'statusCode' in err && (err as { statusCode?: number }).statusCode === 404) {

This keeps TypeScript strict-null-safe without resorting to any.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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);
}
}
if (
typeof err === 'object' &&
err !== null &&
'statusCode' in err &&
(err as { statusCode?: number }).statusCode === 404
) {
try {
controller.enqueue(
encoder.encode(`data: ${JSON.stringify({ removed: true })}\n\n`)
);
cleanup();
controller.close();
} catch {
// Ignore errors if controller is already closed
cleanup();
}
} else {
console.error('Container stats error:', err);
}
🧰 Tools
🪛 GitHub Check: ESLint

[failure] 54-54: Disallow the any type
Unexpected any. Specify a different type.


[failure] 59-59: Disallow unused variables
'e' is defined but never used.

🤖 Prompt for AI Agents (early access)
In src/routes/api/containers/[id]/stats/stream/+server.ts around lines 54 to 66,
remove the use of the `any` cast on `err` by properly typing the error or using
a type guard to safely access `statusCode`. Also, eliminate the unused catch
variable `e` by either removing it or handling it appropriately. This will
comply with lint rules and maintain strict TypeScript type safety.

Comment on lines +21 to +29
const cleanup = () => {
isActive = false;
clearInterval(pollInterval);
clearInterval(pingInterval);
};

// Listen for client disconnects
request.signal.addEventListener('abort', cleanup);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Detach the abort listener during cleanup

addEventListener adds a strong reference to cleanup.
When the client disconnects we already call cleanup; removing the listener prevents a potential retain cycle and makes the intent explicit.

-				request.signal.addEventListener('abort', cleanup);
+				const { signal } = request;
+				signal.addEventListener('abort', cleanup);
…
					const cleanup = () => {
						isActive = false;
						clearInterval(pollInterval);
						clearInterval(pingInterval);
+						signal.removeEventListener('abort', cleanup);
					};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const cleanup = () => {
isActive = false;
clearInterval(pollInterval);
clearInterval(pingInterval);
};
// Listen for client disconnects
request.signal.addEventListener('abort', cleanup);
const cleanup = () => {
isActive = false;
clearInterval(pollInterval);
clearInterval(pingInterval);
// Detach the abort listener to avoid retain cycles
signal.removeEventListener('abort', cleanup);
};
// Listen for client disconnects
const { signal } = request;
signal.addEventListener('abort', cleanup);
🤖 Prompt for AI Agents (early access)
In src/routes/api/containers/[id]/stats/stream/+server.ts around lines 21 to 29,
the abort event listener added to request.signal is not removed during cleanup,
which can cause a retain cycle. Modify the cleanup function to also call
request.signal.removeEventListener('abort', cleanup) to detach the listener when
cleaning up, ensuring no lingering references remain.

Comment on lines +41 to +48
try {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(stats)}\n\n`));
} catch (err) {
// Controller is closed
if (err.code === 'ERR_INVALID_STATE') {
cleanup();
} else {
console.error('Enqueue error:', err);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Type-safely detect closed stream without using err.code

controller.enqueue throws a DOMException with name === 'InvalidStateError'; accessing err.code on an unknown value fails Svelte-check.

-			} catch (err) {
-				// Controller is closed
-				if (err.code === 'ERR_INVALID_STATE') {
+			} catch (err: unknown) {
+				if (err instanceof DOMException && err.name === 'InvalidStateError') {
 					cleanup();
 				} else {
 					console.error('Enqueue error:', err);
 				}
 			}

This removes the type error and the need for the any cast.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(stats)}\n\n`));
} catch (err) {
// Controller is closed
if (err.code === 'ERR_INVALID_STATE') {
cleanup();
} else {
console.error('Enqueue error:', err);
try {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(stats)}\n\n`));
} catch (err: unknown) {
if (err instanceof DOMException && err.name === 'InvalidStateError') {
cleanup();
} else {
console.error('Enqueue error:', err);
}
}
🧰 Tools
🪛 GitHub Actions: Svelte Check

[error] 45-45: 'err' is of type 'unknown'. This causes a type error when accessing 'err.code'.

🤖 Prompt for AI Agents (early access)
In src/routes/api/containers/[id]/stats/stream/+server.ts around lines 41 to 48,
the error handling for a closed stream incorrectly checks err.code, causing type
errors. Update the catch block to check if the caught error is a DOMException
and if its name property equals 'InvalidStateError' to detect a closed stream
safely without type assertions. This ensures type-safe error detection and
removes the need for any casting.

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') {

Check failure

Code scanning / ESLint

Disallow the `any` type Error

Unexpected any. Specify a different type.
@kmendell kmendell merged commit d4f773c into main May 9, 2025
6 of 7 checks passed
@kmendell kmendell deleted the fix/container-stats branch May 9, 2025 00:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant