Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat: Add WebSocket push interval control and optimize client-side rule stats data handling.

luolei87b788c2eb1e
diff --git a/apps/collector/src/websocket.ts b/apps/collector/src/websocket.ts
index a3515e4..1818ae8 100644
--- a/apps/collector/src/websocket.ts
+++ b/apps/collector/src/websocket.ts
@@ -8,6 +8,7 @@ export interface WebSocketMessage {
backendId?: number;
start?: string;
end?: string;
+ minPushIntervalMs?: number;
includeTrend?: boolean;
trendMinutes?: number;
trendBucketMinutes?: number;
@@ -82,6 +83,8 @@ interface ClientInfo {
ws: WebSocket;
backendId: number | null; // null means use active backend
range: ClientRange;
+ minPushIntervalMs: number;
+ lastSentAt: number;
trend: ClientTrend;
deviceDetail: ClientDeviceDetail;
proxyDetail: ClientProxyDetail;
@@ -119,6 +122,8 @@ export class StatsWebSocketServer {
ws,
backendId: null,
range: {},
+ minPushIntervalMs: 0,
+ lastSentAt: 0,
trend: null,
deviceDetail: null,
proxyDetail: null,
@@ -159,6 +164,13 @@ export class StatsWebSocketServer {
}
}
+ if (msg.minPushIntervalMs !== undefined) {
+ clientInfo.minPushIntervalMs = this.parseMinPushIntervalMs(
+ msg.minPushIntervalMs,
+ clientInfo.minPushIntervalMs,
+ );
+ }
+
if (
msg.includeTrend !== undefined ||
msg.trendMinutes !== undefined ||
@@ -305,6 +317,15 @@ export class StatsWebSocketServer {
};
}
+ private parseMinPushIntervalMs(
+ value: number,
+ fallback: number,
+ ): number {
+ if (!Number.isFinite(value)) return fallback;
+ // Keep range conservative to avoid client misuse.
+ return Math.max(0, Math.min(60_000, Math.floor(value)));
+ }
+
private shouldIncludeRealtime(range: ClientRange): boolean {
if (!range.start && !range.end) {
return true;
@@ -854,6 +875,7 @@ export class StatsWebSocketServer {
timestamp: new Date().toISOString(),
};
ws.send(JSON.stringify(message));
+ clientInfo.lastSentAt = Date.now();
} catch (err) {
console.error('[WebSocket] Error sending stats:', err);
}
@@ -877,6 +899,13 @@ export class StatsWebSocketServer {
for (const [ws, clientInfo] of this.clients) {
if (ws.readyState !== WebSocket.OPEN) continue;
+ if (!force && clientInfo.minPushIntervalMs > 0) {
+ const elapsed = now - clientInfo.lastSentAt;
+ if (elapsed < clientInfo.minPushIntervalMs) {
+ continue;
+ }
+ }
+
const resolvedBackendId = this.resolveBackendId(clientInfo.backendId);
if (resolvedBackendId === null) continue;
@@ -930,6 +959,7 @@ export class StatsWebSocketServer {
timestamp: new Date().toISOString(),
};
ws.send(JSON.stringify(message));
+ clientInfo.lastSentAt = now;
sentCount++;
}
diff --git a/apps/web/app/[locale]/page.tsx b/apps/web/app/[locale]/page.tsx
index fdddd7f..f26580f 100644
--- a/apps/web/app/[locale]/page.tsx
+++ b/apps/web/app/[locale]/page.tsx
@@ -83,7 +83,6 @@ import type {
CountryStats,
DeviceStats,
ProxyStats,
- RuleStats,
} from "@clashmaster/shared";
function formatTimeAgo(date: Date, t: any): string {
@@ -249,13 +248,11 @@ const ProxiesContent = memo(function ProxiesContent({
});
const RulesContent = memo(function RulesContent({
- data,
activeBackendId,
timeRange,
backendStatus,
autoRefresh,
}: {
- data?: RuleStats[];
activeBackendId?: number;
timeRange: TimeRange;
backendStatus: BackendStatus;
@@ -264,7 +261,6 @@ const RulesContent = memo(function RulesContent({
return (
<div className="space-y-6">
<InteractiveRuleStats
- data={data}
activeBackendId={activeBackendId}
timeRange={timeRange}
backendStatus={backendStatus}
@@ -357,7 +353,6 @@ export default function DashboardPage() {
activeTab === "domains" ||
activeTab === "countries" ||
activeTab === "proxies" ||
- activeTab === "rules" ||
activeTab === "devices";
const backendsQuery = useQuery({
@@ -534,13 +529,14 @@ export default function DashboardPage() {
// Only reduce to 30s on lightweight WS tabs (overview/countries).
useEffect(() => {
if (!autoRefresh || !isRollingTimePreset(timePreset)) return;
- const intervalMs = shouldReducePolling ? 30000 : 5000;
+ const intervalMs =
+ activeTab === "rules" ? 30000 : shouldReducePolling ? 30000 : 5000;
const interval = setInterval(() => {
setAutoRefreshTick((tick) => tick + 1);
setTimeRange(getPresetTimeRange(timePreset));
}, intervalMs);
return () => clearInterval(interval);
- }, [autoRefresh, shouldReducePolling, timePreset]);
+ }, [activeTab, autoRefresh, shouldReducePolling, timePreset]);
// Fixed presets: keep HTTP polling only when WS realtime is not active.
useEffect(() => {
@@ -593,7 +589,6 @@ export default function DashboardPage() {
case "rules":
return (
<RulesContent
- data={data?.ruleStats}
activeBackendId={activeBackendId}
timeRange={timeRange}
backendStatus={backendStatus}
diff --git a/apps/web/components/interactive-rule-stats.tsx b/apps/web/components/interactive-rule-stats.tsx
index e91c295..ac91e4b 100644
--- a/apps/web/components/interactive-rule-stats.tsx
+++ b/apps/web/components/interactive-rule-stats.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useCallback, useMemo, useEffect } from "react";
+import { useState, useCallback, useMemo, useEffect, useRef, startTransition } from "react";
import { Server, ChevronLeft, ChevronRight, Loader2, BarChart3, Link2, Rows3, ArrowUpDown, ArrowDown, ArrowUp, Globe, Waypoints, ChevronDown, ChevronUp } from "lucide-react";
import { useTranslations } from "next-intl";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
@@ -61,6 +61,10 @@ const CHART_COLORS = [
const PAGE_SIZE_OPTIONS = [10, 20, 50] as const;
type PageSize = typeof PAGE_SIZE_OPTIONS[number];
const DETAIL_QUERY_STALE_MS = 30_000;
+const RULE_DETAIL_WS_MERGE_MS = 5_000;
+const RULE_DETAIL_WS_MIN_PUSH_MS = 5_000;
+const EMPTY_DOMAINS: DomainStats[] = [];
+const EMPTY_IPS: IPStats[] = [];
interface RuleChartItem {
name: string;
@@ -141,7 +145,7 @@ export function InteractiveRuleStats({
const domainsT = useTranslations("domains");
const ipsT = useTranslations("ips");
const backendT = useTranslations("dashboard");
- const stableTimeRange = useStableTimeRange(timeRange);
+ const stableTimeRange = useStableTimeRange(timeRange, { roundToMinute: true });
const detailTimeRange = stableTimeRange;
const ruleListQuery = useQuery({
@@ -167,6 +171,10 @@ export function InteractiveRuleStats({
const [clashRules, setClashRules] = useState<ClashRulesResponse | null>(null);
const [wsRuleDomains, setWsRuleDomains] = useState<DomainStats[] | null>(null);
const [wsRuleIPs, setWsRuleIPs] = useState<IPStats[] | null>(null);
+ const pendingRuleDomainsRef = useRef<DomainStats[] | null>(null);
+ const pendingRuleIPsRef = useRef<IPStats[] | null>(null);
+ const detailFlushTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const lastDetailFlushAtRef = useRef(0);
// Sort states
const [domainSortKey, setDomainSortKey] = useState<DomainSortKey>("totalDownload");
@@ -294,31 +302,100 @@ export function InteractiveRuleStats({
setExpandedIP(newExpanded);
};
+ const flushPendingRuleDetails = useCallback(() => {
+ detailFlushTimerRef.current = null;
+ const nextDomains = pendingRuleDomainsRef.current;
+ const nextIPs = pendingRuleIPsRef.current;
+ pendingRuleDomainsRef.current = null;
+ pendingRuleIPsRef.current = null;
+ if (nextDomains || nextIPs) {
+ startTransition(() => {
+ if (nextDomains) {
+ setWsRuleDomains(nextDomains);
+ }
+ if (nextIPs) {
+ setWsRuleIPs(nextIPs);
+ }
+ });
+ }
+ lastDetailFlushAtRef.current = Date.now();
+ }, []);
+
+ const enqueueRuleDetailUpdate = useCallback((
+ domains: DomainStats[] | undefined,
+ ips: IPStats[] | undefined,
+ ) => {
+ if (domains) {
+ pendingRuleDomainsRef.current = domains;
+ }
+ if (ips) {
+ pendingRuleIPsRef.current = ips;
+ }
+
+ const now = Date.now();
+ const elapsed = now - lastDetailFlushAtRef.current;
+ if (elapsed >= RULE_DETAIL_WS_MERGE_MS) {
+ flushPendingRuleDetails();
+ return;
+ }
+ if (detailFlushTimerRef.current) {
+ return;
+ }
+ detailFlushTimerRef.current = setTimeout(() => {
+ flushPendingRuleDetails();
+ }, RULE_DETAIL_WS_MERGE_MS - elapsed);
+ }, [flushPendingRuleDetails]);
+
const wsDetailEnabled = autoRefresh && !!activeBackendId && !!selectedRule;
const { status: wsDetailStatus } = useStatsWebSocket({
backendId: activeBackendId,
range: detailTimeRange,
+ minPushIntervalMs: RULE_DETAIL_WS_MIN_PUSH_MS,
includeRuleDetails: wsDetailEnabled,
ruleName: selectedRule ?? undefined,
ruleDetailLimit: 5000,
+ trackLastMessage: false,
enabled: wsDetailEnabled,
onMessage: useCallback((stats: StatsSummary) => {
if (!selectedRule) return;
if (stats.ruleDetailName !== selectedRule) return;
- if (stats.ruleDomains) {
- setWsRuleDomains(stats.ruleDomains);
+ if (stats.ruleDomains || stats.ruleIPs) {
+ enqueueRuleDetailUpdate(stats.ruleDomains, stats.ruleIPs);
}
- if (stats.ruleIPs) {
- setWsRuleIPs(stats.ruleIPs);
- }
- }, [selectedRule]),
+ }, [enqueueRuleDetailUpdate, selectedRule]),
});
useEffect(() => {
setWsRuleDomains(null);
setWsRuleIPs(null);
+ pendingRuleDomainsRef.current = null;
+ pendingRuleIPsRef.current = null;
+ lastDetailFlushAtRef.current = 0;
+ if (detailFlushTimerRef.current) {
+ clearTimeout(detailFlushTimerRef.current);
+ detailFlushTimerRef.current = null;
+ }
}, [selectedRule, activeBackendId]);
+ useEffect(() => {
+ if (wsDetailEnabled) return;
+ pendingRuleDomainsRef.current = null;
+ pendingRuleIPsRef.current = null;
+ lastDetailFlushAtRef.current = 0;
+ if (detailFlushTimerRef.current) {
+ clearTimeout(detailFlushTimerRef.current);
+ detailFlushTimerRef.current = null;
+ }
+ }, [wsDetailEnabled]);
+
+ useEffect(() => {
+ return () => {
+ if (detailFlushTimerRef.current) {
+ clearTimeout(detailFlushTimerRef.current);
+ }
+ };
+ }, []);
+
const hasWsRuleDetails =
wsDetailEnabled &&
wsDetailStatus === "connected" &&
@@ -501,8 +578,12 @@ export function InteractiveRuleStats({
return chartData.find(r => r.rawName === selectedRule);
}, [chartData, selectedRule]);
+ const isDomainsTab = activeTab === "domains";
+ const isIPsTab = activeTab === "ips";
+
// Filter, sort and paginate domains
const filteredDomains = useMemo(() => {
+ if (!isDomainsTab) return EMPTY_DOMAINS;
let result = ruleDomains;
if (domainSearch) {
result = ruleDomains.filter(d =>
@@ -519,21 +600,27 @@ export function InteractiveRuleStats({
}
return ((aValue as number) - (bValue as number)) * modifier;
});
- }, [ruleDomains, domainSearch, domainSortKey, domainSortOrder]);
+ }, [isDomainsTab, ruleDomains, domainSearch, domainSortKey, domainSortOrder]);
const paginatedDomains = useMemo(() => {
+ if (!isDomainsTab) return EMPTY_DOMAINS;
const start = (domainPage - 1) * domainPageSize;
return filteredDomains.slice(start, start + domainPageSize);
- }, [filteredDomains, domainPage, domainPageSize]);
+ }, [isDomainsTab, filteredDomains, domainPage, domainPageSize]);
- const domainTotalPages = Math.ceil(filteredDomains.length / domainPageSize);
+ const domainTotalPages = isDomainsTab
+ ? Math.max(1, Math.ceil(filteredDomains.length / domainPageSize))
+ : 1;
const totalFilteredDomainTraffic = useMemo(
- () => filteredDomains.reduce((sum, d) => sum + d.totalDownload + d.totalUpload, 0),
- [filteredDomains],
+ () => (isDomainsTab
+ ? filteredDomains.reduce((sum, d) => sum + d.totalDownload + d.totalUpload, 0)
+ : 0),
+ [isDomainsTab, filteredDomains],
);
// Filter, sort and paginate IPs
const filteredIPs = useMemo(() => {
+ if (!isIPsTab) return EMPTY_IPS;
let result = ruleIPs;
if (ipSearch) {
result = ruleIPs.filter(ip =>
@@ -551,17 +638,22 @@ export function InteractiveRuleStats({
}
return ((aValue as number) - (bValue as number)) * modifier;
});
- }, [ruleIPs, ipSearch, ipSortKey, ipSortOrder]);
+ }, [isIPsTab, ruleIPs, ipSearch, ipSortKey, ipSortOrder]);
const paginatedIPs = useMemo(() => {
+ if (!isIPsTab) return EMPTY_IPS;
const start = (ipPage - 1) * ipPageSize;
return filteredIPs.slice(start, start + ipPageSize);
- }, [filteredIPs, ipPage, ipPageSize]);
+ }, [isIPsTab, filteredIPs, ipPage, ipPageSize]);
- const ipTotalPages = Math.ceil(filteredIPs.length / ipPageSize);
+ const ipTotalPages = isIPsTab
+ ? Math.max(1, Math.ceil(filteredIPs.length / ipPageSize))
+ : 1;
const totalFilteredIPTraffic = useMemo(
- () => filteredIPs.reduce((sum, ip) => sum + ip.totalDownload + ip.totalUpload, 0),
- [filteredIPs],
+ () => (isIPsTab
+ ? filteredIPs.reduce((sum, ip) => sum + ip.totalDownload + ip.totalUpload, 0)
+ : 0),
+ [isIPsTab, filteredIPs],
);
// Chart data
diff --git a/apps/web/components/rule-chain-flow.tsx b/apps/web/components/rule-chain-flow.tsx
index f7f742f..e697870 100644
--- a/apps/web/components/rule-chain-flow.tsx
+++ b/apps/web/components/rule-chain-flow.tsx
@@ -71,6 +71,7 @@ interface UnifiedRuleChainFlowProps {
const COLUMN_WIDTH = 280;
const NODE_HEIGHT = 95;
const OTHER_NODES_OFFSET = 130;
+const RULE_CHAIN_FLOW_WS_MIN_PUSH_MS = 5000;
// ---------- Custom Edge ----------
@@ -875,7 +876,9 @@ function UnifiedRuleChainFlowInner({
const { status: wsStatus } = useStatsWebSocket({
backendId: activeBackendId,
range: stableRange,
+ minPushIntervalMs: RULE_CHAIN_FLOW_WS_MIN_PUSH_MS,
includeRuleChainFlow: wsEnabled,
+ trackLastMessage: false,
enabled: wsEnabled,
onMessage: useCallback((stats: StatsSummary) => {
if (!stats.ruleChainFlowAll) return;
diff --git a/apps/web/lib/websocket.ts b/apps/web/lib/websocket.ts
index 030ec8f..f86156b 100644
--- a/apps/web/lib/websocket.ts
+++ b/apps/web/lib/websocket.ts
@@ -14,6 +14,7 @@ interface WebSocketMessage {
interface UseStatsWebSocketOptions {
backendId?: number;
range?: TimeRange;
+ minPushIntervalMs?: number;
includeTrend?: boolean;
trendMinutes?: number;
trendBucketMinutes?: number;
@@ -39,6 +40,7 @@ interface UseStatsWebSocketOptions {
ipsPageSortBy?: string;
ipsPageSortOrder?: "asc" | "desc";
ipsPageSearch?: string;
+ trackLastMessage?: boolean;
enabled?: boolean;
onMessage?: (data: StatsSummary) => void;
onConnect?: () => void;
@@ -72,6 +74,7 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
const {
backendId,
range,
+ minPushIntervalMs,
includeTrend,
trendMinutes,
trendBucketMinutes,
@@ -97,6 +100,7 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
ipsPageSortBy,
ipsPageSortOrder,
ipsPageSearch,
+ trackLastMessage = true,
enabled = true,
} = options;
const [status, setStatus] = useState<ConnectionStatus>('disconnected');
@@ -112,10 +116,12 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
const onConnectRef = useRef(options.onConnect);
const onDisconnectRef = useRef(options.onDisconnect);
const onErrorRef = useRef(options.onError);
+ const trackLastMessageRef = useRef(trackLastMessage);
onMessageRef.current = options.onMessage;
onConnectRef.current = options.onConnect;
onDisconnectRef.current = options.onDisconnect;
onErrorRef.current = options.onError;
+ trackLastMessageRef.current = trackLastMessage;
const cleanup = useCallback(() => {
if (reconnectTimerRef.current) {
@@ -174,7 +180,9 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
const message = JSON.parse(event.data) as WebSocketMessage;
if (message.type === 'stats' && message.data) {
- setLastMessage(message.data);
+ if (trackLastMessageRef.current) {
+ setLastMessage(message.data);
+ }
onMessageRef.current?.(message.data);
} else if (message.type === 'pong') {
if (lastPingTimeRef.current > 0) {
@@ -229,6 +237,7 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
backendId,
start: range?.start,
end: range?.end,
+ minPushIntervalMs,
includeTrend,
trendMinutes,
trendBucketMinutes,
@@ -260,6 +269,7 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
backendId,
range?.start,
range?.end,
+ minPushIntervalMs,
includeTrend,
trendMinutes,
trendBucketMinutes,