Skip to content

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

chore: save temporary debug changes for websocket

luoleia4b2a758faf4
diff --git a/apps/collector/src/api.ts b/apps/collector/src/api.ts
index b123ad2..33bc95c 100644
--- a/apps/collector/src/api.ts
+++ b/apps/collector/src/api.ts
@@ -167,11 +167,14 @@ export class APIServer {
? realtimeStore.mergeProxyStats(backendId, dbProxyStats)
: dbProxyStats;
- const ruleStats = this.db.getRuleStats(
+ const dbRuleStats = this.db.getRuleStats(
backendId,
timeRange.start,
timeRange.end,
);
+ const ruleStats = includeRealtime
+ ? realtimeStore.mergeRuleStats(backendId, dbRuleStats)
+ : dbRuleStats;
const hourlyStats = this.db.getHourlyStats(
backendId,
24,
@@ -236,15 +239,27 @@ export class APIServer {
sortOrder?: string;
search?: string;
};
- return this.db.getDomainStatsPaginated(backendId, {
- offset: offset ? parseInt(offset) || 0 : 0,
- limit: limit ? parseInt(limit) || 50 : 50,
+ const parsedOffset = offset ? parseInt(offset) || 0 : 0;
+ const parsedLimit = limit ? parseInt(limit) || 50 : 50;
+ const stats = this.db.getDomainStatsPaginated(backendId, {
+ offset: parsedOffset,
+ limit: parsedLimit,
sortBy,
sortOrder,
search,
start: timeRange.start,
end: timeRange.end,
});
+ if (shouldIncludeRealtime(timeRange)) {
+ return realtimeStore.mergeDomainStatsPaginated(backendId, stats, {
+ offset: parsedOffset,
+ limit: parsedLimit,
+ sortBy,
+ sortOrder,
+ search,
+ });
+ }
+ return stats;
});
// Get IP statistics for a specific backend (paginated)
@@ -267,15 +282,27 @@ export class APIServer {
sortOrder?: string;
search?: string;
};
- return this.db.getIPStatsPaginated(backendId, {
- offset: offset ? parseInt(offset) || 0 : 0,
- limit: limit ? parseInt(limit) || 50 : 50,
+ const parsedOffset = offset ? parseInt(offset) || 0 : 0;
+ const parsedLimit = limit ? parseInt(limit) || 50 : 50;
+ const stats = this.db.getIPStatsPaginated(backendId, {
+ offset: parsedOffset,
+ limit: parsedLimit,
sortBy,
sortOrder,
search,
start: timeRange.start,
end: timeRange.end,
});
+ if (shouldIncludeRealtime(timeRange)) {
+ return realtimeStore.mergeIPStatsPaginated(backendId, stats, {
+ offset: parsedOffset,
+ limit: parsedLimit,
+ sortBy,
+ sortOrder,
+ search,
+ });
+ }
+ return stats;
});
// Get per-proxy traffic breakdown for a specific domain
@@ -429,13 +456,17 @@ export class APIServer {
}
const effectiveLimit = parseLimit(limit, 5000, 20000);
- return this.db.getProxyDomains(
+ const stats = this.db.getProxyDomains(
backendId,
chain,
effectiveLimit,
timeRange.start,
timeRange.end,
);
+ if (shouldIncludeRealtime(timeRange)) {
+ return realtimeStore.mergeProxyDomains(backendId, chain, stats, effectiveLimit);
+ }
+ return stats;
});
// Get IPs for a specific proxy/chain
@@ -457,13 +488,17 @@ export class APIServer {
}
const effectiveLimit = parseLimit(limit, 5000, 20000);
- return this.db.getProxyIPs(
+ const stats = this.db.getProxyIPs(
backendId,
chain,
effectiveLimit,
timeRange.start,
timeRange.end,
);
+ if (shouldIncludeRealtime(timeRange)) {
+ return realtimeStore.mergeProxyIPs(backendId, chain, stats, effectiveLimit);
+ }
+ return stats;
});
// Get proxy/chain statistics for a specific backend
@@ -499,7 +534,11 @@ export class APIServer {
return reply.status(404).send({ error: 'No backend specified or active' });
}
- return this.db.getRuleStats(backendId, timeRange.start, timeRange.end);
+ const stats = this.db.getRuleStats(backendId, timeRange.start, timeRange.end);
+ if (shouldIncludeRealtime(timeRange)) {
+ return realtimeStore.mergeRuleStats(backendId, stats);
+ }
+ return stats;
});
// Get domains for a specific rule
@@ -521,13 +560,17 @@ export class APIServer {
}
const effectiveLimit = parseLimit(limit, 5000, 20000);
- return this.db.getRuleDomains(
+ const stats = this.db.getRuleDomains(
backendId,
rule,
effectiveLimit,
timeRange.start,
timeRange.end,
);
+ if (shouldIncludeRealtime(timeRange)) {
+ return realtimeStore.mergeRuleDomains(backendId, rule, stats, effectiveLimit);
+ }
+ return stats;
});
// Get IPs for a specific rule
@@ -549,13 +592,17 @@ export class APIServer {
}
const effectiveLimit = parseLimit(limit, 5000, 20000);
- return this.db.getRuleIPs(
+ const stats = this.db.getRuleIPs(
backendId,
rule,
effectiveLimit,
timeRange.start,
timeRange.end,
);
+ if (shouldIncludeRealtime(timeRange)) {
+ return realtimeStore.mergeRuleIPs(backendId, rule, stats, effectiveLimit);
+ }
+ return stats;
});
// Get per-proxy traffic breakdown for a specific domain under a specific rule
@@ -763,7 +810,17 @@ export class APIServer {
return;
}
const { limit } = request.query as { limit?: string };
- return this.db.getDevices(backendId, parseInt(limit || '50'), timeRange.start, timeRange.end);
+ const effectiveLimit = parseLimit(limit, 50, 2000);
+ const stats = this.db.getDevices(
+ backendId,
+ effectiveLimit,
+ timeRange.start,
+ timeRange.end,
+ );
+ if (shouldIncludeRealtime(timeRange)) {
+ return realtimeStore.mergeDeviceStats(backendId, stats, effectiveLimit);
+ }
+ return stats;
});
app.get('/api/stats/devices/domains', async (request, reply) => {
@@ -778,13 +835,17 @@ export class APIServer {
const { sourceIP, limit } = request.query as { sourceIP: string; limit?: string };
if (!sourceIP) return [];
const effectiveLimit = parseLimit(limit, 5000, 20000);
- return this.db.getDeviceDomains(
+ const stats = this.db.getDeviceDomains(
backendId,
sourceIP,
effectiveLimit,
timeRange.start,
timeRange.end,
);
+ if (shouldIncludeRealtime(timeRange)) {
+ return realtimeStore.mergeDeviceDomains(backendId, sourceIP, stats, effectiveLimit);
+ }
+ return stats;
});
app.get('/api/stats/devices/ips', async (request, reply) => {
@@ -799,13 +860,17 @@ export class APIServer {
const { sourceIP, limit } = request.query as { sourceIP: string; limit?: string };
if (!sourceIP) return [];
const effectiveLimit = parseLimit(limit, 5000, 20000);
- return this.db.getDeviceIPs(
+ const stats = this.db.getDeviceIPs(
backendId,
sourceIP,
effectiveLimit,
timeRange.start,
timeRange.end,
);
+ if (shouldIncludeRealtime(timeRange)) {
+ return realtimeStore.mergeDeviceIPs(backendId, sourceIP, stats, effectiveLimit);
+ }
+ return stats;
});
// Get hourly statistics for a specific backend
diff --git a/apps/collector/src/collector.ts b/apps/collector/src/collector.ts
index 4ea7bbc..ec410b8 100644
--- a/apps/collector/src/collector.ts
+++ b/apps/collector/src/collector.ts
@@ -426,6 +426,7 @@ export function createCollector(
{
domain,
ip,
+ sourceIP,
chains,
rule,
rulePayload,
@@ -497,6 +498,7 @@ export function createCollector(
{
domain: existing.domain,
ip: existing.ip,
+ sourceIP: existing.sourceIP,
chains: existing.chains,
rule: existing.rule || 'Match',
rulePayload: existing.rulePayload || '',
diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.ts
index 77c0b5d..f885b73 100644
--- a/apps/collector/src/index.ts
+++ b/apps/collector/src/index.ts
@@ -158,7 +158,7 @@ function startCollector(backend: BackendConfig) {
geoService,
() => {
// Broadcast stats update via WebSocket when new data arrives
- wsServer.broadcastStats();
+ wsServer.broadcastStats(backend.id);
},
backend.id // Pass backend ID for data isolation
);
diff --git a/apps/collector/src/realtime.ts b/apps/collector/src/realtime.ts
index 69edbea..44c4f67 100644
--- a/apps/collector/src/realtime.ts
+++ b/apps/collector/src/realtime.ts
@@ -1,8 +1,10 @@
import type {
CountryStats,
+ DeviceStats,
DomainStats,
IPStats,
ProxyStats,
+ RuleStats,
StatsSummary,
TrafficTrendPoint,
} from '@clashmaster/shared';
@@ -28,6 +30,23 @@ type ProxyDelta = {
lastSeen: string;
};
+type DeviceDelta = {
+ sourceIP: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+};
+
+type RuleDelta = {
+ rule: string;
+ finalProxy: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+};
+
type CountryDelta = {
country: string;
countryName: string;
@@ -57,11 +76,17 @@ type IPDelta = {
lastSeen: string;
domains: Set<string>;
chains: Set<string>;
+ rules: Set<string>;
};
+function matchesChainPrefix(fullChain: string, chain: string): boolean {
+ return fullChain === chain || fullChain.startsWith(`${chain} > `);
+}
+
export type TrafficMeta = {
domain: string;
ip: string;
+ sourceIP?: string;
chains: string[];
rule: string;
rulePayload: string;
@@ -69,6 +94,22 @@ export type TrafficMeta = {
download: number;
};
+type DomainPageOptions = {
+ offset?: number;
+ limit?: number;
+ sortBy?: string;
+ sortOrder?: string;
+ search?: string;
+};
+
+type IPPageOptions = {
+ offset?: number;
+ limit?: number;
+ sortBy?: string;
+ sortOrder?: string;
+ search?: string;
+};
+
function toMinuteKey(tsMs: number): string {
const iso = new Date(tsMs).toISOString();
return `${iso.slice(0, 16)}:00`;
@@ -81,12 +122,88 @@ function bucketMinuteKey(minuteKey: string, bucketMinutes: number): string {
return `${minuteKey.slice(0, 14)}${String(bucketMinute).padStart(2, '0')}:00`;
}
+function normalizeSortOrder(order?: string): 'asc' | 'desc' {
+ return order?.toLowerCase() === 'asc' ? 'asc' : 'desc';
+}
+
+function compareString(a: string, b: string, order: 'asc' | 'desc'): number {
+ const delta = a.localeCompare(b);
+ return order === 'asc' ? delta : -delta;
+}
+
+function compareNumber(a: number, b: number, order: 'asc' | 'desc'): number {
+ const delta = a - b;
+ return order === 'asc' ? delta : -delta;
+}
+
+function compareTimestamp(a: string, b: string, order: 'asc' | 'desc'): number {
+ const aMs = Date.parse(a || '');
+ const bMs = Date.parse(b || '');
+ const safeA = Number.isFinite(aMs) ? aMs : 0;
+ const safeB = Number.isFinite(bMs) ? bMs : 0;
+ return compareNumber(safeA, safeB, order);
+}
+
+function matchesDomainSearch(domain: string, search: string): boolean {
+ if (!search) return true;
+ return domain.toLowerCase().includes(search);
+}
+
+function matchesIPSearch(ip: string, domains: Iterable<string>, search: string): boolean {
+ if (!search) return true;
+ if (ip.toLowerCase().includes(search)) return true;
+ for (const domain of domains) {
+ if (domain.toLowerCase().includes(search)) return true;
+ }
+ return false;
+}
+
+function sortDomains(data: DomainStats[], sortBy: string, sortOrder: 'asc' | 'desc'): DomainStats[] {
+ return data.sort((a, b) => {
+ switch (sortBy) {
+ case 'domain':
+ return compareString(a.domain, b.domain, sortOrder);
+ case 'totalUpload':
+ return compareNumber(a.totalUpload, b.totalUpload, sortOrder);
+ case 'totalConnections':
+ return compareNumber(a.totalConnections, b.totalConnections, sortOrder);
+ case 'lastSeen':
+ return compareTimestamp(a.lastSeen, b.lastSeen, sortOrder);
+ case 'totalDownload':
+ default:
+ return compareNumber(a.totalDownload, b.totalDownload, sortOrder);
+ }
+ });
+}
+
+function sortIPs(data: IPStats[], sortBy: string, sortOrder: 'asc' | 'desc'): IPStats[] {
+ return data.sort((a, b) => {
+ switch (sortBy) {
+ case 'ip':
+ return compareString(a.ip, b.ip, sortOrder);
+ case 'totalUpload':
+ return compareNumber(a.totalUpload, b.totalUpload, sortOrder);
+ case 'totalConnections':
+ return compareNumber(a.totalConnections, b.totalConnections, sortOrder);
+ case 'lastSeen':
+ return compareTimestamp(a.lastSeen, b.lastSeen, sortOrder);
+ case 'totalDownload':
+ default:
+ return compareNumber(a.totalDownload, b.totalDownload, sortOrder);
+ }
+ });
+}
+
export class RealtimeStore {
private summaryByBackend = new Map<number, SummaryDelta>();
private minuteByBackend = new Map<number, Map<string, MinuteBucket>>();
private domainByBackend = new Map<number, Map<string, DomainDelta>>();
private ipByBackend = new Map<number, Map<string, IPDelta>>();
private proxyByBackend = new Map<number, Map<string, ProxyDelta>>();
+ private deviceByBackend = new Map<number, Map<string, DeviceDelta>>();
+ private deviceDomainByBackend = new Map<number, Map<string, Map<string, DomainDelta>>>();
+ private deviceIPByBackend = new Map<number, Map<string, Map<string, IPDelta>>>();
+ private ruleByBackend = new Map<number, Map<string, RuleDelta>>();
private countryByBackend = new Map<number, Map<string, CountryDelta>>();
private maxMinutes: number;
@@ -180,6 +297,7 @@ export class RealtimeStore {
lastSeen,
domains: new Set<string>(),
chains: new Set<string>(),
+ rules: new Set<string>(),
};
ipDelta.totalUpload += meta.upload;
@@ -189,6 +307,7 @@ export class RealtimeStore {
const ipDomain = meta.domain || 'unknown';
if (ipDomain) ipDelta.domains.add(ipDomain);
if (fullChain) ipDelta.chains.add(fullChain);
+ if (ruleName) ipDelta.rules.add(ruleName);
ipMap.set(meta.ip, ipDelta);
}
@@ -212,6 +331,114 @@ export class RealtimeStore {
proxyDelta.totalConnections += connections;
proxyDelta.lastSeen = lastSeen;
proxyMap.set(proxyChain, proxyDelta);
+
+ const sourceIP = (meta.sourceIP || '').trim();
+ if (sourceIP) {
+ let deviceMap = this.deviceByBackend.get(backendId);
+ if (!deviceMap) {
+ deviceMap = new Map();
+ this.deviceByBackend.set(backendId, deviceMap);
+ }
+
+ const deviceDelta = deviceMap.get(sourceIP) || {
+ sourceIP,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ };
+ deviceDelta.totalUpload += meta.upload;
+ deviceDelta.totalDownload += meta.download;
+ deviceDelta.totalConnections += connections;
+ deviceDelta.lastSeen = lastSeen;
+ deviceMap.set(sourceIP, deviceDelta);
+
+ if (meta.domain) {
+ let sourceDomainMap = this.deviceDomainByBackend.get(backendId);
+ if (!sourceDomainMap) {
+ sourceDomainMap = new Map();
+ this.deviceDomainByBackend.set(backendId, sourceDomainMap);
+ }
+ let domainMap = sourceDomainMap.get(sourceIP);
+ if (!domainMap) {
+ domainMap = new Map();
+ sourceDomainMap.set(sourceIP, domainMap);
+ }
+
+ const domainDelta = domainMap.get(meta.domain) || {
+ domain: meta.domain,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ ips: new Set<string>(),
+ rules: new Set<string>(),
+ chains: new Set<string>(),
+ };
+ domainDelta.totalUpload += meta.upload;
+ domainDelta.totalDownload += meta.download;
+ domainDelta.totalConnections += connections;
+ domainDelta.lastSeen = lastSeen;
+ if (meta.ip) domainDelta.ips.add(meta.ip);
+ if (ruleName) domainDelta.rules.add(ruleName);
+ if (fullChain) domainDelta.chains.add(fullChain);
+ domainMap.set(meta.domain, domainDelta);
+ }
+
+ if (meta.ip) {
+ let sourceIPMap = this.deviceIPByBackend.get(backendId);
+ if (!sourceIPMap) {
+ sourceIPMap = new Map();
+ this.deviceIPByBackend.set(backendId, sourceIPMap);
+ }
+ let ipMap = sourceIPMap.get(sourceIP);
+ if (!ipMap) {
+ ipMap = new Map();
+ sourceIPMap.set(sourceIP, ipMap);
+ }
+
+ const ipDelta = ipMap.get(meta.ip) || {
+ ip: meta.ip,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ domains: new Set<string>(),
+ chains: new Set<string>(),
+ rules: new Set<string>(),
+ };
+ ipDelta.totalUpload += meta.upload;
+ ipDelta.totalDownload += meta.download;
+ ipDelta.totalConnections += connections;
+ ipDelta.lastSeen = lastSeen;
+ if (meta.domain) ipDelta.domains.add(meta.domain);
+ if (fullChain) ipDelta.chains.add(fullChain);
+ if (ruleName) ipDelta.rules.add(ruleName);
+ ipMap.set(meta.ip, ipDelta);
+ }
+ }
+
+ let ruleMap = this.ruleByBackend.get(backendId);
+ if (!ruleMap) {
+ ruleMap = new Map();
+ this.ruleByBackend.set(backendId, ruleMap);
+ }
+
+ const finalProxy = proxyChain || 'DIRECT';
+ const ruleDelta = ruleMap.get(ruleName) || {
+ rule: ruleName,
+ finalProxy,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ };
+ ruleDelta.finalProxy = finalProxy;
+ ruleDelta.totalUpload += meta.upload;
+ ruleDelta.totalDownload += meta.download;
+ ruleDelta.totalConnections += connections;
+ ruleDelta.lastSeen = lastSeen;
+ ruleMap.set(ruleName, ruleDelta);
}
recordCountryTraffic(
@@ -438,6 +665,241 @@ export class RealtimeStore {
.slice(0, limit);
}
+ mergeDomainStatsPaginated(
+ backendId: number,
+ base: { data: DomainStats[]; total: number },
+ opts: DomainPageOptions = {},
+ ): { data: DomainStats[]; total: number } {
+ const domainMap = this.domainByBackend.get(backendId);
+ if (!domainMap || domainMap.size === 0) return base;
+
+ const offset = Math.max(0, opts.offset ?? 0);
+ const limit = Math.max(1, (opts.limit ?? base.data.length) || 50);
+ const sortBy = opts.sortBy || 'totalDownload';
+ const sortOrder = normalizeSortOrder(opts.sortOrder);
+ const search = (opts.search || '').trim().toLowerCase();
+
+ const merged = new Map<string, DomainStats>();
+ for (const item of base.data) {
+ if (!matchesDomainSearch(item.domain, search)) continue;
+ merged.set(item.domain, { ...item });
+ }
+
+ let addedCount = 0;
+ for (const [domain, delta] of domainMap) {
+ if (!matchesDomainSearch(domain, search)) continue;
+
+ const existing = merged.get(domain);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const ips = new Set(existing.ips || []);
+ for (const ip of delta.ips) ips.add(ip);
+ existing.ips = Array.from(ips);
+ const rules = new Set(existing.rules || []);
+ for (const rule of delta.rules) rules.add(rule);
+ existing.rules = Array.from(rules);
+ const chains = new Set(existing.chains || []);
+ for (const chain of delta.chains) chains.add(chain);
+ existing.chains = Array.from(chains);
+ continue;
+ }
+
+ // For non-first pages, avoid injecting unknown new rows that can shift boundaries.
+ if (offset > 0) continue;
+ merged.set(domain, {
+ domain,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ ips: Array.from(delta.ips),
+ rules: Array.from(delta.rules),
+ chains: Array.from(delta.chains),
+ });
+ addedCount += 1;
+ }
+
+ const sorted = sortDomains(Array.from(merged.values()), sortBy, sortOrder);
+ return {
+ data: sorted.slice(0, limit),
+ total: base.total + addedCount,
+ };
+ }
+
+ mergeIPStatsPaginated(
+ backendId: number,
+ base: { data: IPStats[]; total: number },
+ opts: IPPageOptions = {},
+ ): { data: IPStats[]; total: number } {
+ const ipMap = this.ipByBackend.get(backendId);
+ if (!ipMap || ipMap.size === 0) return base;
+
+ const offset = Math.max(0, opts.offset ?? 0);
+ const limit = Math.max(1, (opts.limit ?? base.data.length) || 50);
+ const sortBy = opts.sortBy || 'totalDownload';
+ const sortOrder = normalizeSortOrder(opts.sortOrder);
+ const search = (opts.search || '').trim().toLowerCase();
+
+ const merged = new Map<string, IPStats>();
+ for (const item of base.data) {
+ if (!matchesIPSearch(item.ip, item.domains || [], search)) continue;
+ merged.set(item.ip, { ...item });
+ }
+
+ let addedCount = 0;
+ for (const [ip, delta] of ipMap) {
+ if (!matchesIPSearch(ip, delta.domains, search)) continue;
+
+ const existing = merged.get(ip);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const domains = new Set(existing.domains || []);
+ for (const domain of delta.domains) domains.add(domain);
+ existing.domains = Array.from(domains);
+ const chains = new Set(existing.chains || []);
+ for (const chain of delta.chains) chains.add(chain);
+ existing.chains = Array.from(chains);
+ continue;
+ }
+
+ if (offset > 0) continue;
+ merged.set(ip, {
+ ip,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ domains: Array.from(delta.domains),
+ chains: Array.from(delta.chains),
+ });
+ addedCount += 1;
+ }
+
+ const sorted = sortIPs(Array.from(merged.values()), sortBy, sortOrder);
+ return {
+ data: sorted.slice(0, limit),
+ total: base.total + addedCount,
+ };
+ }
+
+ mergeProxyDomains(
+ backendId: number,
+ chain: string,
+ base: DomainStats[],
+ limit = 5000,
+ ): DomainStats[] {
+ const domainMap = this.domainByBackend.get(backendId);
+ if (!domainMap || domainMap.size === 0) return base;
+
+ const merged = new Map<string, DomainStats>();
+ for (const item of base) {
+ merged.set(item.domain, { ...item });
+ }
+
+ for (const [domain, delta] of domainMap) {
+ const matched = Array.from(delta.chains).some((full) => matchesChainPrefix(full, chain));
+ if (!matched) continue;
+
+ const existing = merged.get(domain);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const ips = new Set(existing.ips || []);
+ for (const ip of delta.ips) ips.add(ip);
+ existing.ips = Array.from(ips);
+ const rules = new Set(existing.rules || []);
+ for (const rule of delta.rules) rules.add(rule);
+ existing.rules = Array.from(rules);
+ const chains = new Set(existing.chains || []);
+ for (const full of delta.chains) {
+ if (matchesChainPrefix(full, chain)) chains.add(full);
+ }
+ existing.chains = Array.from(chains);
+ } else {
+ merged.set(domain, {
+ domain,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ ips: Array.from(delta.ips),
+ rules: Array.from(delta.rules),
+ chains: Array.from(delta.chains).filter((full) => matchesChainPrefix(full, chain)),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeProxyIPs(
+ backendId: number,
+ chain: string,
+ base: IPStats[],
+ limit = 5000,
+ ): IPStats[] {
+ const ipMap = this.ipByBackend.get(backendId);
+ if (!ipMap || ipMap.size === 0) return base;
+
+ const merged = new Map<string, IPStats>();
+ for (const item of base) {
+ merged.set(item.ip, { ...item });
+ }
+
+ for (const [ip, delta] of ipMap) {
+ const matched = Array.from(delta.chains).some((full) => matchesChainPrefix(full, chain));
+ if (!matched) continue;
+
+ const existing = merged.get(ip);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const domains = new Set(existing.domains || []);
+ for (const domain of delta.domains) domains.add(domain);
+ existing.domains = Array.from(domains);
+ const chains = new Set(existing.chains || []);
+ for (const full of delta.chains) {
+ if (matchesChainPrefix(full, chain)) chains.add(full);
+ }
+ existing.chains = Array.from(chains);
+ } else {
+ merged.set(ip, {
+ ip,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ domains: Array.from(delta.domains),
+ chains: Array.from(delta.chains).filter((full) => matchesChainPrefix(full, chain)),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
mergeProxyStats(backendId: number, base: ProxyStats[]): ProxyStats[] {
const proxyMap = this.proxyByBackend.get(backendId);
if (!proxyMap || proxyMap.size === 0) return base;
@@ -472,6 +934,294 @@ export class RealtimeStore {
);
}
+ mergeDeviceStats(backendId: number, base: DeviceStats[], limit = 50): DeviceStats[] {
+ const deviceMap = this.deviceByBackend.get(backendId);
+ if (!deviceMap || deviceMap.size === 0) {
+ return base;
+ }
+
+ const merged = new Map<string, DeviceStats>();
+ for (const item of base) {
+ merged.set(item.sourceIP, { ...item });
+ }
+
+ for (const [sourceIP, delta] of deviceMap) {
+ const existing = merged.get(sourceIP);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ } else {
+ merged.set(sourceIP, {
+ sourceIP,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeDeviceDomains(
+ backendId: number,
+ sourceIP: string,
+ base: DomainStats[],
+ limit = 5000,
+ ): DomainStats[] {
+ const sourceDomainMap = this.deviceDomainByBackend.get(backendId);
+ const domainMap = sourceDomainMap?.get(sourceIP);
+ if (!domainMap || domainMap.size === 0) {
+ return base;
+ }
+
+ const merged = new Map<string, DomainStats>();
+ for (const item of base) {
+ merged.set(item.domain, { ...item });
+ }
+
+ for (const [domain, delta] of domainMap) {
+ const existing = merged.get(domain);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ if (delta.ips.size > 0) {
+ const ips = new Set(existing.ips || []);
+ for (const ip of delta.ips) ips.add(ip);
+ existing.ips = Array.from(ips);
+ }
+ if (delta.rules.size > 0) {
+ const rules = new Set(existing.rules || []);
+ for (const rule of delta.rules) rules.add(rule);
+ existing.rules = Array.from(rules);
+ }
+ if (delta.chains.size > 0) {
+ const chains = new Set(existing.chains || []);
+ for (const chain of delta.chains) chains.add(chain);
+ existing.chains = Array.from(chains);
+ }
+ } else {
+ merged.set(domain, {
+ domain,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ ips: Array.from(delta.ips),
+ rules: Array.from(delta.rules),
+ chains: Array.from(delta.chains),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeDeviceIPs(
+ backendId: number,
+ sourceIP: string,
+ base: IPStats[],
+ limit = 5000,
+ ): IPStats[] {
+ const sourceIPMap = this.deviceIPByBackend.get(backendId);
+ const ipMap = sourceIPMap?.get(sourceIP);
+ if (!ipMap || ipMap.size === 0) {
+ return base;
+ }
+
+ const merged = new Map<string, IPStats>();
+ for (const item of base) {
+ merged.set(item.ip, { ...item });
+ }
+
+ for (const [ip, delta] of ipMap) {
+ const existing = merged.get(ip);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ if (delta.domains.size > 0) {
+ const domains = new Set(existing.domains || []);
+ for (const domain of delta.domains) domains.add(domain);
+ existing.domains = Array.from(domains);
+ }
+ if (delta.chains.size > 0) {
+ const chains = new Set(existing.chains || []);
+ for (const chain of delta.chains) chains.add(chain);
+ existing.chains = Array.from(chains);
+ }
+ } else {
+ merged.set(ip, {
+ ip,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ domains: Array.from(delta.domains),
+ chains: Array.from(delta.chains),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeRuleStats(backendId: number, base: RuleStats[]): RuleStats[] {
+ const ruleMap = this.ruleByBackend.get(backendId);
+ if (!ruleMap || ruleMap.size === 0) return base;
+
+ const merged = new Map<string, RuleStats>();
+ for (const item of base) {
+ merged.set(item.rule, { ...item });
+ }
+
+ for (const [rule, delta] of ruleMap) {
+ const existing = merged.get(rule);
+ if (existing) {
+ existing.finalProxy = delta.finalProxy || existing.finalProxy;
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ } else {
+ merged.set(rule, {
+ rule,
+ finalProxy: delta.finalProxy,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ });
+ }
+ }
+
+ return Array.from(merged.values()).sort(
+ (a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload),
+ );
+ }
+
+ mergeRuleDomains(
+ backendId: number,
+ rule: string,
+ base: DomainStats[],
+ limit = 5000,
+ ): DomainStats[] {
+ const domainMap = this.domainByBackend.get(backendId);
+ if (!domainMap || domainMap.size === 0) return base;
+
+ const merged = new Map<string, DomainStats>();
+ for (const item of base) {
+ merged.set(item.domain, { ...item });
+ }
+
+ for (const [domain, delta] of domainMap) {
+ if (!delta.rules.has(rule)) continue;
+
+ const existing = merged.get(domain);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const ips = new Set(existing.ips || []);
+ for (const ip of delta.ips) ips.add(ip);
+ existing.ips = Array.from(ips);
+ const rules = new Set(existing.rules || []);
+ for (const r of delta.rules) rules.add(r);
+ existing.rules = Array.from(rules);
+ const chains = new Set(existing.chains || []);
+ for (const full of delta.chains) chains.add(full);
+ existing.chains = Array.from(chains);
+ } else {
+ merged.set(domain, {
+ domain,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ ips: Array.from(delta.ips),
+ rules: Array.from(delta.rules),
+ chains: Array.from(delta.chains),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeRuleIPs(
+ backendId: number,
+ rule: string,
+ base: IPStats[],
+ limit = 5000,
+ ): IPStats[] {
+ const ipMap = this.ipByBackend.get(backendId);
+ if (!ipMap || ipMap.size === 0) return base;
+
+ const merged = new Map<string, IPStats>();
+ for (const item of base) {
+ merged.set(item.ip, { ...item });
+ }
+
+ for (const [ip, delta] of ipMap) {
+ if (!delta.rules.has(rule)) continue;
+
+ const existing = merged.get(ip);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const domains = new Set(existing.domains || []);
+ for (const domain of delta.domains) domains.add(domain);
+ existing.domains = Array.from(domains);
+ const chains = new Set(existing.chains || []);
+ for (const full of delta.chains) chains.add(full);
+ existing.chains = Array.from(chains);
+ } else {
+ merged.set(ip, {
+ ip,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ domains: Array.from(delta.domains),
+ chains: Array.from(delta.chains),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
mergeCountryStats(backendId: number, base: CountryStats[]): CountryStats[] {
const countryMap = this.countryByBackend.get(backendId);
if (!countryMap || countryMap.size === 0) return base;
@@ -520,6 +1270,10 @@ export class RealtimeStore {
this.domainByBackend.delete(backendId);
this.ipByBackend.delete(backendId);
this.proxyByBackend.delete(backendId);
+ this.deviceByBackend.delete(backendId);
+ this.deviceDomainByBackend.delete(backendId);
+ this.deviceIPByBackend.delete(backendId);
+ this.ruleByBackend.delete(backendId);
}
clearCountries(backendId: number): void {
diff --git a/apps/collector/src/websocket.ts b/apps/collector/src/websocket.ts
index 47c04a3..a3515e4 100644
--- a/apps/collector/src/websocket.ts
+++ b/apps/collector/src/websocket.ts
@@ -6,13 +6,89 @@ import { realtimeStore } from './realtime.js';
export interface WebSocketMessage {
type: 'stats' | 'ping' | 'pong' | 'subscribe';
backendId?: number;
+ start?: string;
+ end?: string;
+ includeTrend?: boolean;
+ trendMinutes?: number;
+ trendBucketMinutes?: number;
+ includeDeviceDetails?: boolean;
+ deviceSourceIP?: string;
+ deviceDetailLimit?: number;
+ includeProxyDetails?: boolean;
+ proxyChain?: string;
+ proxyDetailLimit?: number;
+ includeRuleDetails?: boolean;
+ ruleName?: string;
+ ruleDetailLimit?: number;
+ includeRuleChainFlow?: boolean;
+ includeDomainsPage?: boolean;
+ domainsPageOffset?: number;
+ domainsPageLimit?: number;
+ domainsPageSortBy?: string;
+ domainsPageSortOrder?: string;
+ domainsPageSearch?: string;
+ includeIPsPage?: boolean;
+ ipsPageOffset?: number;
+ ipsPageLimit?: number;
+ ipsPageSortBy?: string;
+ ipsPageSortOrder?: string;
+ ipsPageSearch?: string;
data?: StatsSummary;
timestamp: string;
}
+type ClientRange = {
+ start?: string;
+ end?: string;
+};
+
+type ClientTrend = {
+ minutes: number;
+ bucketMinutes: number;
+} | null;
+
+type ClientDeviceDetail = {
+ sourceIP: string;
+ limit: number;
+} | null;
+
+type ClientProxyDetail = {
+ chain: string;
+ limit: number;
+} | null;
+
+type ClientRuleDetail = {
+ rule: string;
+ limit: number;
+} | null;
+
+type ClientDomainsPage = {
+ offset: number;
+ limit: number;
+ sortBy?: string;
+ sortOrder?: 'asc' | 'desc';
+ search?: string;
+} | null;
+
+type ClientIPsPage = {
+ offset: number;
+ limit: number;
+ sortBy?: string;
+ sortOrder?: 'asc' | 'desc';
+ search?: string;
+} | null;
+
interface ClientInfo {
ws: WebSocket;
backendId: number | null; // null means use active backend
+ range: ClientRange;
+ trend: ClientTrend;
+ deviceDetail: ClientDeviceDetail;
+ proxyDetail: ClientProxyDetail;
+ ruleDetail: ClientRuleDetail;
+ includeRuleChainFlow: boolean;
+ domainsPage: ClientDomainsPage;
+ ipsPage: ClientIPsPage;
}
export class StatsWebSocketServer {
@@ -20,8 +96,8 @@ export class StatsWebSocketServer {
private db: StatsDatabase;
private clients: Map<WebSocket, ClientInfo> = new Map();
private port: number;
- private lastBroadcastTime: number = 0;
- private broadcastThrottleMs: number = 1000; // Minimum time between broadcasts
+ private lastBroadcastTime = 0;
+ private broadcastThrottleMs = 1000; // minimum interval between broadcasts
constructor(port: number, db: StatsDatabase) {
this.port = port;
@@ -29,8 +105,8 @@ export class StatsWebSocketServer {
}
start() {
- this.wss = new WSServer({
- port: this.port,
+ this.wss = new WSServer({
+ port: this.port,
host: '0.0.0.0',
perMessageDeflate: false,
});
@@ -38,35 +114,156 @@ export class StatsWebSocketServer {
this.wss.on('connection', (ws: WebSocket, req) => {
console.log(`[WebSocket] Connection from ${req.socket.remoteAddress}`);
console.log(`[WebSocket] Client connected, total: ${this.clients.size + 1}`);
-
- // Store client with default to active backend
- const clientInfo: ClientInfo = { ws, backendId: null };
+
+ const clientInfo: ClientInfo = {
+ ws,
+ backendId: null,
+ range: {},
+ trend: null,
+ deviceDetail: null,
+ proxyDetail: null,
+ ruleDetail: null,
+ includeRuleChainFlow: false,
+ domainsPage: null,
+ ipsPage: null,
+ };
this.clients.set(ws, clientInfo);
- // Send initial stats
+ // Push an initial snapshot immediately.
this.sendStatsToClient(ws);
- // Handle messages
ws.on('message', (data) => {
try {
const msg = JSON.parse(data.toString()) as WebSocketMessage;
-
+
if (msg.type === 'ping') {
ws.send(JSON.stringify({ type: 'pong', timestamp: new Date().toISOString() }));
- } else if (msg.type === 'subscribe' && msg.backendId !== undefined) {
- // Client wants to subscribe to a specific backend
- const backend = this.db.getBackend(msg.backendId);
- if (backend) {
- clientInfo.backendId = msg.backendId;
- console.log(`[WebSocket] Client subscribed to backend: ${backend.name} (ID: ${msg.backendId})`);
- // Send immediate update
- this.sendStatsToClient(ws);
- } else {
- console.warn(`[WebSocket] Client tried to subscribe to non-existent backend: ${msg.backendId}`);
+ return;
+ }
+
+ if (msg.type === 'subscribe') {
+ if (msg.backendId !== undefined) {
+ const backend = this.db.getBackend(msg.backendId);
+ if (backend) {
+ clientInfo.backendId = msg.backendId;
+ console.log(`[WebSocket] Client subscribed to backend: ${backend.name} (ID: ${msg.backendId})`);
+ } else {
+ console.warn(`[WebSocket] Client tried to subscribe to non-existent backend: ${msg.backendId}`);
+ }
+ }
+
+ if (msg.start !== undefined || msg.end !== undefined) {
+ const parsedRange = this.parseRange(msg.start, msg.end);
+ if (parsedRange) {
+ clientInfo.range = parsedRange;
+ }
+ }
+
+ if (
+ msg.includeTrend !== undefined ||
+ msg.trendMinutes !== undefined ||
+ msg.trendBucketMinutes !== undefined
+ ) {
+ const parsedTrend = this.parseTrend(
+ msg.includeTrend,
+ msg.trendMinutes,
+ msg.trendBucketMinutes,
+ clientInfo.range,
+ );
+ if (parsedTrend !== undefined) {
+ clientInfo.trend = parsedTrend;
+ }
}
+ if (
+ msg.includeDeviceDetails !== undefined ||
+ msg.deviceSourceIP !== undefined ||
+ msg.deviceDetailLimit !== undefined
+ ) {
+ const parsedDeviceDetail = this.parseDeviceDetail(
+ msg.includeDeviceDetails,
+ msg.deviceSourceIP,
+ msg.deviceDetailLimit,
+ );
+ if (parsedDeviceDetail !== undefined) {
+ clientInfo.deviceDetail = parsedDeviceDetail;
+ }
+ }
+ if (
+ msg.includeProxyDetails !== undefined ||
+ msg.proxyChain !== undefined ||
+ msg.proxyDetailLimit !== undefined
+ ) {
+ const parsedProxyDetail = this.parseProxyDetail(
+ msg.includeProxyDetails,
+ msg.proxyChain,
+ msg.proxyDetailLimit,
+ );
+ if (parsedProxyDetail !== undefined) {
+ clientInfo.proxyDetail = parsedProxyDetail;
+ }
+ }
+ if (
+ msg.includeRuleDetails !== undefined ||
+ msg.ruleName !== undefined ||
+ msg.ruleDetailLimit !== undefined
+ ) {
+ const parsedRuleDetail = this.parseRuleDetail(
+ msg.includeRuleDetails,
+ msg.ruleName,
+ msg.ruleDetailLimit,
+ );
+ if (parsedRuleDetail !== undefined) {
+ clientInfo.ruleDetail = parsedRuleDetail;
+ }
+ }
+ if (msg.includeRuleChainFlow !== undefined) {
+ clientInfo.includeRuleChainFlow = !!msg.includeRuleChainFlow;
+ }
+ if (
+ msg.includeDomainsPage !== undefined ||
+ msg.domainsPageOffset !== undefined ||
+ msg.domainsPageLimit !== undefined ||
+ msg.domainsPageSortBy !== undefined ||
+ msg.domainsPageSortOrder !== undefined ||
+ msg.domainsPageSearch !== undefined
+ ) {
+ const parsedDomainsPage = this.parseDomainsPage(
+ msg.includeDomainsPage,
+ msg.domainsPageOffset,
+ msg.domainsPageLimit,
+ msg.domainsPageSortBy,
+ msg.domainsPageSortOrder,
+ msg.domainsPageSearch,
+ );
+ if (parsedDomainsPage !== undefined) {
+ clientInfo.domainsPage = parsedDomainsPage;
+ }
+ }
+ if (
+ msg.includeIPsPage !== undefined ||
+ msg.ipsPageOffset !== undefined ||
+ msg.ipsPageLimit !== undefined ||
+ msg.ipsPageSortBy !== undefined ||
+ msg.ipsPageSortOrder !== undefined ||
+ msg.ipsPageSearch !== undefined
+ ) {
+ const parsedIPsPage = this.parseIPsPage(
+ msg.includeIPsPage,
+ msg.ipsPageOffset,
+ msg.ipsPageLimit,
+ msg.ipsPageSortBy,
+ msg.ipsPageSortOrder,
+ msg.ipsPageSearch,
+ );
+ if (parsedIPsPage !== undefined) {
+ clientInfo.ipsPage = parsedIPsPage;
+ }
+ }
+
+ this.sendStatsToClient(ws);
}
- } catch (err) {
- // Ignore invalid messages
+ } catch {
+ // Ignore invalid frames.
}
});
@@ -84,76 +281,577 @@ export class StatsWebSocketServer {
console.log(`[WebSocket] Server running at ws://0.0.0.0:${this.port}`);
}
- private getStatsForBackend(backendId: number | null): StatsSummary | null {
- // If no backendId specified, use the active backend
- if (backendId === null) {
- const activeBackend = this.db.getActiveBackend();
- if (!activeBackend) {
- return null;
- }
- backendId = activeBackend.id;
+ private parseRange(start?: string, end?: string): ClientRange | null {
+ if (start === undefined && end === undefined) {
+ return {};
}
- const backend = this.db.getBackend(backendId);
- if (!backend) {
+ if (!start || !end) {
return null;
}
- const summary = this.db.getSummary(backendId);
- const topDomains = realtimeStore.mergeTopDomains(
- backendId,
- this.db.getTopDomains(backendId, 100),
- 100
- );
- const topIPs = realtimeStore.mergeTopIPs(
- backendId,
- this.db.getTopIPs(backendId, 100),
- 100
- );
- const proxyStats = realtimeStore.mergeProxyStats(
- backendId,
- this.db.getProxyStats(backendId)
- );
- const ruleStats = this.db.getRuleStats(backendId);
- const hourly = this.db.getHourlyStats(backendId, 24);
-
- const stats: StatsSummary = {
+ const startDate = new Date(start);
+ const endDate = new Date(end);
+ if (Number.isNaN(startDate.getTime()) || Number.isNaN(endDate.getTime())) {
+ return null;
+ }
+ if (startDate > endDate) {
+ return null;
+ }
+
+ return {
+ start: startDate.toISOString(),
+ end: endDate.toISOString(),
+ };
+ }
+
+ private shouldIncludeRealtime(range: ClientRange): boolean {
+ if (!range.start && !range.end) {
+ return true;
+ }
+ if (!range.end) {
+ return false;
+ }
+
+ const endMs = new Date(range.end).getTime();
+ if (Number.isNaN(endMs)) {
+ return false;
+ }
+
+ const toleranceMs = parseInt(process.env.REALTIME_RANGE_END_TOLERANCE_MS || '120000', 10);
+ const windowMs = Number.isFinite(toleranceMs) ? Math.max(10_000, toleranceMs) : 120_000;
+ return endMs >= Date.now() - windowMs;
+ }
+
+ private parsePositiveInt(value: number | undefined): number | null {
+ if (value === undefined) return null;
+ const parsed = Number.parseInt(String(value), 10);
+ if (!Number.isFinite(parsed) || parsed <= 0) return null;
+ return parsed;
+ }
+
+ private parseNonNegativeInt(value: number | undefined): number | null {
+ if (value === undefined) return null;
+ const parsed = Number.parseInt(String(value), 10);
+ if (!Number.isFinite(parsed) || parsed < 0) return null;
+ return parsed;
+ }
+
+ private resolveMinutesFromRange(range: ClientRange): number | null {
+ if (!range.start || !range.end) return null;
+ const startMs = new Date(range.start).getTime();
+ const endMs = new Date(range.end).getTime();
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs < startMs) {
+ return null;
+ }
+ return Math.max(1, Math.ceil((endMs - startMs) / 60000));
+ }
+
+ private parseTrend(
+ includeTrend: boolean | undefined,
+ trendMinutes: number | undefined,
+ trendBucketMinutes: number | undefined,
+ range: ClientRange,
+ ): ClientTrend | undefined {
+ if (includeTrend === false) return null;
+ if (
+ includeTrend !== true &&
+ trendMinutes === undefined &&
+ trendBucketMinutes === undefined
+ ) {
+ return undefined;
+ }
+
+ const parsedMinutes = this.parsePositiveInt(trendMinutes);
+ const parsedBucket = this.parsePositiveInt(trendBucketMinutes);
+ if (trendMinutes !== undefined && parsedMinutes === null) return undefined;
+ if (trendBucketMinutes !== undefined && parsedBucket === null) return undefined;
+
+ const fallbackMinutes = this.resolveMinutesFromRange(range) ?? 30;
+ const minutes = Math.min(parsedMinutes ?? fallbackMinutes, 30 * 24 * 60);
+ const bucketMinutes = Math.min(parsedBucket ?? 1, 24 * 60);
+
+ return {
+ minutes,
+ bucketMinutes,
+ };
+ }
+
+ private parseDeviceDetail(
+ includeDeviceDetails: boolean | undefined,
+ deviceSourceIP: string | undefined,
+ deviceDetailLimit: number | undefined,
+ ): ClientDeviceDetail | undefined {
+ if (includeDeviceDetails === false) return null;
+ if (
+ includeDeviceDetails !== true &&
+ deviceSourceIP === undefined &&
+ deviceDetailLimit === undefined
+ ) {
+ return undefined;
+ }
+
+ const sourceIP = (deviceSourceIP || '').trim();
+ if (!sourceIP) return undefined;
+
+ const parsedLimit = this.parsePositiveInt(deviceDetailLimit);
+ if (deviceDetailLimit !== undefined && parsedLimit === null) {
+ return undefined;
+ }
+
+ return {
+ sourceIP,
+ limit: Math.min(parsedLimit ?? 5000, 20000),
+ };
+ }
+
+ private parseProxyDetail(
+ includeProxyDetails: boolean | undefined,
+ proxyChain: string | undefined,
+ proxyDetailLimit: number | undefined,
+ ): ClientProxyDetail | undefined {
+ if (includeProxyDetails === false) return null;
+ if (
+ includeProxyDetails !== true &&
+ proxyChain === undefined &&
+ proxyDetailLimit === undefined
+ ) {
+ return undefined;
+ }
+
+ const chain = (proxyChain || '').trim();
+ if (!chain) return undefined;
+
+ const parsedLimit = this.parsePositiveInt(proxyDetailLimit);
+ if (proxyDetailLimit !== undefined && parsedLimit === null) {
+ return undefined;
+ }
+
+ return {
+ chain,
+ limit: Math.min(parsedLimit ?? 5000, 20000),
+ };
+ }
+
+ private parseRuleDetail(
+ includeRuleDetails: boolean | undefined,
+ ruleName: string | undefined,
+ ruleDetailLimit: number | undefined,
+ ): ClientRuleDetail | undefined {
+ if (includeRuleDetails === false) return null;
+ if (
+ includeRuleDetails !== true &&
+ ruleName === undefined &&
+ ruleDetailLimit === undefined
+ ) {
+ return undefined;
+ }
+
+ const rule = (ruleName || '').trim();
+ if (!rule) return undefined;
+
+ const parsedLimit = this.parsePositiveInt(ruleDetailLimit);
+ if (ruleDetailLimit !== undefined && parsedLimit === null) {
+ return undefined;
+ }
+
+ return {
+ rule,
+ limit: Math.min(parsedLimit ?? 5000, 20000),
+ };
+ }
+
+ private normalizePageSortOrder(sortOrder?: string): 'asc' | 'desc' {
+ return sortOrder?.toLowerCase() === 'asc' ? 'asc' : 'desc';
+ }
+
+ private normalizeDomainSortBy(sortBy?: string): string {
+ const value = (sortBy || '').trim();
+ switch (value) {
+ case 'domain':
+ case 'totalUpload':
+ case 'totalConnections':
+ case 'lastSeen':
+ case 'totalDownload':
+ return value;
+ default:
+ return 'totalDownload';
+ }
+ }
+
+ private normalizeIPSortBy(sortBy?: string): string {
+ const value = (sortBy || '').trim();
+ switch (value) {
+ case 'ip':
+ case 'totalUpload':
+ case 'totalConnections':
+ case 'lastSeen':
+ case 'totalDownload':
+ return value;
+ default:
+ return 'totalDownload';
+ }
+ }
+
+ private parseDomainsPage(
+ includeDomainsPage: boolean | undefined,
+ offset: number | undefined,
+ limit: number | undefined,
+ sortBy: string | undefined,
+ sortOrder: string | undefined,
+ search: string | undefined,
+ ): ClientDomainsPage | undefined {
+ if (includeDomainsPage === false) return null;
+ if (
+ includeDomainsPage !== true &&
+ offset === undefined &&
+ limit === undefined &&
+ sortBy === undefined &&
+ sortOrder === undefined &&
+ search === undefined
+ ) {
+ return undefined;
+ }
+
+ const parsedOffset = this.parseNonNegativeInt(offset);
+ const parsedLimit = this.parsePositiveInt(limit);
+ if (offset !== undefined && parsedOffset === null) return undefined;
+ if (limit !== undefined && parsedLimit === null) return undefined;
+
+ return {
+ offset: parsedOffset ?? 0,
+ limit: Math.min(parsedLimit ?? 50, 200),
+ sortBy: this.normalizeDomainSortBy(sortBy),
+ sortOrder: this.normalizePageSortOrder(sortOrder),
+ search: (search || '').trim() || undefined,
+ };
+ }
+
+ private parseIPsPage(
+ includeIPsPage: boolean | undefined,
+ offset: number | undefined,
+ limit: number | undefined,
+ sortBy: string | undefined,
+ sortOrder: string | undefined,
+ search: string | undefined,
+ ): ClientIPsPage | undefined {
+ if (includeIPsPage === false) return null;
+ if (
+ includeIPsPage !== true &&
+ offset === undefined &&
+ limit === undefined &&
+ sortBy === undefined &&
+ sortOrder === undefined &&
+ search === undefined
+ ) {
+ return undefined;
+ }
+
+ const parsedOffset = this.parseNonNegativeInt(offset);
+ const parsedLimit = this.parsePositiveInt(limit);
+ if (offset !== undefined && parsedOffset === null) return undefined;
+ if (limit !== undefined && parsedLimit === null) return undefined;
+
+ return {
+ offset: parsedOffset ?? 0,
+ limit: Math.min(parsedLimit ?? 50, 200),
+ sortBy: this.normalizeIPSortBy(sortBy),
+ sortOrder: this.normalizePageSortOrder(sortOrder),
+ search: (search || '').trim() || undefined,
+ };
+ }
+
+ private resolveBackendId(rawBackendId: number | null): number | null {
+ if (rawBackendId !== null) {
+ return this.db.getBackend(rawBackendId) ? rawBackendId : null;
+ }
+
+ const activeBackend = this.db.getActiveBackend();
+ return activeBackend?.id ?? null;
+ }
+
+ private getStatsForBackend(
+ backendId: number | null,
+ range: ClientRange,
+ trend: ClientTrend,
+ deviceDetail: ClientDeviceDetail,
+ proxyDetail: ClientProxyDetail,
+ ruleDetail: ClientRuleDetail,
+ includeRuleChainFlow: boolean,
+ domainsPage: ClientDomainsPage,
+ ipsPage: ClientIPsPage,
+ ): StatsSummary | null {
+ const resolvedBackendId = this.resolveBackendId(backendId);
+ if (resolvedBackendId === null) {
+ return null;
+ }
+
+ const includeRealtime = this.shouldIncludeRealtime(range);
+
+ const summary = this.db.getSummary(resolvedBackendId, range.start, range.end);
+
+ const dbTopDomains = this.db.getTopDomains(resolvedBackendId, 100, range.start, range.end);
+ const topDomains = includeRealtime
+ ? realtimeStore.mergeTopDomains(resolvedBackendId, dbTopDomains, 100)
+ : dbTopDomains;
+
+ const dbTopIPs = this.db.getTopIPs(resolvedBackendId, 100, range.start, range.end);
+ const topIPs = includeRealtime
+ ? realtimeStore.mergeTopIPs(resolvedBackendId, dbTopIPs, 100)
+ : dbTopIPs;
+
+ const dbProxyStats = this.db.getProxyStats(resolvedBackendId, range.start, range.end);
+ const proxyStats = includeRealtime
+ ? realtimeStore.mergeProxyStats(resolvedBackendId, dbProxyStats)
+ : dbProxyStats;
+ const dbCountryStats = this.db.getCountryStats(resolvedBackendId, 50, range.start, range.end);
+ const countryStats = includeRealtime
+ ? realtimeStore.mergeCountryStats(resolvedBackendId, dbCountryStats)
+ : dbCountryStats;
+ const dbDeviceStats = this.db.getDevices(resolvedBackendId, 50, range.start, range.end);
+ const deviceStats = includeRealtime
+ ? realtimeStore.mergeDeviceStats(resolvedBackendId, dbDeviceStats, 50)
+ : dbDeviceStats;
+
+ const dbRuleStats = this.db.getRuleStats(resolvedBackendId, range.start, range.end);
+ const ruleStats = includeRealtime
+ ? realtimeStore.mergeRuleStats(resolvedBackendId, dbRuleStats)
+ : dbRuleStats;
+ const hourlyStats = this.db.getHourlyStats(resolvedBackendId, 24, range.start, range.end);
+ const trendStats = trend
+ ? this.db.getTrafficTrendAggregated(
+ resolvedBackendId,
+ trend.minutes,
+ trend.bucketMinutes,
+ range.start,
+ range.end,
+ )
+ : undefined;
+ const dbDeviceDomains = deviceDetail
+ ? this.db.getDeviceDomains(
+ resolvedBackendId,
+ deviceDetail.sourceIP,
+ deviceDetail.limit,
+ range.start,
+ range.end,
+ )
+ : undefined;
+ const dbDeviceIPs = deviceDetail
+ ? this.db.getDeviceIPs(
+ resolvedBackendId,
+ deviceDetail.sourceIP,
+ deviceDetail.limit,
+ range.start,
+ range.end,
+ )
+ : undefined;
+ const deviceDomains = deviceDetail && dbDeviceDomains
+ ? includeRealtime
+ ? realtimeStore.mergeDeviceDomains(
+ resolvedBackendId,
+ deviceDetail.sourceIP,
+ dbDeviceDomains,
+ deviceDetail.limit,
+ )
+ : dbDeviceDomains
+ : undefined;
+ const deviceIPs = deviceDetail && dbDeviceIPs
+ ? includeRealtime
+ ? realtimeStore.mergeDeviceIPs(
+ resolvedBackendId,
+ deviceDetail.sourceIP,
+ dbDeviceIPs,
+ deviceDetail.limit,
+ )
+ : dbDeviceIPs
+ : undefined;
+ const dbProxyDomains = proxyDetail
+ ? this.db.getProxyDomains(
+ resolvedBackendId,
+ proxyDetail.chain,
+ proxyDetail.limit,
+ range.start,
+ range.end,
+ )
+ : undefined;
+ const dbProxyIPs = proxyDetail
+ ? this.db.getProxyIPs(
+ resolvedBackendId,
+ proxyDetail.chain,
+ proxyDetail.limit,
+ range.start,
+ range.end,
+ )
+ : undefined;
+ const proxyDomains = proxyDetail && dbProxyDomains
+ ? includeRealtime
+ ? realtimeStore.mergeProxyDomains(
+ resolvedBackendId,
+ proxyDetail.chain,
+ dbProxyDomains,
+ proxyDetail.limit,
+ )
+ : dbProxyDomains
+ : undefined;
+ const proxyIPs = proxyDetail && dbProxyIPs
+ ? includeRealtime
+ ? realtimeStore.mergeProxyIPs(
+ resolvedBackendId,
+ proxyDetail.chain,
+ dbProxyIPs,
+ proxyDetail.limit,
+ )
+ : dbProxyIPs
+ : undefined;
+ const dbRuleDomains = ruleDetail
+ ? this.db.getRuleDomains(
+ resolvedBackendId,
+ ruleDetail.rule,
+ ruleDetail.limit,
+ range.start,
+ range.end,
+ )
+ : undefined;
+ const dbRuleIPs = ruleDetail
+ ? this.db.getRuleIPs(
+ resolvedBackendId,
+ ruleDetail.rule,
+ ruleDetail.limit,
+ range.start,
+ range.end,
+ )
+ : undefined;
+ const ruleDomains = ruleDetail && dbRuleDomains
+ ? includeRealtime
+ ? realtimeStore.mergeRuleDomains(
+ resolvedBackendId,
+ ruleDetail.rule,
+ dbRuleDomains,
+ ruleDetail.limit,
+ )
+ : dbRuleDomains
+ : undefined;
+ const ruleIPs = ruleDetail && dbRuleIPs
+ ? includeRealtime
+ ? realtimeStore.mergeRuleIPs(
+ resolvedBackendId,
+ ruleDetail.rule,
+ dbRuleIPs,
+ ruleDetail.limit,
+ )
+ : dbRuleIPs
+ : undefined;
+ const ruleChainFlowAll = includeRuleChainFlow
+ ? this.db.getAllRuleChainFlows(
+ resolvedBackendId,
+ range.start,
+ range.end,
+ )
+ : undefined;
+ const dbDomainsPage = domainsPage
+ ? this.db.getDomainStatsPaginated(resolvedBackendId, {
+ offset: domainsPage.offset,
+ limit: domainsPage.limit,
+ sortBy: domainsPage.sortBy,
+ sortOrder: domainsPage.sortOrder,
+ search: domainsPage.search,
+ start: range.start,
+ end: range.end,
+ })
+ : undefined;
+ const domainsPageData = domainsPage && dbDomainsPage
+ ? includeRealtime
+ ? realtimeStore.mergeDomainStatsPaginated(resolvedBackendId, dbDomainsPage, domainsPage)
+ : dbDomainsPage
+ : undefined;
+ const dbIPsPage = ipsPage
+ ? this.db.getIPStatsPaginated(resolvedBackendId, {
+ offset: ipsPage.offset,
+ limit: ipsPage.limit,
+ sortBy: ipsPage.sortBy,
+ sortOrder: ipsPage.sortOrder,
+ search: ipsPage.search,
+ start: range.start,
+ end: range.end,
+ })
+ : undefined;
+ const ipsPageData = ipsPage && dbIPsPage
+ ? includeRealtime
+ ? realtimeStore.mergeIPStatsPaginated(resolvedBackendId, dbIPsPage, ipsPage)
+ : dbIPsPage
+ : undefined;
+ const mergedTrendStats = trend && trendStats && includeRealtime
+ ? realtimeStore.mergeTrend(
+ resolvedBackendId,
+ trendStats,
+ trend.minutes,
+ trend.bucketMinutes,
+ )
+ : trendStats;
+
+ const baseStats: StatsSummary = {
totalUpload: summary.totalUpload,
totalDownload: summary.totalDownload,
totalConnections: summary.totalConnections,
totalDomains: summary.uniqueDomains,
totalIPs: summary.uniqueIPs,
totalProxies: proxyStats.length,
+ totalRules: ruleStats.length,
topDomains,
topIPs,
proxyStats,
+ countryStats,
+ deviceStats,
+ deviceDetailSourceIP: deviceDetail?.sourceIP,
+ deviceDomains,
+ deviceIPs,
+ proxyDetailChain: proxyDetail?.chain,
+ proxyDomains,
+ proxyIPs,
+ ruleDetailName: ruleDetail?.rule,
+ ruleDomains,
+ ruleIPs,
+ ruleChainFlowAll,
+ domainsPage: domainsPageData,
+ domainsPageQuery: domainsPage ? { ...domainsPage } : undefined,
+ ipsPage: ipsPageData,
+ ipsPageQuery: ipsPage ? { ...ipsPage } : undefined,
+ trendStats: mergedTrendStats,
ruleStats,
- hourlyStats: hourly
+ hourlyStats,
};
- return realtimeStore.applySummaryDelta(backendId, stats);
+
+ return includeRealtime
+ ? realtimeStore.applySummaryDelta(resolvedBackendId, baseStats)
+ : baseStats;
}
- private async sendStatsToClient(ws: WebSocket) {
+ private sendStatsToClient(ws: WebSocket) {
if (ws.readyState !== WebSocket.OPEN) return;
-
+
const clientInfo = this.clients.get(ws);
if (!clientInfo) return;
try {
- const stats = this.getStatsForBackend(clientInfo.backendId);
+ const stats = this.getStatsForBackend(
+ clientInfo.backendId,
+ clientInfo.range,
+ clientInfo.trend,
+ clientInfo.deviceDetail,
+ clientInfo.proxyDetail,
+ clientInfo.ruleDetail,
+ clientInfo.includeRuleChainFlow,
+ clientInfo.domainsPage,
+ clientInfo.ipsPage,
+ );
if (!stats) {
- ws.send(JSON.stringify({
- type: 'stats',
- error: 'No backend available',
- timestamp: new Date().toISOString()
- }));
return;
}
-
+
const message: WebSocketMessage = {
type: 'stats',
data: stats,
- timestamp: new Date().toISOString()
+ timestamp: new Date().toISOString(),
};
ws.send(JSON.stringify(message));
} catch (err) {
@@ -161,43 +859,78 @@ export class StatsWebSocketServer {
}
}
- // Broadcast stats to all connected clients
- async broadcastStats(force = false) {
+ // Broadcast stats snapshot to subscribed clients.
+ broadcastStats(changedBackendId?: number, force = false) {
const now = Date.now();
- // Throttle broadcasts to prevent overwhelming clients
if (!force && now - this.lastBroadcastTime < this.broadcastThrottleMs) {
return;
}
-
this.lastBroadcastTime = now;
if (this.clients.size === 0) return;
try {
let sentCount = 0;
- // Cache stats per backendId to avoid redundant DB queries
- const statsCache = new Map<number | null, StatsSummary | null>();
+ const statsCache = new Map<string, StatsSummary | null>();
- // Send stats to each client based on their subscribed backend
for (const [ws, clientInfo] of this.clients) {
if (ws.readyState !== WebSocket.OPEN) continue;
- const cacheKey = clientInfo.backendId;
- if (!statsCache.has(cacheKey)) {
- statsCache.set(cacheKey, this.getStatsForBackend(cacheKey));
+ const resolvedBackendId = this.resolveBackendId(clientInfo.backendId);
+ if (resolvedBackendId === null) continue;
+
+ if (changedBackendId !== undefined && resolvedBackendId !== changedBackendId) {
+ continue;
}
- const stats = statsCache.get(cacheKey)!;
-
- if (stats) {
- const message: WebSocketMessage = {
- type: 'stats',
- data: stats,
- timestamp: new Date().toISOString()
- };
- ws.send(JSON.stringify(message));
- sentCount++;
+
+ const trendKey = clientInfo.trend
+ ? `${clientInfo.trend.minutes}|${clientInfo.trend.bucketMinutes}`
+ : '';
+ const deviceDetailKey = clientInfo.deviceDetail
+ ? `${clientInfo.deviceDetail.sourceIP}|${clientInfo.deviceDetail.limit}`
+ : '';
+ const proxyDetailKey = clientInfo.proxyDetail
+ ? `${clientInfo.proxyDetail.chain}|${clientInfo.proxyDetail.limit}`
+ : '';
+ const ruleDetailKey = clientInfo.ruleDetail
+ ? `${clientInfo.ruleDetail.rule}|${clientInfo.ruleDetail.limit}`
+ : '';
+ const ruleChainFlowKey = clientInfo.includeRuleChainFlow ? '1' : '0';
+ const domainsPageKey = clientInfo.domainsPage
+ ? `${clientInfo.domainsPage.offset}|${clientInfo.domainsPage.limit}|${clientInfo.domainsPage.sortBy || ''}|${clientInfo.domainsPage.sortOrder || ''}|${clientInfo.domainsPage.search || ''}`
+ : '';
+ const ipsPageKey = clientInfo.ipsPage
+ ? `${clientInfo.ipsPage.offset}|${clientInfo.ipsPage.limit}|${clientInfo.ipsPage.sortBy || ''}|${clientInfo.ipsPage.sortOrder || ''}|${clientInfo.ipsPage.search || ''}`
+ : '';
+ const cacheKey = `${resolvedBackendId}|${clientInfo.range.start || ''}|${clientInfo.range.end || ''}|${trendKey}|${deviceDetailKey}|${proxyDetailKey}|${ruleDetailKey}|${ruleChainFlowKey}|${domainsPageKey}|${ipsPageKey}`;
+ if (!statsCache.has(cacheKey)) {
+ statsCache.set(
+ cacheKey,
+ this.getStatsForBackend(
+ resolvedBackendId,
+ clientInfo.range,
+ clientInfo.trend,
+ clientInfo.deviceDetail,
+ clientInfo.proxyDetail,
+ clientInfo.ruleDetail,
+ clientInfo.includeRuleChainFlow,
+ clientInfo.domainsPage,
+ clientInfo.ipsPage,
+ ),
+ );
}
+
+ const stats = statsCache.get(cacheKey);
+ if (!stats) continue;
+
+ const message: WebSocketMessage = {
+ type: 'stats',
+ data: stats,
+ timestamp: new Date().toISOString(),
+ };
+ ws.send(JSON.stringify(message));
+ sentCount++;
}
if (sentCount > 0) {
@@ -208,7 +941,6 @@ export class StatsWebSocketServer {
}
}
- // Get number of connected clients
getClientCount(): number {
return this.clients.size;
}
diff --git a/apps/web/app/[locale]/page.tsx b/apps/web/app/[locale]/page.tsx
index 258e9ff..fdddd7f 100644
--- a/apps/web/app/[locale]/page.tsx
+++ b/apps/web/app/[locale]/page.tsx
@@ -76,8 +76,15 @@ import {
getSummaryQueryKey,
} from "@/lib/stats-query-keys";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
+import { useStatsWebSocket } from "@/lib/websocket";
import { cn } from "@/lib/utils";
-import type { StatsSummary, CountryStats, DeviceStats } from "@clashmaster/shared";
+import type {
+ StatsSummary,
+ CountryStats,
+ DeviceStats,
+ ProxyStats,
+ RuleStats,
+} from "@clashmaster/shared";
function formatTimeAgo(date: Date, t: any): string {
const now = new Date();
@@ -116,6 +123,7 @@ const OverviewContent = memo(function OverviewContent({
error,
timeRange,
timePreset,
+ autoRefresh,
activeBackendId,
onNavigate,
backendStatus,
@@ -125,6 +133,7 @@ const OverviewContent = memo(function OverviewContent({
error: string | null;
timeRange: TimeRange;
timePreset: TimePreset;
+ autoRefresh: boolean;
activeBackendId?: number;
onNavigate?: (tab: string) => void;
backendStatus: BackendStatus;
@@ -138,6 +147,7 @@ const OverviewContent = memo(function OverviewContent({
countries={countryData}
timeRange={timeRange}
timePreset={timePreset}
+ autoRefresh={autoRefresh}
activeBackendId={activeBackendId}
onNavigate={onNavigate}
backendStatus={backendStatus}
@@ -150,25 +160,39 @@ const DomainsContent = memo(function DomainsContent({
data,
activeBackendId,
timeRange,
+ autoRefresh,
}: {
data: StatsSummary | null;
activeBackendId?: number;
timeRange: TimeRange;
+ autoRefresh: boolean;
}) {
const t = useTranslations("domains");
return (
<div className="space-y-6">
- <TopDomainsChart activeBackendId={activeBackendId} timeRange={timeRange} />
+ <TopDomainsChart
+ data={data?.topDomains}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ />
<Tabs defaultValue="domains" className="w-full">
<TabsList className="glass">
<TabsTrigger value="domains">{t("domainList")}</TabsTrigger>
<TabsTrigger value="ips">{t("ipList")}</TabsTrigger>
</TabsList>
<TabsContent value="domains" className="overflow-hidden">
- <DomainsTable activeBackendId={activeBackendId} timeRange={timeRange} />
+ <DomainsTable
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ autoRefresh={autoRefresh}
+ />
</TabsContent>
<TabsContent value="ips" className="overflow-hidden">
- <IPsTable activeBackendId={activeBackendId} timeRange={timeRange} />
+ <IPsTable
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ autoRefresh={autoRefresh}
+ />
</TabsContent>
</Tabs>
</div>
@@ -199,65 +223,81 @@ const CountriesContent = memo(function CountriesContent({
});
const ProxiesContent = memo(function ProxiesContent({
+ data,
activeBackendId,
timeRange,
backendStatus,
+ autoRefresh,
}: {
+ data?: ProxyStats[];
activeBackendId?: number;
timeRange: TimeRange;
backendStatus: BackendStatus;
+ autoRefresh: boolean;
}) {
return (
<div className="space-y-6">
<InteractiveProxyStats
+ data={data}
activeBackendId={activeBackendId}
timeRange={timeRange}
backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
/>
</div>
);
});
const RulesContent = memo(function RulesContent({
+ data,
activeBackendId,
timeRange,
backendStatus,
+ autoRefresh,
}: {
+ data?: RuleStats[];
activeBackendId?: number;
timeRange: TimeRange;
backendStatus: BackendStatus;
+ autoRefresh: boolean;
}) {
return (
<div className="space-y-6">
<InteractiveRuleStats
+ data={data}
activeBackendId={activeBackendId}
timeRange={timeRange}
backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
/>
</div>
);
});
const DevicesContent = memo(function DevicesContent({
+ data,
activeBackendId,
timeRange,
backendStatus,
+ autoRefresh,
}: {
+ data?: DeviceStats[];
activeBackendId?: number;
timeRange: TimeRange;
backendStatus: BackendStatus;
+ autoRefresh: boolean;
}) {
const stableTimeRange = useStableTimeRange(timeRange);
const devicesQuery = useQuery({
queryKey: getDevicesQueryKey(activeBackendId, 50, stableTimeRange),
queryFn: () => api.getDevices(activeBackendId, 50, stableTimeRange),
- enabled: !!activeBackendId,
+ enabled: !data && !!activeBackendId,
placeholderData: keepPreviousData,
});
- const deviceStats: DeviceStats[] = devicesQuery.data ?? [];
- const loading = devicesQuery.isLoading && !devicesQuery.data;
+ const deviceStats: DeviceStats[] = data ?? devicesQuery.data ?? [];
+ const loading = !data && devicesQuery.isLoading && !devicesQuery.data;
if (loading) {
return (
@@ -274,6 +314,7 @@ const DevicesContent = memo(function DevicesContent({
activeBackendId={activeBackendId}
timeRange={timeRange}
backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
/>
</div>
);
@@ -311,6 +352,13 @@ export default function DashboardPage() {
const [showAboutDialog, setShowAboutDialog] = useState(false);
const stableTimeRange = useStableTimeRange(timeRange);
+ const isWsSummaryTab =
+ activeTab === "overview" ||
+ activeTab === "domains" ||
+ activeTab === "countries" ||
+ activeTab === "proxies" ||
+ activeTab === "rules" ||
+ activeTab === "devices";
const backendsQuery = useQuery({
queryKey: ["backends"],
@@ -330,24 +378,64 @@ export default function DashboardPage() {
);
const activeBackendId = activeBackend?.id;
+ // Use WebSocket for summary-driven tabs; keep detail-heavy tabs on HTTP.
+ const wsEnabled = autoRefresh && isWsSummaryTab && !!activeBackendId;
+ const { status: wsStatus, lastMessage: wsSummary } = useStatsWebSocket({
+ backendId: activeBackendId,
+ range: stableTimeRange,
+ enabled: wsEnabled,
+ onMessage: useCallback((stats: StatsSummary) => {
+ if (!activeBackendId) return;
+ setAutoRefreshTick((tick) => tick + 1);
+ queryClient.setQueryData(
+ getSummaryQueryKey(activeBackendId, stableTimeRange),
+ (previous) => ({
+ ...(typeof previous === "object" && previous ? previous : {}),
+ ...stats,
+ }),
+ );
+ if (stats.countryStats) {
+ queryClient.setQueryData(
+ getCountriesQueryKey(activeBackendId, 50, stableTimeRange),
+ stats.countryStats,
+ );
+ }
+ if (stats.deviceStats) {
+ queryClient.setQueryData(
+ getDevicesQueryKey(activeBackendId, 50, stableTimeRange),
+ stats.deviceStats,
+ );
+ }
+ }, [activeBackendId, queryClient, stableTimeRange]),
+ });
+ const wsConnected = wsStatus === "connected";
+ const wsRealtimeActive = wsEnabled && wsConnected;
+ const shouldReducePolling = wsRealtimeActive;
+ const hasWsCountries =
+ wsRealtimeActive &&
+ !!wsSummary?.countryStats &&
+ (activeTab === "overview" || activeTab === "countries");
+
const needsCountries = activeTab === "overview" || activeTab === "countries";
const summaryQuery = useQuery({
queryKey: getSummaryQueryKey(activeBackendId, stableTimeRange),
queryFn: () => api.getSummary(activeBackendId, stableTimeRange),
- enabled: !!activeBackendId,
+ enabled: !!activeBackendId && !(wsEnabled && wsConnected),
placeholderData: keepPreviousData,
});
const countriesQuery = useQuery({
queryKey: getCountriesQueryKey(activeBackendId, 50, stableTimeRange),
queryFn: () => api.getCountries(activeBackendId, 50, stableTimeRange),
- enabled: !!activeBackendId && needsCountries,
+ enabled: !!activeBackendId && needsCountries && !hasWsCountries,
placeholderData: keepPreviousData,
});
- const data: StatsSummary | null = summaryQuery.data ?? null;
- const countryData: CountryStats[] = countriesQuery.data ?? [];
+ const data: StatsSummary | null =
+ (wsEnabled && wsConnected && wsSummary) || summaryQuery.data || null;
+ const countryData: CountryStats[] =
+ (hasWsCountries ? wsSummary?.countryStats : countriesQuery.data) ?? [];
const isLoading = isManualRefreshing;
const summaryError = useMemo(() => {
@@ -356,6 +444,7 @@ export default function DashboardPage() {
? summaryQuery.error.message
: "Unknown error";
}, [summaryQuery.error]);
+ const effectiveSummaryError = wsEnabled && wsConnected ? null : summaryError;
const countriesError = useMemo(() => {
if (!countriesQuery.error) return null;
@@ -363,21 +452,22 @@ export default function DashboardPage() {
? countriesQuery.error.message
: "Unknown error";
}, [countriesQuery.error]);
+ const effectiveCountriesError = hasWsCountries ? null : countriesError;
- const queryError = summaryError ?? countriesError;
+ const queryError = effectiveSummaryError ?? effectiveCountriesError;
const backendStatus: BackendStatus = useMemo(() => {
if (!activeBackend) return "unknown";
- if (summaryError) return "unhealthy";
+ if (effectiveSummaryError) return "unhealthy";
if (activeBackend.listening) return "healthy";
return "unhealthy";
- }, [activeBackend, summaryError]);
+ }, [activeBackend, effectiveSummaryError]);
const backendStatusHint = useMemo(() => {
- if (summaryError) return summaryError;
+ if (effectiveSummaryError) return effectiveSummaryError;
if (activeBackend && !activeBackend.listening) return dashboardT("backendUnavailableHint");
return null;
- }, [summaryError, activeBackend, dashboardT]);
+ }, [effectiveSummaryError, activeBackend, dashboardT]);
const refreshNow = useCallback(
async (showLoading = false) => {
@@ -440,26 +530,28 @@ export default function DashboardPage() {
}
}, [backends.length, backendsQuery.isError, backendsQuery.isFetching, backendsQuery.isLoading, isFirstTime]);
- // Keep rolling windows fresh by moving the range every 5s.
+ // Rolling presets: keep the time window moving.
+ // Only reduce to 30s on lightweight WS tabs (overview/countries).
useEffect(() => {
if (!autoRefresh || !isRollingTimePreset(timePreset)) return;
+ const intervalMs = shouldReducePolling ? 30000 : 5000;
const interval = setInterval(() => {
setAutoRefreshTick((tick) => tick + 1);
setTimeRange(getPresetTimeRange(timePreset));
- queryClient.removeQueries({ queryKey: ["stats"], type: "inactive" });
- }, 5000);
+ }, intervalMs);
return () => clearInterval(interval);
- }, [autoRefresh, timePreset]);
+ }, [autoRefresh, shouldReducePolling, timePreset]);
- // For fixed windows, keep polling active stats queries.
+ // Fixed presets: keep HTTP polling only when WS realtime is not active.
useEffect(() => {
- if (!autoRefresh || isRollingTimePreset(timePreset)) return;
+ if (!autoRefresh || isRollingTimePreset(timePreset) || wsRealtimeActive) return;
+ const intervalMs = 5000;
const interval = setInterval(() => {
setAutoRefreshTick((tick) => tick + 1);
queryClient.invalidateQueries({ queryKey: ["stats"] });
- }, 5000);
+ }, intervalMs);
return () => clearInterval(interval);
- }, [autoRefresh, timePreset]);
+ }, [autoRefresh, queryClient, wsRealtimeActive, timePreset]);
const renderContent = () => {
switch (activeTab) {
@@ -471,37 +563,51 @@ export default function DashboardPage() {
error={queryError}
timeRange={timeRange}
timePreset={timePreset}
+ autoRefresh={autoRefresh}
activeBackendId={activeBackendId}
onNavigate={setActiveTab}
backendStatus={backendStatus}
/>
);
case "domains":
- return <DomainsContent data={data} activeBackendId={activeBackendId} timeRange={timeRange} />;
+ return (
+ <DomainsContent
+ data={data}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ autoRefresh={autoRefresh}
+ />
+ );
case "countries":
return <CountriesContent countryData={countryData} />;
case "proxies":
return (
<ProxiesContent
+ data={data?.proxyStats}
activeBackendId={activeBackendId}
timeRange={timeRange}
backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
/>
);
case "rules":
return (
<RulesContent
+ data={data?.ruleStats}
activeBackendId={activeBackendId}
timeRange={timeRange}
backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
/>
);
case "devices":
return (
<DevicesContent
+ data={data?.deviceStats}
activeBackendId={activeBackendId}
timeRange={timeRange}
backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
/>
);
case "network":
@@ -514,6 +620,7 @@ export default function DashboardPage() {
error={queryError}
timeRange={timeRange}
timePreset={timePreset}
+ autoRefresh={autoRefresh}
activeBackendId={activeBackendId}
onNavigate={setActiveTab}
backendStatus={backendStatus}
@@ -646,12 +753,18 @@ export default function DashboardPage() {
aria-label={autoRefresh ? dashboardT("autoRefresh") : dashboardT("paused")}
className={cn(
"h-9 w-9 rounded-full transition-colors",
- autoRefresh
+ autoRefresh && (!wsEnabled || wsConnected)
? "text-emerald-600 hover:bg-emerald-500/10"
- : "text-muted-foreground hover:bg-muted",
+ : autoRefresh && wsEnabled && !wsConnected
+ ? "text-amber-600 hover:bg-amber-500/10"
+ : "text-muted-foreground hover:bg-muted",
)}>
<RefreshCw
- className={cn("w-4 h-4", autoRefresh && "text-emerald-500")}
+ className={cn(
+ "w-4 h-4",
+ autoRefresh && (!wsEnabled || wsConnected) && "text-emerald-500",
+ autoRefresh && wsEnabled && !wsConnected && "text-amber-500",
+ )}
style={
autoRefresh
? {
diff --git a/apps/web/components/domains-table.tsx b/apps/web/components/domains-table.tsx
index ee48109..12d8422 100644
--- a/apps/web/components/domains-table.tsx
+++ b/apps/web/components/domains-table.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useEffect, useMemo, useRef } from "react";
+import { useState, useEffect, useMemo, useRef, useCallback } from "react";
import { Search, ArrowUpDown, ArrowDown, ArrowUp, ChevronLeft, ChevronRight, Rows3, ChevronDown, ChevronUp, Server, Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
@@ -12,9 +12,10 @@ import { ProxyChainBadge } from "@/components/proxy-chain-badge";
import { ExpandReveal } from "@/components/ui/expand-reveal";
import { formatBytes, formatNumber, formatDuration } from "@/lib/utils";
import { cn } from "@/lib/utils";
-import type { DomainStats } from "@clashmaster/shared";
+import type { DomainStats, StatsSummary } from "@clashmaster/shared";
import { api, type TimeRange } from "@/lib/api";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
+import { useStatsWebSocket } from "@/lib/websocket";
import {
getDomainIPDetailsQueryKey,
getDomainProxyStatsQueryKey,
@@ -30,6 +31,7 @@ import {
interface DomainsTableProps {
activeBackendId?: number;
timeRange?: TimeRange;
+ autoRefresh?: boolean;
}
type SortKey = "domain" | "totalDownload" | "totalUpload" | "totalConnections" | "lastSeen";
@@ -37,8 +39,9 @@ type SortOrder = "asc" | "desc";
const PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
type PageSize = typeof PAGE_SIZE_OPTIONS[number];
+const DETAIL_QUERY_STALE_MS = 30_000;
-export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps) {
+export function DomainsTable({ activeBackendId, timeRange, autoRefresh = true }: DomainsTableProps) {
const t = useTranslations("domains");
const stableTimeRange = useStableTimeRange(timeRange);
const detailTimeRange = stableTimeRange;
@@ -49,7 +52,46 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState<PageSize>(10);
const [expandedDomain, setExpandedDomain] = useState<string | null>(null);
+ const [wsDomainsPage, setWsDomainsPage] = useState<{ data: DomainStats[]; total: number } | null>(null);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const pageOffset = (currentPage - 1) * pageSize;
+ const wsPageSearch = debouncedSearch || undefined;
+
+ const wsPageEnabled = autoRefresh && !!activeBackendId;
+ const { status: wsPageStatus } = useStatsWebSocket({
+ backendId: activeBackendId,
+ range: stableTimeRange,
+ includeDomainsPage: wsPageEnabled,
+ domainsPageOffset: pageOffset,
+ domainsPageLimit: pageSize,
+ domainsPageSortBy: sortKey,
+ domainsPageSortOrder: sortOrder,
+ domainsPageSearch: wsPageSearch,
+ enabled: wsPageEnabled,
+ onMessage: useCallback((stats: StatsSummary) => {
+ const query = stats.domainsPageQuery;
+ const page = stats.domainsPage;
+ if (!page || !query) return;
+ if (query.offset !== pageOffset || query.limit !== pageSize) return;
+ if ((query.sortBy || "totalDownload") !== sortKey) return;
+ if ((query.sortOrder || "desc") !== sortOrder) return;
+ if ((query.search || undefined) !== wsPageSearch) return;
+ setWsDomainsPage(page);
+ }, [pageOffset, pageSize, sortKey, sortOrder, wsPageSearch]),
+ });
+
+ useEffect(() => {
+ setWsDomainsPage(null);
+ }, [
+ activeBackendId,
+ stableTimeRange?.start,
+ stableTimeRange?.end,
+ pageOffset,
+ pageSize,
+ sortKey,
+ sortOrder,
+ wsPageSearch,
+ ]);
// Debounce search input
useEffect(() => {
@@ -82,13 +124,16 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)
start: stableTimeRange?.start,
end: stableTimeRange?.end,
}),
- enabled: !!activeBackendId,
+ enabled: !!activeBackendId && wsPageStatus !== "connected",
placeholderData: keepPreviousData,
});
- const data = domainsQuery.data?.data ?? [];
- const total = domainsQuery.data?.total ?? 0;
- const loading = domainsQuery.isLoading && !domainsQuery.data;
+ const hasWsDomainsPage = wsPageEnabled && wsPageStatus === "connected" && wsDomainsPage !== null;
+ const data = hasWsDomainsPage ? wsDomainsPage.data : domainsQuery.data?.data ?? [];
+ const total = hasWsDomainsPage ? wsDomainsPage.total : domainsQuery.data?.total ?? 0;
+ const loading =
+ (wsPageStatus === "connected" && wsDomainsPage === null) ||
+ (!hasWsDomainsPage && domainsQuery.isLoading && !domainsQuery.data);
useEffect(() => {
// Backend switch means a different data universe, collapse safely.
@@ -99,6 +144,7 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)
queryKey: getDomainProxyStatsQueryKey(expandedDomain, activeBackendId, detailTimeRange),
queryFn: () => api.getDomainProxyStats(expandedDomain!, activeBackendId, detailTimeRange),
enabled: !!activeBackendId && !!expandedDomain,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) => {
const prevKey = (previousQuery?.queryKey?.[2] ?? null) as
| { domain?: string; backendId?: number | null }
@@ -114,6 +160,7 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)
queryKey: getDomainIPDetailsQueryKey(expandedDomain, activeBackendId, detailTimeRange),
queryFn: () => api.getDomainIPDetails(expandedDomain!, activeBackendId, detailTimeRange),
enabled: !!activeBackendId && !!expandedDomain,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) => {
const prevKey = (previousQuery?.queryKey?.[2] ?? null) as
| { domain?: string; backendId?: number | null }
diff --git a/apps/web/components/interactive-device-stats.tsx b/apps/web/components/interactive-device-stats.tsx
index e9c7296..56f4d65 100644
--- a/apps/web/components/interactive-device-stats.tsx
+++ b/apps/web/components/interactive-device-stats.tsx
@@ -17,16 +17,18 @@ import {
} from "@/lib/stats-query-keys";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { keepPreviousByIdentity } from "@/lib/query-placeholder";
+import { useStatsWebSocket } from "@/lib/websocket";
import { Favicon } from "@/components/favicon";
import { DomainStatsTable, IPStatsTable } from "@/components/stats-tables";
import { COLORS } from "@/lib/stats-utils";
-import type { DeviceStats } from "@clashmaster/shared";
+import type { DeviceStats, DomainStats, IPStats, StatsSummary } from "@clashmaster/shared";
interface InteractiveDeviceStatsProps {
data: DeviceStats[];
activeBackendId?: number;
timeRange?: TimeRange;
backendStatus?: "healthy" | "unhealthy" | "unknown";
+ autoRefresh?: boolean;
}
@@ -45,6 +47,7 @@ export function InteractiveDeviceStats({
activeBackendId,
timeRange,
backendStatus,
+ autoRefresh = true,
}: InteractiveDeviceStatsProps) {
const t = useTranslations("devices");
const domainsT = useTranslations("domains");
@@ -54,6 +57,8 @@ export function InteractiveDeviceStats({
const [selectedDevice, setSelectedDevice] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState("domains");
const [showDomainBarLabels, setShowDomainBarLabels] = useState(true);
+ const [wsDeviceDomains, setWsDeviceDomains] = useState<DomainStats[] | null>(null);
+ const [wsDeviceIPs, setWsDeviceIPs] = useState<IPStats[] | null>(null);
useEffect(() => {
const media = window.matchMedia("(min-width: 640px)");
@@ -92,6 +97,37 @@ export function InteractiveDeviceStats({
}
}, [chartData, selectedDevice]);
+ const wsDetailEnabled = autoRefresh && !!activeBackendId && !!selectedDevice;
+ const { status: wsDetailStatus } = useStatsWebSocket({
+ backendId: activeBackendId,
+ range: detailTimeRange,
+ includeDeviceDetails: wsDetailEnabled,
+ deviceSourceIP: selectedDevice ?? undefined,
+ deviceDetailLimit: 5000,
+ enabled: wsDetailEnabled,
+ onMessage: useCallback((stats: StatsSummary) => {
+ if (!selectedDevice) return;
+ if (stats.deviceDetailSourceIP !== selectedDevice) return;
+ if (stats.deviceDomains) {
+ setWsDeviceDomains(stats.deviceDomains);
+ }
+ if (stats.deviceIPs) {
+ setWsDeviceIPs(stats.deviceIPs);
+ }
+ }, [selectedDevice]),
+ });
+
+ useEffect(() => {
+ setWsDeviceDomains(null);
+ setWsDeviceIPs(null);
+ }, [selectedDevice, activeBackendId]);
+
+ const hasWsDeviceDetails =
+ wsDetailEnabled &&
+ wsDetailStatus === "connected" &&
+ wsDeviceDomains !== null &&
+ wsDeviceIPs !== null;
+
const deviceDomainsQuery = useQuery({
queryKey: getDeviceDomainsQueryKey(selectedDevice, activeBackendId, detailTimeRange),
queryFn: () =>
@@ -100,7 +136,7 @@ export function InteractiveDeviceStats({
activeBackendId,
detailTimeRange,
),
- enabled: !!activeBackendId && !!selectedDevice,
+ enabled: !!activeBackendId && !!selectedDevice && !hasWsDeviceDetails,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
sourceIP: selectedDevice ?? "",
@@ -116,7 +152,7 @@ export function InteractiveDeviceStats({
activeBackendId,
detailTimeRange,
),
- enabled: !!activeBackendId && !!selectedDevice,
+ enabled: !!activeBackendId && !!selectedDevice && !hasWsDeviceDetails,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
sourceIP: selectedDevice ?? "",
@@ -124,9 +160,9 @@ export function InteractiveDeviceStats({
}),
});
- const deviceDomains = deviceDomainsQuery.data ?? [];
- const deviceIPs = deviceIPsQuery.data ?? [];
- const loading = !!selectedDevice && !deviceDomainsQuery.data && !deviceIPsQuery.data;
+ const deviceDomains = hasWsDeviceDetails ? wsDeviceDomains ?? [] : deviceDomainsQuery.data ?? [];
+ const deviceIPs = hasWsDeviceDetails ? wsDeviceIPs ?? [] : deviceIPsQuery.data ?? [];
+ const loading = !!selectedDevice && !hasWsDeviceDetails && !deviceDomainsQuery.data && !deviceIPsQuery.data;
const handleDeviceClick = useCallback((rawName: string) => {
if (selectedDevice !== rawName) {
diff --git a/apps/web/components/interactive-proxy-stats.tsx b/apps/web/components/interactive-proxy-stats.tsx
index 9030921..d339f28 100644
--- a/apps/web/components/interactive-proxy-stats.tsx
+++ b/apps/web/components/interactive-proxy-stats.tsx
@@ -14,6 +14,7 @@ import { cn } from "@/lib/utils";
import { api, type TimeRange } from "@/lib/api";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { keepPreviousByIdentity } from "@/lib/query-placeholder";
+import { useStatsWebSocket } from "@/lib/websocket";
import {
getProxiesQueryKey,
getProxyDomainsQueryKey,
@@ -22,13 +23,14 @@ import {
import { Favicon } from "@/components/favicon";
import { DomainStatsTable, IPStatsTable } from "@/components/stats-tables";
import { COLORS } from "@/lib/stats-utils";
-import type { ProxyStats } from "@clashmaster/shared";
+import type { DomainStats, IPStats, ProxyStats, StatsSummary } from "@clashmaster/shared";
interface InteractiveProxyStatsProps {
data?: ProxyStats[];
activeBackendId?: number;
timeRange?: TimeRange;
backendStatus?: "healthy" | "unhealthy" | "unknown";
+ autoRefresh?: boolean;
}
function normalizeProxyName(name: string): string {
@@ -70,6 +72,7 @@ export function InteractiveProxyStats({
activeBackendId,
timeRange,
backendStatus,
+ autoRefresh = true,
}: InteractiveProxyStatsProps) {
const t = useTranslations("proxies");
const domainsT = useTranslations("domains");
@@ -89,6 +92,8 @@ export function InteractiveProxyStats({
const [selectedProxy, setSelectedProxy] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState("domains");
const [showDomainBarLabels, setShowDomainBarLabels] = useState(true);
+ const [wsProxyDomains, setWsProxyDomains] = useState<DomainStats[] | null>(null);
+ const [wsProxyIPs, setWsProxyIPs] = useState<IPStats[] | null>(null);
useEffect(() => {
const media = window.matchMedia("(min-width: 640px)");
@@ -128,6 +133,37 @@ export function InteractiveProxyStats({
}
}, [chartData, selectedProxy]);
+ const wsDetailEnabled = autoRefresh && !!activeBackendId && !!selectedProxy;
+ const { status: wsDetailStatus } = useStatsWebSocket({
+ backendId: activeBackendId,
+ range: detailTimeRange,
+ includeProxyDetails: wsDetailEnabled,
+ proxyChain: selectedProxy ?? undefined,
+ proxyDetailLimit: 5000,
+ enabled: wsDetailEnabled,
+ onMessage: useCallback((stats: StatsSummary) => {
+ if (!selectedProxy) return;
+ if (stats.proxyDetailChain !== selectedProxy) return;
+ if (stats.proxyDomains) {
+ setWsProxyDomains(stats.proxyDomains);
+ }
+ if (stats.proxyIPs) {
+ setWsProxyIPs(stats.proxyIPs);
+ }
+ }, [selectedProxy]),
+ });
+
+ useEffect(() => {
+ setWsProxyDomains(null);
+ setWsProxyIPs(null);
+ }, [selectedProxy, activeBackendId]);
+
+ const hasWsProxyDetails =
+ wsDetailEnabled &&
+ wsDetailStatus === "connected" &&
+ wsProxyDomains !== null &&
+ wsProxyIPs !== null;
+
const proxyDomainsQuery = useQuery({
queryKey: getProxyDomainsQueryKey(selectedProxy, activeBackendId, detailTimeRange),
queryFn: () =>
@@ -136,7 +172,7 @@ export function InteractiveProxyStats({
activeBackendId,
detailTimeRange,
),
- enabled: !!activeBackendId && !!selectedProxy,
+ enabled: !!activeBackendId && !!selectedProxy && !hasWsProxyDetails,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
chain: selectedProxy ?? "",
@@ -152,7 +188,7 @@ export function InteractiveProxyStats({
activeBackendId,
detailTimeRange,
),
- enabled: !!activeBackendId && !!selectedProxy,
+ enabled: !!activeBackendId && !!selectedProxy && !hasWsProxyDetails,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
chain: selectedProxy ?? "",
@@ -160,9 +196,9 @@ export function InteractiveProxyStats({
}),
});
- const proxyDomains = proxyDomainsQuery.data ?? [];
- const proxyIPs = proxyIPsQuery.data ?? [];
- const loading = !!selectedProxy && !proxyDomainsQuery.data && !proxyIPsQuery.data;
+ const proxyDomains = hasWsProxyDetails ? wsProxyDomains ?? [] : proxyDomainsQuery.data ?? [];
+ const proxyIPs = hasWsProxyDetails ? wsProxyIPs ?? [] : proxyIPsQuery.data ?? [];
+ const loading = !!selectedProxy && !hasWsProxyDetails && !proxyDomainsQuery.data && !proxyIPsQuery.data;
const handleProxyClick = useCallback((rawName: string) => {
if (selectedProxy !== rawName) {
diff --git a/apps/web/components/interactive-rule-stats.tsx b/apps/web/components/interactive-rule-stats.tsx
index eca83aa..e71b82a 100644
--- a/apps/web/components/interactive-rule-stats.tsx
+++ b/apps/web/components/interactive-rule-stats.tsx
@@ -22,6 +22,7 @@ import { cn } from "@/lib/utils";
import { api, type ClashRulesResponse, type TimeRange } from "@/lib/api";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { keepPreviousByIdentity } from "@/lib/query-placeholder";
+import { useStatsWebSocket } from "@/lib/websocket";
import {
getRuleDomainsQueryKey,
getRuleIPsQueryKey,
@@ -37,13 +38,14 @@ import { ProxyChainBadge } from "@/components/proxy-chain-badge";
import { DomainExpandedDetails, IPExpandedDetails } from "@/components/stats-tables/expanded-details";
import { ExpandReveal } from "@/components/ui/expand-reveal";
import { UnifiedRuleChainFlow } from "@/components/rule-chain-flow";
-import type { RuleStats, DomainStats, IPStats } from "@clashmaster/shared";
+import type { RuleStats, DomainStats, IPStats, StatsSummary } from "@clashmaster/shared";
interface InteractiveRuleStatsProps {
data?: RuleStats[];
activeBackendId?: number;
timeRange?: TimeRange;
backendStatus?: "healthy" | "unhealthy" | "unknown";
+ autoRefresh?: boolean;
}
const COLORS = [
@@ -58,6 +60,30 @@ 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;
+
+interface RuleChartItem {
+ name: string;
+ rawName: string;
+ value: number;
+ download: number;
+ upload: number;
+ connections: number;
+ finalProxy?: string;
+ color: string;
+ rank: number;
+ hasTraffic: boolean;
+}
+
+interface RuleDomainChartItem {
+ name: string;
+ fullDomain: string;
+ total: number;
+ download: number;
+ upload: number;
+ connections: number;
+ color: string;
+}
// Domain sort keys
type DomainSortKey = "domain" | "totalDownload" | "totalUpload" | "totalConnections";
@@ -109,6 +135,7 @@ export function InteractiveRuleStats({
activeBackendId,
timeRange,
backendStatus,
+ autoRefresh = true,
}: InteractiveRuleStatsProps) {
const t = useTranslations("rules");
const domainsT = useTranslations("domains");
@@ -138,6 +165,8 @@ export function InteractiveRuleStats({
const [ipSearch, setIpSearch] = useState("");
const [showDomainBarLabels, setShowDomainBarLabels] = useState(true);
const [clashRules, setClashRules] = useState<ClashRulesResponse | null>(null);
+ const [wsRuleDomains, setWsRuleDomains] = useState<DomainStats[] | null>(null);
+ const [wsRuleIPs, setWsRuleIPs] = useState<IPStats[] | null>(null);
// Sort states
const [domainSortKey, setDomainSortKey] = useState<DomainSortKey>("totalDownload");
@@ -157,7 +186,8 @@ export function InteractiveRuleStats({
return () => media.removeEventListener("change", update);
}, []);
- // Fetch Clash rules to find zero-traffic rules
+ // Fetch Clash rules to find zero-traffic rules.
+ // Ruleset metadata changes infrequently, so load on mount/backend switch only.
useEffect(() => {
let cancelled = false;
async function fetchClashRules() {
@@ -169,14 +199,13 @@ export function InteractiveRuleStats({
}
}
fetchClashRules();
- const interval = setInterval(fetchClashRules, 30000);
- return () => { cancelled = true; clearInterval(interval); };
+ return () => { cancelled = true; };
}, [activeBackendId]);
- const chartData = useMemo(() => {
+ const chartData = useMemo<RuleChartItem[]>(() => {
if (!rulesData) return [];
const existingRuleNames = new Set(rulesData.map(r => r.rule));
- const trafficItems = rulesData.map((rule, index) => ({
+ const trafficItems: RuleChartItem[] = rulesData.map((rule, index) => ({
name: rule.rule,
rawName: rule.rule,
value: rule.totalDownload + rule.totalUpload,
@@ -265,6 +294,37 @@ export function InteractiveRuleStats({
setExpandedIP(newExpanded);
};
+ const wsDetailEnabled = autoRefresh && !!activeBackendId && !!selectedRule;
+ const { status: wsDetailStatus } = useStatsWebSocket({
+ backendId: activeBackendId,
+ range: detailTimeRange,
+ includeRuleDetails: wsDetailEnabled,
+ ruleName: selectedRule ?? undefined,
+ ruleDetailLimit: 5000,
+ enabled: wsDetailEnabled,
+ onMessage: useCallback((stats: StatsSummary) => {
+ if (!selectedRule) return;
+ if (stats.ruleDetailName !== selectedRule) return;
+ if (stats.ruleDomains) {
+ setWsRuleDomains(stats.ruleDomains);
+ }
+ if (stats.ruleIPs) {
+ setWsRuleIPs(stats.ruleIPs);
+ }
+ }, [selectedRule]),
+ });
+
+ useEffect(() => {
+ setWsRuleDomains(null);
+ setWsRuleIPs(null);
+ }, [selectedRule, activeBackendId]);
+
+ const hasWsRuleDetails =
+ wsDetailEnabled &&
+ wsDetailStatus === "connected" &&
+ wsRuleDomains !== null &&
+ wsRuleIPs !== null;
+
const expandedDomainProxyQuery = useQuery({
queryKey: getDomainProxyStatsQueryKey(expandedDomain, activeBackendId, detailTimeRange, {
rule: selectedRule ?? undefined,
@@ -277,6 +337,7 @@ export function InteractiveRuleStats({
detailTimeRange,
),
enabled: !!activeBackendId && !!selectedRule && !!expandedDomain,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
domain: expandedDomain ?? "",
@@ -297,6 +358,7 @@ export function InteractiveRuleStats({
detailTimeRange,
),
enabled: !!activeBackendId && !!selectedRule && !!expandedDomain,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
domain: expandedDomain ?? "",
@@ -317,6 +379,7 @@ export function InteractiveRuleStats({
detailTimeRange,
),
enabled: !!activeBackendId && !!selectedRule && !!expandedIP,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
ip: expandedIP ?? "",
@@ -337,6 +400,7 @@ export function InteractiveRuleStats({
detailTimeRange,
),
enabled: !!activeBackendId && !!selectedRule && !!expandedIP,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
ip: expandedIP ?? "",
@@ -353,7 +417,7 @@ export function InteractiveRuleStats({
activeBackendId,
detailTimeRange,
),
- enabled: !!activeBackendId && !!selectedRule,
+ enabled: !!activeBackendId && !!selectedRule && !hasWsRuleDetails,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
rule: selectedRule ?? "",
@@ -369,7 +433,7 @@ export function InteractiveRuleStats({
activeBackendId,
detailTimeRange,
),
- enabled: !!activeBackendId && !!selectedRule,
+ enabled: !!activeBackendId && !!selectedRule && !hasWsRuleDetails,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
rule: selectedRule ?? "",
@@ -377,9 +441,9 @@ export function InteractiveRuleStats({
}),
});
- const ruleDomains: DomainStats[] = ruleDomainsQuery.data ?? [];
- const ruleIPs: IPStats[] = ruleIPsQuery.data ?? [];
- const loading = !!selectedRule && !ruleDomainsQuery.data && !ruleIPsQuery.data;
+ const ruleDomains: DomainStats[] = hasWsRuleDetails ? wsRuleDomains ?? [] : ruleDomainsQuery.data ?? [];
+ const ruleIPs: IPStats[] = hasWsRuleDetails ? wsRuleIPs ?? [] : ruleIPsQuery.data ?? [];
+ const loading = !!selectedRule && !hasWsRuleDetails && !ruleDomainsQuery.data && !ruleIPsQuery.data;
// Sort icon component
const DomainSortIcon = ({ column }: { column: DomainSortKey }) => {
@@ -463,6 +527,10 @@ export function InteractiveRuleStats({
}, [filteredDomains, domainPage, domainPageSize]);
const domainTotalPages = Math.ceil(filteredDomains.length / domainPageSize);
+ const totalFilteredDomainTraffic = useMemo(
+ () => filteredDomains.reduce((sum, d) => sum + d.totalDownload + d.totalUpload, 0),
+ [filteredDomains],
+ );
// Filter, sort and paginate IPs
const filteredIPs = useMemo(() => {
@@ -491,9 +559,13 @@ export function InteractiveRuleStats({
}, [filteredIPs, ipPage, ipPageSize]);
const ipTotalPages = Math.ceil(filteredIPs.length / ipPageSize);
+ const totalFilteredIPTraffic = useMemo(
+ () => filteredIPs.reduce((sum, ip) => sum + ip.totalDownload + ip.totalUpload, 0),
+ [filteredIPs],
+ );
// Chart data
- const domainChartData = useMemo(() => {
+ const domainChartData = useMemo<RuleDomainChartItem[]>(() => {
if (!ruleDomains?.length) return [];
return ruleDomains
.slice(0, 10)
@@ -871,6 +943,7 @@ export function InteractiveRuleStats({
selectedRule={selectedRule}
activeBackendId={activeBackendId}
timeRange={timeRange}
+ autoRefresh={autoRefresh}
/>
{/* Bottom Section: Domain List & IP Addresses with pagination */}
@@ -999,12 +1072,12 @@ export function InteractiveRuleStats({
{/* Domain List */}
<div className="divide-y divide-border/30">
{(() => {
- const totalDomainTraffic = filteredDomains.reduce(
- (sum, d) => sum + d.totalDownload + d.totalUpload, 0
- );
return paginatedDomains.map((domain, index) => {
const domainTraffic = domain.totalDownload + domain.totalUpload;
- const percent = totalDomainTraffic > 0 ? (domainTraffic / totalDomainTraffic) * 100 : 0;
+ const percent =
+ totalFilteredDomainTraffic > 0
+ ? (domainTraffic / totalFilteredDomainTraffic) * 100
+ : 0;
const isExpanded = expandedDomain === domain.domain;
return (
@@ -1351,12 +1424,12 @@ export function InteractiveRuleStats({
{/* IP List */}
<div className="divide-y divide-border/30">
{(() => {
- const totalIPTraffic = filteredIPs.reduce(
- (sum, ip) => sum + ip.totalDownload + ip.totalUpload, 0
- );
return paginatedIPs.map((ip, index) => {
const ipTraffic = ip.totalDownload + ip.totalUpload;
- const percent = totalIPTraffic > 0 ? (ipTraffic / totalIPTraffic) * 100 : 0;
+ const percent =
+ totalFilteredIPTraffic > 0
+ ? (ipTraffic / totalFilteredIPTraffic) * 100
+ : 0;
const isExpanded = expandedIP === ip.ip;
const ipColor = getIPColor(ip.ip);
diff --git a/apps/web/components/ips-table.tsx b/apps/web/components/ips-table.tsx
index f009d91..cf97a70 100644
--- a/apps/web/components/ips-table.tsx
+++ b/apps/web/components/ips-table.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useEffect, useMemo, useRef } from "react";
+import { useState, useEffect, useMemo, useRef, useCallback } from "react";
import {
Search,
ArrowUpDown,
@@ -26,9 +26,10 @@ import { cn } from "@/lib/utils";
import { IPExpandedDetails } from "@/components/stats-tables/expanded-details";
import { ProxyChainBadge } from "@/components/proxy-chain-badge";
import { ExpandReveal } from "@/components/ui/expand-reveal";
-import type { IPStats } from "@clashmaster/shared";
+import type { IPStats, StatsSummary } from "@clashmaster/shared";
import { api, type TimeRange } from "@/lib/api";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
+import { useStatsWebSocket } from "@/lib/websocket";
import {
getIPDomainDetailsQueryKey,
getIPProxyStatsQueryKey,
@@ -44,6 +45,7 @@ import {
interface IPsTableProps {
activeBackendId?: number;
timeRange?: TimeRange;
+ autoRefresh?: boolean;
}
type SortKey =
@@ -56,6 +58,7 @@ type SortOrder = "asc" | "desc";
const PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
type PageSize = (typeof PAGE_SIZE_OPTIONS)[number];
+const DETAIL_QUERY_STALE_MS = 30_000;
// Color palette for IP icons - solid colors that work in both light/dark modes
const IP_COLORS = [
@@ -78,7 +81,7 @@ const getIPColor = (ip: string) => {
return IP_COLORS[Math.abs(hash) % IP_COLORS.length];
};
-export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
+export function IPsTable({ activeBackendId, timeRange, autoRefresh = true }: IPsTableProps) {
const t = useTranslations("ips");
const stableTimeRange = useStableTimeRange(timeRange);
const detailTimeRange = stableTimeRange;
@@ -89,7 +92,46 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState<PageSize>(10);
const [expandedIP, setExpandedIP] = useState<string | null>(null);
+ const [wsIPsPage, setWsIPsPage] = useState<{ data: IPStats[]; total: number } | null>(null);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const pageOffset = (currentPage - 1) * pageSize;
+ const wsPageSearch = debouncedSearch || undefined;
+
+ const wsPageEnabled = autoRefresh && !!activeBackendId;
+ const { status: wsPageStatus } = useStatsWebSocket({
+ backendId: activeBackendId,
+ range: stableTimeRange,
+ includeIPsPage: wsPageEnabled,
+ ipsPageOffset: pageOffset,
+ ipsPageLimit: pageSize,
+ ipsPageSortBy: sortKey,
+ ipsPageSortOrder: sortOrder,
+ ipsPageSearch: wsPageSearch,
+ enabled: wsPageEnabled,
+ onMessage: useCallback((stats: StatsSummary) => {
+ const query = stats.ipsPageQuery;
+ const page = stats.ipsPage;
+ if (!page || !query) return;
+ if (query.offset !== pageOffset || query.limit !== pageSize) return;
+ if ((query.sortBy || "totalDownload") !== sortKey) return;
+ if ((query.sortOrder || "desc") !== sortOrder) return;
+ if ((query.search || undefined) !== wsPageSearch) return;
+ setWsIPsPage(page);
+ }, [pageOffset, pageSize, sortKey, sortOrder, wsPageSearch]),
+ });
+
+ useEffect(() => {
+ setWsIPsPage(null);
+ }, [
+ activeBackendId,
+ stableTimeRange?.start,
+ stableTimeRange?.end,
+ pageOffset,
+ pageSize,
+ sortKey,
+ sortOrder,
+ wsPageSearch,
+ ]);
// Debounce search input
useEffect(() => {
@@ -124,13 +166,16 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
start: stableTimeRange?.start,
end: stableTimeRange?.end,
}),
- enabled: !!activeBackendId,
+ enabled: !!activeBackendId && wsPageStatus !== "connected",
placeholderData: keepPreviousData,
});
- const data = ipsQuery.data?.data ?? [];
- const total = ipsQuery.data?.total ?? 0;
- const loading = ipsQuery.isLoading && !ipsQuery.data;
+ const hasWsIPsPage = wsPageEnabled && wsPageStatus === "connected" && wsIPsPage !== null;
+ const data = hasWsIPsPage ? wsIPsPage.data : ipsQuery.data?.data ?? [];
+ const total = hasWsIPsPage ? wsIPsPage.total : ipsQuery.data?.total ?? 0;
+ const loading =
+ (wsPageStatus === "connected" && wsIPsPage === null) ||
+ (!hasWsIPsPage && ipsQuery.isLoading && !ipsQuery.data);
useEffect(() => {
// Backend switch means a different data universe, collapse safely.
@@ -141,6 +186,7 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
queryKey: getIPProxyStatsQueryKey(expandedIP, activeBackendId, detailTimeRange),
queryFn: () => api.getIPProxyStats(expandedIP!, activeBackendId, detailTimeRange),
enabled: !!activeBackendId && !!expandedIP,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) => {
const prevKey = (previousQuery?.queryKey?.[2] ?? null) as
| { ip?: string; backendId?: number | null }
@@ -156,6 +202,7 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
queryKey: getIPDomainDetailsQueryKey(expandedIP, activeBackendId, detailTimeRange),
queryFn: () => api.getIPDomainDetails(expandedIP!, activeBackendId, detailTimeRange),
enabled: !!activeBackendId && !!expandedIP,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) => {
const prevKey = (previousQuery?.queryKey?.[2] ?? null) as
| { ip?: string; backendId?: number | null }
diff --git a/apps/web/components/overview/index.tsx b/apps/web/components/overview/index.tsx
index 729cf01..3bc5d74 100644
--- a/apps/web/components/overview/index.tsx
+++ b/apps/web/components/overview/index.tsx
@@ -6,8 +6,15 @@ import { TopDomainsSimple } from "./top-domains-simple";
import { TopProxiesSimple } from "./top-proxies-simple";
import { TopCountriesSimple } from "./top-countries-simple";
import { TrafficTrendChart } from "@/components/traffic-trend-chart";
+import { useStatsWebSocket } from "@/lib/websocket";
import { api, type TimeRange } from "@/lib/api";
-import type { DomainStats, ProxyStats, CountryStats, TrafficTrendPoint } from "@clashmaster/shared";
+import type {
+ DomainStats,
+ ProxyStats,
+ CountryStats,
+ TrafficTrendPoint,
+ StatsSummary,
+} from "@clashmaster/shared";
type TrendTimeRange = "30m" | "1h" | "24h";
type TrendGranularity = "minute" | "day";
@@ -29,6 +36,7 @@ interface OverviewTabProps {
timeRange: TimeRange;
timePreset: GlobalTimePreset;
activeBackendId?: number;
+ autoRefresh?: boolean;
onNavigate?: (tab: string) => void;
backendStatus?: "healthy" | "unhealthy" | "unknown";
}
@@ -104,6 +112,7 @@ export function OverviewTab({
timeRange,
timePreset,
activeBackendId,
+ autoRefresh = true,
onNavigate,
backendStatus = "unknown",
}: OverviewTabProps) {
@@ -191,6 +200,24 @@ export function OverviewTab({
cacheKey: `${queryStart.toISOString()}-${queryEnd.toISOString()}-${bucketMinutes}`,
};
}, [parsedRange.end, parsedRange.start, canUseTrendSelector, trendTimeRange]);
+ const wsTrendEnabled = autoRefresh && !!activeBackendId && canUseTrendSelector && trendQuery.realtime;
+ const { status: wsTrendStatus } = useStatsWebSocket({
+ backendId: activeBackendId,
+ range: { start: trendQuery.start, end: trendQuery.end },
+ includeTrend: wsTrendEnabled,
+ trendMinutes: trendQuery.minutes,
+ trendBucketMinutes: trendQuery.bucketMinutes,
+ enabled: wsTrendEnabled,
+ onMessage: useCallback((stats: StatsSummary) => {
+ if (!stats.trendStats) return;
+ startTransition(() => {
+ setTrendData(stats.trendStats ?? []);
+ setTrendGranularity(trendQuery.granularity);
+ });
+ setTrendLoading(false);
+ }, [trendQuery.granularity]),
+ });
+ const wsTrendConnected = wsTrendStatus === "connected";
// Load traffic trend data with caching
const loadTrendData = useCallback(async (showLoading = false) => {
@@ -295,6 +322,15 @@ export function OverviewTab({
initialLoadedRef.current = true;
}, [activeBackendId, loadTrendData, trendQuery.realtime]);
+ // Periodic HTTP reconciliation while WS drives real-time updates.
+ useEffect(() => {
+ if (!wsTrendEnabled || !wsTrendConnected) return;
+ const interval = setInterval(() => {
+ loadTrendData(false);
+ }, 90000);
+ return () => clearInterval(interval);
+ }, [wsTrendEnabled, wsTrendConnected, loadTrendData]);
+
// Handle time range change with transition
const handleTimeRangeChange = (range: TrendTimeRange) => {
startTransition(() => {
diff --git a/apps/web/components/rule-chain-flow.tsx b/apps/web/components/rule-chain-flow.tsx
index 0145775..d1aa5b2 100644
--- a/apps/web/components/rule-chain-flow.tsx
+++ b/apps/web/components/rule-chain-flow.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useEffect, useCallback, useMemo, useRef } from "react";
+import { useState, useEffect, useCallback, useMemo, useRef, memo } from "react";
import {
ReactFlow,
ReactFlowProvider,
@@ -33,8 +33,10 @@ import { Button } from "@/components/ui/button";
import { cn, formatBytes, formatNumber } from "@/lib/utils";
import { useTheme } from "next-themes";
import { api, type TimeRange } from "@/lib/api";
+import { useStatsWebSocket } from "@/lib/websocket";
import { resolveActiveChains, type ActiveChainInfo } from "@/lib/active-chain";
import { useTranslations } from "next-intl";
+import type { StatsSummary } from "@clashmaster/shared";
// ---------- Types ----------
@@ -60,6 +62,7 @@ interface UnifiedRuleChainFlowProps {
selectedRule: string | null;
activeBackendId?: number;
timeRange?: TimeRange;
+ autoRefresh?: boolean;
}
// ---------- Layout constants ----------
@@ -361,6 +364,84 @@ function areChainFlowDataEqual(a: AllChainFlowData, b: AllChainFlowData): boolea
return areRulePathsEqual(a.rulePaths, b.rulePaths);
}
+function sortStringArray(values: string[]): string[] {
+ return [...values].sort((a, b) => a.localeCompare(b));
+}
+
+function nodeTypeRank(type: MergedChainNode["nodeType"]): number {
+ if (type === "rule") return 0;
+ if (type === "group") return 1;
+ return 2;
+}
+
+// Normalize node/link ordering to keep index mapping stable across pushes.
+// This avoids unnecessary full re-layout when backend output order changes.
+function normalizeChainFlowData(input: AllChainFlowData): AllChainFlowData {
+ const indexedNodes = input.nodes.map((node, index) => ({ node, index }));
+ indexedNodes.sort((a, b) => {
+ if (a.node.layer !== b.node.layer) return a.node.layer - b.node.layer;
+ const typeDiff = nodeTypeRank(a.node.nodeType) - nodeTypeRank(b.node.nodeType);
+ if (typeDiff !== 0) return typeDiff;
+ return a.node.name.localeCompare(b.node.name);
+ });
+
+ const oldNodeIndexToNew = new Map<number, number>();
+ const nodes: MergedChainNode[] = indexedNodes.map((item, nextIndex) => {
+ oldNodeIndexToNew.set(item.index, nextIndex);
+ return {
+ ...item.node,
+ rules: sortStringArray(item.node.rules),
+ _zeroTraffic: !!item.node._zeroTraffic,
+ };
+ });
+
+ const indexedLinks = input.links.map((link, index) => {
+ const source = oldNodeIndexToNew.get(link.source);
+ const target = oldNodeIndexToNew.get(link.target);
+ if (source === undefined || target === undefined) {
+ return null;
+ }
+ return {
+ index,
+ link: {
+ source,
+ target,
+ rules: sortStringArray(link.rules),
+ },
+ };
+ }).filter((item): item is { index: number; link: { source: number; target: number; rules: string[] } } => !!item);
+
+ indexedLinks.sort((a, b) => {
+ if (a.link.source !== b.link.source) return a.link.source - b.link.source;
+ if (a.link.target !== b.link.target) return a.link.target - b.link.target;
+ const aRules = a.link.rules.join("|");
+ const bRules = b.link.rules.join("|");
+ return aRules.localeCompare(bRules);
+ });
+
+ const oldLinkIndexToNew = new Map<number, number>();
+ const links = indexedLinks.map((item, nextIndex) => {
+ oldLinkIndexToNew.set(item.index, nextIndex);
+ return item.link;
+ });
+
+ const rulePaths: Record<string, { nodeIndices: number[]; linkIndices: number[] }> = {};
+ const ruleNames = Object.keys(input.rulePaths).sort((a, b) => a.localeCompare(b));
+ for (const ruleName of ruleNames) {
+ const path = input.rulePaths[ruleName];
+ const nodeIndices = path.nodeIndices
+ .map((oldIndex) => oldNodeIndexToNew.get(oldIndex))
+ .filter((value): value is number => value !== undefined);
+ const linkIndices = path.linkIndices
+ .map((oldIndex) => oldLinkIndexToNew.get(oldIndex))
+ .filter((value): value is number => value !== undefined);
+ rulePaths[ruleName] = { nodeIndices, linkIndices };
+ }
+
+ const maxLayer = nodes.reduce((max, node) => Math.max(max, node.layer), 0);
+ return { nodes, links, rulePaths, maxLayer };
+}
+
// ---------- Inner renderer (needs ReactFlowProvider context) ----------
function FlowRenderer({
@@ -419,23 +500,42 @@ function FlowRenderer({
// For data-only updates: update node data in-place without re-layout or fitView
if (isDataOnlyUpdate) {
- setNodes((prev) =>
- prev.map((node) => {
+ const activeNodeSet = activeIndices
+ ? new Set(activeIndices.nodeIndices)
+ : null;
+ setNodes((prev) => {
+ let changed = false;
+ const next = prev.map((node) => {
const idx = Number(node.id);
const freshNode = data.nodes[idx];
if (!freshNode) return node;
- const activeNodeSet = activeIndices
- ? new Set(activeIndices.nodeIndices)
- : null;
+ const dimmed = activeNodeSet ? !activeNodeSet.has(idx) : false;
+ const prevData = node.data as unknown as (MergedChainNode & { dimmed?: boolean });
+ if (
+ prevData.name === freshNode.name &&
+ prevData.layer === freshNode.layer &&
+ prevData.nodeType === freshNode.nodeType &&
+ prevData.totalUpload === freshNode.totalUpload &&
+ prevData.totalDownload === freshNode.totalDownload &&
+ prevData.totalConnections === freshNode.totalConnections &&
+ prevData._zeroTraffic === !!freshNode._zeroTraffic &&
+ prevData.dimmed === dimmed &&
+ areStringArraysEqual(prevData.rules, freshNode.rules)
+ ) {
+ return node;
+ }
+ changed = true;
return {
...node,
data: {
...freshNode,
- dimmed: activeNodeSet ? !activeNodeSet.has(idx) : false,
+ dimmed,
+ _zeroTraffic: !!freshNode._zeroTraffic,
},
};
- }),
- );
+ });
+ return changed ? next : prev;
+ });
return;
}
@@ -667,12 +767,15 @@ function FlowRenderer({
);
}
+const MemoizedFlowRenderer = memo(FlowRenderer);
+
// ---------- Main component ----------
-export function UnifiedRuleChainFlow({
+function UnifiedRuleChainFlowInner({
selectedRule,
activeBackendId,
timeRange,
+ autoRefresh = true,
}: UnifiedRuleChainFlowProps) {
const t = useTranslations("rules");
const [data, setData] = useState<AllChainFlowData | null>(null);
@@ -688,6 +791,33 @@ export function UnifiedRuleChainFlow({
const prevBackendRef = useRef<number | undefined>(undefined);
const flowContainerRef = useRef<HTMLDivElement | null>(null);
const [isFullscreen, setIsFullscreen] = useState(false);
+ const commitChainFlowData = useCallback((next: AllChainFlowData) => {
+ const normalized = normalizeChainFlowData(next);
+ setData((prev) => {
+ if (prev && areChainFlowDataEqual(prev, normalized)) {
+ return prev;
+ }
+ return normalized;
+ });
+ hasLoadedRef.current = true;
+ prevBackendRef.current = activeBackendId;
+ setError(null);
+ setLoading(false);
+ }, [activeBackendId]);
+
+ const wsEnabled = autoRefresh && !!activeBackendId;
+ const { status: wsStatus } = useStatsWebSocket({
+ backendId: activeBackendId,
+ range: timeRange,
+ includeRuleChainFlow: wsEnabled,
+ enabled: wsEnabled,
+ onMessage: useCallback((stats: StatsSummary) => {
+ if (!stats.ruleChainFlowAll) return;
+ commitChainFlowData(stats.ruleChainFlowAll);
+ }, [commitChainFlowData]),
+ });
+
+ const useHttpFallback = !wsEnabled || wsStatus !== "connected";
const toggleFullscreen = useCallback(async () => {
if (typeof document === "undefined") return;
@@ -745,9 +875,12 @@ export function UnifiedRuleChainFlow({
};
}, []);
- // Fetch on backend/time-range changes. Parent already drives 5s updates
- // for rolling windows, so avoid an additional local polling loop.
+ // HTTP fallback only when websocket is disabled or not connected.
useEffect(() => {
+ if (!useHttpFallback) {
+ return;
+ }
+
let cancelled = false;
const requestId = ++requestIdRef.current;
const backendChanged = prevBackendRef.current !== activeBackendId;
@@ -761,14 +894,7 @@ export function UnifiedRuleChainFlow({
try {
const result = await api.getAllRuleChainFlows(activeBackendId, timeRange);
if (cancelled || requestId !== requestIdRef.current) return;
- setData((prev) => {
- if (prev && areChainFlowDataEqual(prev, result)) {
- return prev;
- }
- return result;
- });
- hasLoadedRef.current = true;
- prevBackendRef.current = activeBackendId;
+ commitChainFlowData(result);
} catch (err) {
if (cancelled || requestId !== requestIdRef.current) return;
console.error("Failed to load chain flows:", err);
@@ -787,7 +913,18 @@ export function UnifiedRuleChainFlow({
return () => {
cancelled = true;
};
- }, [activeBackendId, timeRange]);
+ }, [activeBackendId, timeRange, useHttpFallback, commitChainFlowData]);
+
+ useEffect(() => {
+ if (!wsEnabled) {
+ return;
+ }
+ const backendChanged = prevBackendRef.current !== activeBackendId;
+ if (backendChanged) {
+ setLoading(true);
+ setError(null);
+ }
+ }, [activeBackendId, wsEnabled]);
// Fetch active chain info when activePolicyOnly is ON
useEffect(() => {
@@ -811,12 +948,17 @@ export function UnifiedRuleChainFlow({
}
fetchActiveChains();
- const interval = setInterval(fetchActiveChains, 10000);
+ if (!autoRefresh) {
+ return () => {
+ cancelled = true;
+ };
+ }
+ const interval = setInterval(fetchActiveChains, 60000);
return () => {
cancelled = true;
clearInterval(interval);
};
- }, [activePolicyOnly, activeBackendId]);
+ }, [activePolicyOnly, activeBackendId, autoRefresh]);
// When user selects a different rule, auto-disable showAll
useEffect(() => {
@@ -958,7 +1100,6 @@ export function UnifiedRuleChainFlow({
};
}, [data, activePolicyOnly, activeChainInfo]);
- // Use filteredData for rendering
const renderData = filteredData;
// Container height: compact for focused mode, taller for show-all
@@ -1076,7 +1217,7 @@ export function UnifiedRuleChainFlow({
</div>
)}
<ReactFlowProvider>
- <FlowRenderer
+ <MemoizedFlowRenderer
data={renderData}
selectedRule={showAll ? null : selectedRule}
showAll={showAll}
@@ -1090,5 +1231,15 @@ export function UnifiedRuleChainFlow({
);
}
+export const UnifiedRuleChainFlow = memo(
+ UnifiedRuleChainFlowInner,
+ (prev, next) =>
+ prev.selectedRule === next.selectedRule &&
+ prev.activeBackendId === next.activeBackendId &&
+ prev.autoRefresh === next.autoRefresh &&
+ prev.timeRange?.start === next.timeRange?.start &&
+ prev.timeRange?.end === next.timeRange?.end,
+);
+
// Backward-compatible alias
export { UnifiedRuleChainFlow as RuleChainFlow };
diff --git a/apps/web/components/stats-tables/domain-stats-table.tsx b/apps/web/components/stats-tables/domain-stats-table.tsx
index d03fff7..1eefcfd 100644
--- a/apps/web/components/stats-tables/domain-stats-table.tsx
+++ b/apps/web/components/stats-tables/domain-stats-table.tsx
@@ -45,6 +45,7 @@ import {
type SortOrder,
} from "@/lib/stats-utils";
import type { DomainStats } from "@clashmaster/shared";
+const DETAIL_QUERY_STALE_MS = 30_000;
interface DomainStatsTableProps {
domains: DomainStats[];
@@ -102,6 +103,7 @@ export function DomainStatsTable({
sourceChain,
),
enabled: richExpand && !!activeBackendId && !!expandedDomain,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
domain: expandedDomain ?? "",
@@ -125,6 +127,7 @@ export function DomainStatsTable({
sourceChain,
),
enabled: richExpand && !!activeBackendId && !!expandedDomain,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
domain: expandedDomain ?? "",
diff --git a/apps/web/components/stats-tables/ip-stats-table.tsx b/apps/web/components/stats-tables/ip-stats-table.tsx
index d31408d..de954e0 100644
--- a/apps/web/components/stats-tables/ip-stats-table.tsx
+++ b/apps/web/components/stats-tables/ip-stats-table.tsx
@@ -47,6 +47,7 @@ import {
type SortOrder,
} from "@/lib/stats-utils";
import type { IPStats } from "@clashmaster/shared";
+const DETAIL_QUERY_STALE_MS = 30_000;
interface IPStatsTableProps {
ips: IPStats[];
@@ -104,6 +105,7 @@ export function IPStatsTable({
sourceChain,
),
enabled: richExpand && !!activeBackendId && !!expandedIP,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
ip: expandedIP ?? "",
@@ -128,6 +130,7 @@ export function IPStatsTable({
sourceChain,
),
enabled: richExpand && !!activeBackendId && !!expandedIP,
+ staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
keepPreviousByIdentity(previousData, previousQuery, {
ip: expandedIP ?? "",
diff --git a/apps/web/components/top-domains-chart.tsx b/apps/web/components/top-domains-chart.tsx
index d4caf74..e18108e 100644
--- a/apps/web/components/top-domains-chart.tsx
+++ b/apps/web/components/top-domains-chart.tsx
@@ -25,6 +25,7 @@ import { getDomainsQueryKey } from "@/lib/stats-query-keys";
import type { DomainStats } from "@clashmaster/shared";
interface TopDomainsChartProps {
+ data?: DomainStats[];
activeBackendId?: number;
timeRange?: TimeRange;
}
@@ -71,7 +72,7 @@ function renderCustomBarLabel(props: any) {
);
}
-export function TopDomainsChart({ activeBackendId, timeRange }: TopDomainsChartProps) {
+export function TopDomainsChart({ data, activeBackendId, timeRange }: TopDomainsChartProps) {
const t = useTranslations("domains");
const commonT = useTranslations("stats");
const [topN, setTopN] = useState<TopOption>(10);
@@ -102,12 +103,17 @@ export function TopDomainsChart({ activeBackendId, timeRange }: TopDomainsChartP
start: stableTimeRange?.start,
end: stableTimeRange?.end,
}),
- enabled: !!activeBackendId,
+ enabled: !data && !!activeBackendId,
placeholderData: keepPreviousData,
});
- const domains = domainsQuery.data?.data ?? [];
- const isLoading = domainsQuery.isLoading && !domainsQuery.data;
+ const domains = useMemo(() => {
+ const source = data ?? domainsQuery.data?.data ?? [];
+ return [...source]
+ .sort((a, b) => b.totalDownload - a.totalDownload)
+ .slice(0, topN);
+ }, [data, domainsQuery.data?.data, topN]);
+ const isLoading = !data && domainsQuery.isLoading && !domainsQuery.data;
useEffect(() => {
if (!containerRef.current) return;
diff --git a/apps/web/components/traffic-trend-chart.tsx b/apps/web/components/traffic-trend-chart.tsx
index a7b0d4f..bc186d3 100644
--- a/apps/web/components/traffic-trend-chart.tsx
+++ b/apps/web/components/traffic-trend-chart.tsx
@@ -199,28 +199,30 @@ export const TrafficTrendChart = React.memo(
{t("title")}
</CardTitle>
- <div className={selectorSlotClassName}>
- {showTimeRangeSelector ? (
- <div className="flex items-center gap-0.5 bg-muted/50 rounded-lg p-0.5">
- {selectorOptions.map((option) => (
- <Button
- key={option.value}
- variant="ghost"
- size="sm"
- className={cn(
- "h-7 px-3 text-xs rounded-md transition-all",
- timeRange === option.value
- ? "bg-background shadow-sm text-primary font-medium"
- : "text-muted-foreground hover:text-foreground",
- )}
- onClick={() => onTimeRangeChange?.(option.value)}>
- {option.label}
- </Button>
- ))}
- </div>
- ) : (
- <div aria-hidden className="h-7 w-[168px]" />
- )}
+ <div className="flex items-center gap-2">
+ <div className={selectorSlotClassName}>
+ {showTimeRangeSelector ? (
+ <div className="flex items-center gap-0.5 bg-muted/50 rounded-lg p-0.5">
+ {selectorOptions.map((option) => (
+ <Button
+ key={option.value}
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "h-7 px-3 text-xs rounded-md transition-all",
+ timeRange === option.value
+ ? "bg-background shadow-sm text-primary font-medium"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ onClick={() => onTimeRangeChange?.(option.value)}>
+ {option.label}
+ </Button>
+ ))}
+ </div>
+ ) : (
+ <div aria-hidden className="h-7 w-[168px]" />
+ )}
+ </div>
</div>
</div>
diff --git a/apps/web/lib/websocket.ts b/apps/web/lib/websocket.ts
index 575ee5d..030ec8f 100644
--- a/apps/web/lib/websocket.ts
+++ b/apps/web/lib/websocket.ts
@@ -1,15 +1,45 @@
import { useEffect, useRef, useState, useCallback } from 'react';
import type { StatsSummary } from '@clashmaster/shared';
+import type { TimeRange } from '@/lib/api';
export type ConnectionStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
interface WebSocketMessage {
type: 'stats' | 'ping' | 'pong';
+ backendId?: number;
data?: StatsSummary;
timestamp: string;
}
-interface UseWebSocketOptions {
+interface UseStatsWebSocketOptions {
+ backendId?: number;
+ range?: TimeRange;
+ includeTrend?: boolean;
+ trendMinutes?: number;
+ trendBucketMinutes?: number;
+ includeDeviceDetails?: boolean;
+ deviceSourceIP?: string;
+ deviceDetailLimit?: number;
+ includeProxyDetails?: boolean;
+ proxyChain?: string;
+ proxyDetailLimit?: number;
+ includeRuleDetails?: boolean;
+ ruleName?: string;
+ ruleDetailLimit?: number;
+ includeRuleChainFlow?: boolean;
+ includeDomainsPage?: boolean;
+ domainsPageOffset?: number;
+ domainsPageLimit?: number;
+ domainsPageSortBy?: string;
+ domainsPageSortOrder?: "asc" | "desc";
+ domainsPageSearch?: string;
+ includeIPsPage?: boolean;
+ ipsPageOffset?: number;
+ ipsPageLimit?: number;
+ ipsPageSortBy?: string;
+ ipsPageSortOrder?: "asc" | "desc";
+ ipsPageSearch?: string;
+ enabled?: boolean;
onMessage?: (data: StatsSummary) => void;
onConnect?: () => void;
onDisconnect?: () => void;
@@ -27,7 +57,48 @@ function getRuntimeConfig(): RuntimeConfig | undefined {
return (window as any).__RUNTIME_CONFIG__ as RuntimeConfig | undefined;
}
-export function useStatsWebSocket(options: UseWebSocketOptions = {}) {
+function getWsUrl(): string {
+ const runtime = getRuntimeConfig();
+ const wsPort = runtime?.WS_PORT || process.env.NEXT_PUBLIC_WS_PORT || '3002';
+ if (runtime?.WS_URL) return runtime.WS_URL;
+ if (process.env.NEXT_PUBLIC_WS_URL) return process.env.NEXT_PUBLIC_WS_URL;
+ if (typeof window !== 'undefined') {
+ return `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${runtime?.WS_HOST || window.location.hostname}:${wsPort}`;
+ }
+ return `ws://localhost:${wsPort}`;
+}
+
+export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
+ const {
+ backendId,
+ range,
+ includeTrend,
+ trendMinutes,
+ trendBucketMinutes,
+ includeDeviceDetails,
+ deviceSourceIP,
+ deviceDetailLimit,
+ includeProxyDetails,
+ proxyChain,
+ proxyDetailLimit,
+ includeRuleDetails,
+ ruleName,
+ ruleDetailLimit,
+ includeRuleChainFlow,
+ includeDomainsPage,
+ domainsPageOffset,
+ domainsPageLimit,
+ domainsPageSortBy,
+ domainsPageSortOrder,
+ domainsPageSearch,
+ includeIPsPage,
+ ipsPageOffset,
+ ipsPageLimit,
+ ipsPageSortBy,
+ ipsPageSortOrder,
+ ipsPageSearch,
+ enabled = true,
+ } = options;
const [status, setStatus] = useState<ConnectionStatus>('disconnected');
const [lastMessage, setLastMessage] = useState<StatsSummary | null>(null);
const [latency, setLatency] = useState<number | null>(null);
@@ -36,26 +107,47 @@ export function useStatsWebSocket(options: UseWebSocketOptions = {}) {
const pingIntervalRef = useRef<NodeJS.Timeout | null>(null);
const lastPingTimeRef = useRef<number>(0);
const reconnectAttemptsRef = useRef<number>(0);
- const maxReconnectAttempts = 5;
+ const maxReconnectDelayMs = 30000;
+ const onMessageRef = useRef(options.onMessage);
+ const onConnectRef = useRef(options.onConnect);
+ const onDisconnectRef = useRef(options.onDisconnect);
+ const onErrorRef = useRef(options.onError);
+ onMessageRef.current = options.onMessage;
+ onConnectRef.current = options.onConnect;
+ onDisconnectRef.current = options.onDisconnect;
+ onErrorRef.current = options.onError;
+
+ const cleanup = useCallback(() => {
+ if (reconnectTimerRef.current) {
+ clearTimeout(reconnectTimerRef.current);
+ reconnectTimerRef.current = null;
+ }
+ if (pingIntervalRef.current) {
+ clearInterval(pingIntervalRef.current);
+ pingIntervalRef.current = null;
+ }
+ if (wsRef.current) {
+ // Nullify handlers BEFORE closing to prevent stale onclose/onerror
+ // from overwriting status set by a newer connection
+ wsRef.current.onopen = null;
+ wsRef.current.onmessage = null;
+ wsRef.current.onclose = null;
+ wsRef.current.onerror = null;
+ wsRef.current.close();
+ wsRef.current = null;
+ }
+ }, []);
const connect = useCallback(() => {
- if (wsRef.current?.readyState === WebSocket.OPEN) return;
+ if (
+ wsRef.current?.readyState === WebSocket.OPEN ||
+ wsRef.current?.readyState === WebSocket.CONNECTING
+ ) return;
if (typeof window === 'undefined') return;
setStatus('connecting');
- // Support dynamic WebSocket URL configuration
- // Priority: runtime WS_URL > runtime WS_PORT > NEXT_PUBLIC_WS_URL > NEXT_PUBLIC_WS_PORT > default localhost
- const runtime = getRuntimeConfig();
- const wsPort = runtime?.WS_PORT || process.env.NEXT_PUBLIC_WS_PORT || '3002';
- const wsUrl = runtime?.WS_URL
- ? runtime.WS_URL
- : process.env.NEXT_PUBLIC_WS_URL
- ? process.env.NEXT_PUBLIC_WS_URL
- : typeof window !== 'undefined'
- ? `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${runtime?.WS_HOST || window.location.hostname}:${wsPort}`
- : `ws://localhost:${wsPort}`;
-
+ const wsUrl = getWsUrl();
console.log('[WebSocket] Connecting to:', wsUrl);
try {
@@ -66,7 +158,7 @@ export function useStatsWebSocket(options: UseWebSocketOptions = {}) {
console.log('[WebSocket] Connected successfully');
setStatus('connected');
reconnectAttemptsRef.current = 0;
- options.onConnect?.();
+ onConnectRef.current?.();
// Start ping interval
pingIntervalRef.current = setInterval(() => {
@@ -83,7 +175,7 @@ export function useStatsWebSocket(options: UseWebSocketOptions = {}) {
if (message.type === 'stats' && message.data) {
setLastMessage(message.data);
- options.onMessage?.(message.data);
+ onMessageRef.current?.(message.data);
} else if (message.type === 'pong') {
if (lastPingTimeRef.current > 0) {
setLatency(Date.now() - lastPingTimeRef.current);
@@ -97,61 +189,124 @@ export function useStatsWebSocket(options: UseWebSocketOptions = {}) {
ws.onclose = (event) => {
console.log(`[WebSocket] Disconnected. Code: ${event.code}, Reason: ${event.reason}`);
setStatus('disconnected');
- options.onDisconnect?.();
+ onDisconnectRef.current?.();
- // Clear intervals
+ // Clear ping interval
if (pingIntervalRef.current) {
clearInterval(pingIntervalRef.current);
pingIntervalRef.current = null;
}
- // Auto reconnect with exponential backoff
- if (reconnectAttemptsRef.current < maxReconnectAttempts) {
- const delay = Math.min(3000 * Math.pow(2, reconnectAttemptsRef.current), 30000);
- reconnectAttemptsRef.current++;
- console.log(`[WebSocket] Reconnecting in ${delay}ms (attempt ${reconnectAttemptsRef.current})`);
-
- reconnectTimerRef.current = setTimeout(() => {
- connect();
- }, delay);
- } else {
- console.log('[WebSocket] Max reconnection attempts reached, giving up');
- setStatus('error');
- }
+ // Auto reconnect with exponential backoff.
+ const delay = Math.min(3000 * Math.pow(2, reconnectAttemptsRef.current), maxReconnectDelayMs);
+ reconnectAttemptsRef.current++;
+ console.log(`[WebSocket] Reconnecting in ${delay}ms (attempt ${reconnectAttemptsRef.current})`);
+ reconnectTimerRef.current = setTimeout(() => {
+ connect();
+ }, delay);
};
ws.onerror = (error) => {
console.error('[WebSocket] Connection error. URL:', wsUrl);
setStatus('error');
- options.onError?.(error);
+ onErrorRef.current?.(error);
};
} catch (err) {
console.error('[WebSocket] Failed to create connection:', err);
setStatus('error');
}
- }, [options]);
+ }, []);
+
+ // Send subscribe message when backend/time-range changes or WS becomes connected.
+ useEffect(() => {
+ if (status !== 'connected') return;
+ if (wsRef.current?.readyState !== WebSocket.OPEN) return;
+ if (backendId === undefined) return;
+
+ console.log('[WebSocket] Subscribing to backend:', backendId);
+ wsRef.current.send(JSON.stringify({
+ type: 'subscribe',
+ backendId,
+ start: range?.start,
+ end: range?.end,
+ includeTrend,
+ trendMinutes,
+ trendBucketMinutes,
+ includeDeviceDetails,
+ deviceSourceIP,
+ deviceDetailLimit,
+ includeProxyDetails,
+ proxyChain,
+ proxyDetailLimit,
+ includeRuleDetails,
+ ruleName,
+ ruleDetailLimit,
+ includeRuleChainFlow,
+ includeDomainsPage,
+ domainsPageOffset,
+ domainsPageLimit,
+ domainsPageSortBy,
+ domainsPageSortOrder,
+ domainsPageSearch,
+ includeIPsPage,
+ ipsPageOffset,
+ ipsPageLimit,
+ ipsPageSortBy,
+ ipsPageSortOrder,
+ ipsPageSearch,
+ timestamp: new Date().toISOString(),
+ }));
+ }, [
+ backendId,
+ range?.start,
+ range?.end,
+ includeTrend,
+ trendMinutes,
+ trendBucketMinutes,
+ includeDeviceDetails,
+ deviceSourceIP,
+ deviceDetailLimit,
+ includeProxyDetails,
+ proxyChain,
+ proxyDetailLimit,
+ includeRuleDetails,
+ ruleName,
+ ruleDetailLimit,
+ includeRuleChainFlow,
+ includeDomainsPage,
+ domainsPageOffset,
+ domainsPageLimit,
+ domainsPageSortBy,
+ domainsPageSortOrder,
+ domainsPageSearch,
+ includeIPsPage,
+ ipsPageOffset,
+ ipsPageLimit,
+ ipsPageSortBy,
+ ipsPageSortOrder,
+ ipsPageSearch,
+ status,
+ ]);
const disconnect = useCallback(() => {
- reconnectAttemptsRef.current = maxReconnectAttempts; // Prevent auto reconnect
- if (reconnectTimerRef.current) {
- clearTimeout(reconnectTimerRef.current);
- reconnectTimerRef.current = null;
- }
- if (pingIntervalRef.current) {
- clearInterval(pingIntervalRef.current);
- pingIntervalRef.current = null;
- }
- if (wsRef.current) {
- wsRef.current.close();
- wsRef.current = null;
- }
+ reconnectAttemptsRef.current = 0;
+ cleanup();
setStatus('disconnected');
- }, []);
+ }, [cleanup]);
useEffect(() => {
+ if (!enabled) {
+ disconnect();
+ return;
+ }
+
+ reconnectAttemptsRef.current = 0;
connect();
- return () => disconnect();
- }, [connect, disconnect]);
+
+ return () => {
+ disconnect();
+ };
+ }, [enabled, connect, disconnect]);
return {
status,
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 68b7f53..b5eabe8 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -140,6 +140,25 @@ export interface ProxyTrafficStats {
totalConnections: number;
}
+export interface RuleChainFlowAll {
+ nodes: Array<{
+ name: string;
+ layer: number;
+ nodeType: "rule" | "group" | "proxy";
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ rules: string[];
+ }>;
+ links: Array<{
+ source: number;
+ target: number;
+ rules: string[];
+ }>;
+ rulePaths: Record<string, { nodeIndices: number[]; linkIndices: number[] }>;
+ maxLayer: number;
+}
+
// API Response Types
export interface StatsSummary {
totalUpload: number;
@@ -155,6 +174,35 @@ export interface StatsSummary {
topDomains: DomainStats[];
topIPs: IPStats[];
proxyStats: ProxyStats[];
+ countryStats?: CountryStats[];
+ deviceStats?: DeviceStats[];
+ deviceDetailSourceIP?: string;
+ deviceDomains?: DomainStats[];
+ deviceIPs?: IPStats[];
+ proxyDetailChain?: string;
+ proxyDomains?: DomainStats[];
+ proxyIPs?: IPStats[];
+ ruleDetailName?: string;
+ ruleDomains?: DomainStats[];
+ ruleIPs?: IPStats[];
+ ruleChainFlowAll?: RuleChainFlowAll;
+ domainsPage?: { data: DomainStats[]; total: number };
+ domainsPageQuery?: {
+ offset: number;
+ limit: number;
+ sortBy?: string;
+ sortOrder?: "asc" | "desc";
+ search?: string;
+ };
+ ipsPage?: { data: IPStats[]; total: number };
+ ipsPageQuery?: {
+ offset: number;
+ limit: number;
+ sortBy?: string;
+ sortOrder?: "asc" | "desc";
+ search?: string;
+ };
+ trendStats?: TrafficTrendPoint[];
ruleStats?: RuleStats[];
hourlyStats: HourlyStats[];
}