Implementing Memory Usage and Traffic Monitoring in Clash Verge Rev

Clash Verge Rev gathers real-time memory and traffic statistics from the Mihomo core via WebSocket connections, exposing them through the useMemoryData and useTrafficData React hooks.

The clash-verge-rev/clash-verge-rev repository implements a high-performance monitoring subsystem that streams metrics from the underlying proxy engine without blocking the main thread. This article breaks down the architecture, key hooks, and data sampling strategies used to implement memory usage and traffic monitoring in Clash Verge Rev.

Architecture Overview

The monitoring layer sits between the Tauri backend and the React frontend, utilizing the tauri-plugin-mihomo-api to establish persistent WebSocket connections. Two primary hooks—useMemoryData and useTrafficData—abstract the complexity of connection management, reconnection logic, and data normalization.

Both hooks rely on useMihomoWsSubscription, a generic subscription wrapper that handles storage caching keyed by date (storageKey and buildSubscriptKey), automatic reconnection scheduling, and fallback data emission on errors.

Monitoring Memory Usage in Clash Verge Rev

The useMemoryData Hook

Located at src/hooks/use-memory-data.ts, this hook opens a WebSocket to the getClashMemory channel and returns the latest memory snapshot containing inuse (current consumption in KB) and optional oslimit (OS-imposed limit).

export const useMemoryData = () => {
  const { response, refresh } = useMihomoWsSubscription<IMemoryUsageItem>({
    storageKey: "mihomo_memory_date",
    buildSubscriptKey: (date) => `getClashMemory-${date}`,
    fallbackData: { inuse: 0 },
    connect: () => MihomoWebSocket.connect_memory(),
    setupHandlers: ({ next, scheduleReconnect }) => ({
      handleMessage: (data) => {
        if (data.startsWith("Websocket error")) {
          next(data, { inuse: 0 });
          void scheduleReconnect();
          return;
        }
        try {
          const parsed = JSON.parse(data) as IMemoryUsageItem;
          next(null, parsed);
        } catch {
          next(new Error("Parse error"), { inuse: 0 });
        }
      },
    }),
  });

  return { response, refreshGetClashMemory: refresh };
};

WebSocket Connection Handling

The hook delegates low-level WebSocket management to useMihomoWsSubscription. When the connection drops, scheduleReconnect queues a reconnection attempt while emitting fallbackData to prevent UI flickering. The storageKey ensures that if the user reloads the application within the same day, the subscription resumes using the cached date identifier.

Implementation Example

To display current memory usage in a React component:

import { useMemoryData } from "@/hooks/use-memory-data";

export const MemoryUsage = () => {
  const { response } = useMemoryData();

  return (
    <div>
      <h3>Memory Usage</h3>
      <p>
        In‑use: {(response?.inuse ?? 0).toLocaleString()} KB
        {response?.oslimit && (
          <> / {response.oslimit.toLocaleString()} KB (OS limit)</>
        )}
      </p>
    </div>
  );
};

Real-Time Traffic Monitoring Pipeline

Traffic Data Sampling

The TrafficDataSampler class in src/utils/traffic-sampler.ts manages high-frequency traffic data without consuming excessive memory. It maintains a ring buffer of raw traffic points (up/down bytes with timestamps) and applies dynamic compression based on configurable time windows.

Key capabilities include:

  • O(1) amortized trimming using head indices to discard stale entries beyond rawDataMinutes and compressedDataMinutes.
  • Dynamic compression that aggregates compressionRatio points into single compressed records, reducing memory footprint while preserving trend accuracy.
  • Range queries via getDataForTimeRange(minutes), returning merged raw and compressed points for any requested window.

Worker-Backed Monitoring

The useTrafficMonitorEnhanced hook in src/hooks/use-traffic-monitor.ts instantiates a TrafficWorkerClient that offloads sampling to a Web Worker (src/services/traffic-monitor-worker.ts). When Web Workers are unavailable, it falls back to an inline sampler running on the main thread.

Features of this layer:

  • Reference counting (ReferenceCounter) ensures the worker terminates only when no components remain subscribed.
  • Snapshot throttling (snapshotIntervalMs) prevents UI overload during traffic bursts by limiting update frequency.
  • Graph data API exposing dataPoints, requestRange, appendData, and clearData for visualization components.

The useTrafficData Hook

Located at src/hooks/use-traffic-data.ts, this hook bridges the WebSocket traffic stream with the sampling pipeline:

export const useTrafficData = (options?: { enabled?: boolean }) => {
  const { graphData: { appendData } } = useTrafficMonitorEnhanced({
    subscribe: false,
    enabled,
  });

  const { response, refresh } = useMihomoWsSubscription<ITrafficItem>({
    storageKey: "mihomo_traffic_date",
    buildSubscriptKey: (date) => `getClashTraffic-${date}`,
    fallbackData: { up: 0, down: 0 },
    connect: () => MihomoWebSocket.connect_traffic(),
    setupHandlers: ({ next, scheduleReconnect }) => ({
      handleMessage: (data) => {
        if (data.startsWith("Websocket error")) {
          next(data, { up: 0, down: 0 });
          void scheduleReconnect();
          return;
        }
        try {
          const parsed = JSON.parse(data) as Traffic;
          appendData(parsed);          // feed into sampler
          next(null, parsed);
        } catch {
          next(new Error("Parse error"), { up: 0, down: 0 });
        }
      },
    }),
  });

  return { response, refreshGetClashTraffic: refresh };
};

Each incoming traffic record is immediately pushed into the TrafficDataSampler via appendData, while the hook simultaneously returns the latest raw values for instantaneous display.

End-to-End Data Flow

The complete monitoring pipeline operates as follows:

  1. Subscription initiation: Components invoke useMemoryData or useTrafficData, triggering useMihomoWsSubscription to open WebSocket connections to getClashMemory or getClashTraffic.

  2. Data ingestion: Raw JSON payloads from the Mihomo core are parsed and validated. Memory data flows directly to the React state, while traffic data is forwarded to appendData.

  3. Sampling and compression: The TrafficDataSampler (running in a Web Worker when possible) maintains ring buffers, applies compression ratios, and trims stale data in O(1) time.

  4. Throttled snapshots: useTrafficMonitorEnhanced throttles high-frequency updates using snapshotIntervalMs, ensuring the UI receives manageable update rates even during network bursts.

  5. Visualization: Components consume graphData (for traffic trends) or response (for instantaneous memory usage) to render charts, tables, or status indicators.

Key Files and Responsibilities

File Role
src/hooks/use-memory-data.ts Opens the getClashMemory WebSocket, parses memory JSON, and exposes the latest snapshot via useMemoryData.
src/hooks/use-traffic-data.ts Consumes the traffic WebSocket and forwards parsed data to the sampling pipeline via useTrafficMonitorEnhanced.
src/hooks/use-traffic-monitor.ts Instantiates the worker client, manages reference counting, and throttles snapshot updates for the UI.
src/services/traffic-monitor-worker.ts Web Worker script that runs TrafficDataSampler off the main thread, handling init, append, clear, and setRange messages.
src/utils/traffic-sampler.ts Core sampling logic: ring buffer management, dynamic compression, and range queries for traffic data points.
src/utils/traffic-diagnostics.ts Optional diagnostic utilities for debugging sampler behavior and memory usage.
src/hooks/use-mihomo-ws-subscription.ts Generic WebSocket subscription manager used by both memory and traffic hooks, handling reconnection and date-keyed caching.

Summary

  • Clash Verge Rev implements real-time monitoring via the tauri-plugin-mihomo-api, streaming metrics from the Mihomo core through persistent WebSockets.
  • useMemoryData in src/hooks/use-memory-data.ts provides instantaneous memory snapshots with automatic reconnection and fallback handling.
  • useTrafficData in src/hooks/use-traffic-data.ts feeds high-frequency traffic updates into a TrafficDataSampler that compresses and throttles data for efficient visualization.
  • Web Workers offload sampling calculations in src/services/traffic-monitor-worker.ts, preventing UI blocking during heavy network activity.
  • Reference counting and snapshot throttling ensure resources are released when components unmount and the UI updates at sustainable rates.

Frequently Asked Questions

How does Clash Verge Rev handle WebSocket reconnections when the Mihomo core restarts?

The useMihomoWsSubscription hook in src/hooks/use-mihomo-ws-subscription.ts automatically schedules reconnections using the scheduleReconnect callback. When a "Websocket error" message is detected, the hook emits fallback data (zero values) to maintain UI stability and then initiates a reconnection attempt without manual intervention.

What is the difference between useTrafficData and useTrafficMonitorEnhanced?

useTrafficData in src/hooks/use-traffic-data.ts is the high-level hook that opens the WebSocket to the Mihomo core and parses incoming traffic JSON. useTrafficMonitorEnhanced in src/hooks/use-traffic-monitor.ts is the underlying infrastructure that manages the TrafficDataSampler (often in a Web Worker), handles reference counting, and throttles snapshot updates to prevent UI overload.

How does the traffic sampler prevent memory leaks with high-frequency data?

The TrafficDataSampler class in src/utils/traffic-sampler.ts uses a ring buffer with O(1) amortized trimming based on configurable time windows (rawDataMinutes and compressedDataMinutes). It dynamically compresses older data points into aggregated records, ensuring the buffer size remains bounded regardless of how long the application runs or how high the network throughput becomes.

Can I use these hooks outside of the main dashboard components?

Yes, both useMemoryData and useTrafficData are designed as reusable React hooks that can be imported into any component within the Clash Verge Rev application. The useTrafficMonitorEnhanced hook uses reference counting to ensure that the underlying Web Worker or sampler instance is shared efficiently across multiple components, making it safe to use these hooks in modular UI architectures without creating duplicate WebSocket connections.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →