Skip to content

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

feat: Implement real-time traffic statistics collection and enhance version status display in the about dialog.

luoleidfaa2f0d13dd
diff --git a/apps/collector/src/api.ts b/apps/collector/src/api.ts
index 825ccc2..ca455f3 100644
--- a/apps/collector/src/api.ts
+++ b/apps/collector/src/api.ts
@@ -1,6 +1,7 @@
import Fastify from 'fastify';
import cors from '@fastify/cors';
import type { StatsDatabase } from './db.js';
+import { realtimeStore } from './realtime.js';
export class APIServer {
private app: ReturnType<typeof Fastify> | null = null;
@@ -50,12 +51,25 @@ export class APIServer {
}
const summary = this.db.getSummary(backendId);
- const topDomains = this.db.getTopDomains(backendId, 10);
- const topIPs = this.db.getTopIPs(backendId, 10);
- const proxyStats = this.db.getProxyStats(backendId);
+ const summaryWithRealtime = realtimeStore.applySummaryDelta(backendId, summary);
+ const topDomains = realtimeStore.mergeTopDomains(
+ backendId,
+ this.db.getTopDomains(backendId, 10),
+ 10
+ );
+ const topIPs = realtimeStore.mergeTopIPs(
+ backendId,
+ this.db.getTopIPs(backendId, 10),
+ 10
+ );
+ const proxyStats = realtimeStore.mergeProxyStats(
+ backendId,
+ this.db.getProxyStats(backendId)
+ );
const ruleStats = this.db.getRuleStats(backendId);
const hourlyStats = this.db.getHourlyStats(backendId, 24);
const todayTraffic = this.db.getTodayTraffic(backendId);
+ const todayDelta = realtimeStore.getTodayDelta(backendId);
return {
backend: {
@@ -64,15 +78,15 @@ export class APIServer {
isActive: backend.is_active,
listening: backend.listening,
},
- totalConnections: summary.totalConnections,
- totalUpload: summary.totalUpload,
- totalDownload: summary.totalDownload,
+ totalConnections: summaryWithRealtime.totalConnections,
+ totalUpload: summaryWithRealtime.totalUpload,
+ totalDownload: summaryWithRealtime.totalDownload,
totalDomains: summary.uniqueDomains,
totalIPs: summary.uniqueIPs,
totalRules: ruleStats.length,
totalProxies: proxyStats.length,
- todayUpload: todayTraffic.upload,
- todayDownload: todayTraffic.download,
+ todayUpload: todayTraffic.upload + todayDelta.upload,
+ todayDownload: todayTraffic.download + todayDelta.download,
topDomains,
topIPs,
proxyStats,
@@ -229,7 +243,10 @@ export class APIServer {
return reply.status(404).send({ error: 'No backend specified or active' });
}
- return this.db.getProxyStats(backendId);
+ return realtimeStore.mergeProxyStats(
+ backendId,
+ this.db.getProxyStats(backendId)
+ );
});
// Get rule statistics for a specific backend
@@ -321,7 +338,10 @@ export class APIServer {
return reply.status(404).send({ error: 'No backend specified or active' });
}
- return this.db.getCountryStats(backendId);
+ return realtimeStore.mergeCountryStats(
+ backendId,
+ this.db.getCountryStats(backendId)
+ );
});
// Get hourly statistics for a specific backend
@@ -345,7 +365,9 @@ export class APIServer {
}
const { minutes = 30 } = request.query as { minutes?: string };
- return this.db.getTrafficTrend(backendId, parseInt(minutes as string) || 30);
+ const windowMinutes = parseInt(minutes as string) || 30;
+ const base = this.db.getTrafficTrend(backendId, windowMinutes);
+ return realtimeStore.mergeTrend(backendId, base, windowMinutes, 1);
});
// Get traffic trend aggregated by time buckets for chart display
@@ -357,11 +379,10 @@ export class APIServer {
}
const { minutes = 30, bucketMinutes = 1 } = request.query as { minutes?: string; bucketMinutes?: string };
- return this.db.getTrafficTrendAggregated(
- backendId,
- parseInt(minutes as string) || 30,
- parseInt(bucketMinutes as string) || 1
- );
+ const windowMinutes = parseInt(minutes as string) || 30;
+ const bucket = parseInt(bucketMinutes as string) || 1;
+ const base = this.db.getTrafficTrendAggregated(backendId, windowMinutes, bucket);
+ return realtimeStore.mergeTrend(backendId, base, windowMinutes, bucket);
});
// Get recent connections for a specific backend
diff --git a/apps/collector/src/collector.ts b/apps/collector/src/collector.ts
index 86626d2..bf1f74a 100644
--- a/apps/collector/src/collector.ts
+++ b/apps/collector/src/collector.ts
@@ -1,7 +1,8 @@
-import WebSocket from 'ws';
-import type { ConnectionsData } from '@clashmaster/shared';
-import { StatsDatabase } from './db.js';
-import { GeoIPService } from './geo-service.js';
+import WebSocket from "ws";
+import type { ConnectionsData } from "@clashmaster/shared";
+import { StatsDatabase } from "./db.js";
+import { GeoIPService } from "./geo-service.js";
+import { realtimeStore } from "./realtime.js";
interface CollectorOptions {
url: string;
@@ -59,11 +60,13 @@ export class OpenClashCollector {
console.log(`[Collector:${this.backendId}] Connecting to ${this.url}...`);
const headers: Record<string, string> = {
- 'Origin': this.url.replace('ws://', 'http://').replace('wss://', 'https://'),
+ Origin: this.url
+ .replace("ws://", "http://")
+ .replace("wss://", "https://"),
};
if (this.token) {
- headers['Authorization'] = `Bearer ${this.token}`;
+ headers["Authorization"] = `Bearer ${this.token}`;
}
this.ws = new WebSocket(this.url, {
@@ -71,26 +74,34 @@ export class OpenClashCollector {
followRedirects: true,
});
- this.ws.on('open', () => {
+ this.ws.on("open", () => {
console.log(`[Collector:${this.backendId}] WebSocket connected`);
});
- this.ws.on('message', (data: WebSocket.Data) => {
+ this.ws.on("message", (data: WebSocket.Data) => {
try {
const json = JSON.parse(data.toString()) as ConnectionsData;
this.onData?.(json);
} catch (err) {
- console.error(`[Collector:${this.backendId}] Failed to parse message:`, err);
+ console.error(
+ `[Collector:${this.backendId}] Failed to parse message:`,
+ err,
+ );
}
});
- this.ws.on('error', (err) => {
- console.error(`[Collector:${this.backendId}] WebSocket error:`, err.message);
+ this.ws.on("error", (err) => {
+ console.error(
+ `[Collector:${this.backendId}] WebSocket error:`,
+ err.message,
+ );
this.onError?.(err);
});
- this.ws.on('close', (code, reason) => {
- console.log(`[Collector:${this.backendId}] WebSocket closed: ${code} ${reason}`);
+ this.ws.on("close", (code, reason) => {
+ console.log(
+ `[Collector:${this.backendId}] WebSocket closed: ${code} ${reason}`,
+ );
if (!this.isClosing) {
this.scheduleReconnect();
}
@@ -99,7 +110,9 @@ export class OpenClashCollector {
private scheduleReconnect() {
if (this.reconnectTimer) return;
- console.log(`[Collector:${this.backendId}] Reconnecting in ${this.reconnectInterval}ms...`);
+ console.log(
+ `[Collector:${this.backendId}] Reconnecting in ${this.reconnectInterval}ms...`,
+ );
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.connect();
@@ -126,11 +139,11 @@ class BatchBuffer {
private geoQueue: GeoIPResult[] = [];
private lastLogTime = 0;
private logCounter = 0;
-
+
add(backendId: number, update: TrafficUpdate) {
const key = `${backendId}:${update.domain}:${update.ip}:${update.chain}`;
const existing = this.buffer.get(key);
-
+
if (existing) {
existing.upload += update.upload;
existing.download += update.download;
@@ -138,55 +151,86 @@ class BatchBuffer {
this.buffer.set(key, { ...update });
}
}
-
+
addGeoResult(result: GeoIPResult) {
this.geoQueue.push(result);
}
-
- flush(db: StatsDatabase, geoService: GeoIPService | undefined, backendId: number): { domains: number; rules: number } {
+
+ flush(
+ db: StatsDatabase,
+ geoService: GeoIPService | undefined,
+ backendId: number,
+ ): { domains: number; rules: number; trafficOk: boolean; countryOk: boolean; hasUpdates: boolean } {
if (this.buffer.size === 0) {
- return { domains: 0, rules: 0 };
+ return { domains: 0, rules: 0, trafficOk: true, countryOk: true, hasUpdates: false };
}
-
+
const updates = Array.from(this.buffer.values());
- this.buffer.clear();
-
+
// Merge geo queue
const geoResults = [...this.geoQueue];
- this.geoQueue = [];
-
+
// Calculate unique domains and rules for logging
const domains = new Set<string>();
const rules = new Set<string>();
-
+
for (const update of updates) {
if (update.domain) domains.add(update.domain);
- const initialRule = update.chains.length > 0 ? update.chains[update.chains.length - 1] : 'DIRECT';
+ const initialRule =
+ update.chains.length > 0
+ ? update.chains[update.chains.length - 1]
+ : "DIRECT";
rules.add(initialRule);
}
-
+
// Batch write to database
+ let trafficOk = true;
+ let countryOk = true;
try {
db.batchUpdateTrafficStats(backendId, updates);
-
- // Process geo results in batch
- const countryUpdates = geoResults
- .filter((r): r is GeoIPResult & { geo: NonNullable<GeoIPResult['geo']> } => r.geo !== null)
- .map(r => ({
- country: r.geo.country,
- countryName: r.geo.country_name,
- continent: r.geo.continent,
- upload: r.upload,
- download: r.download,
- }));
- db.batchUpdateCountryStats(backendId, countryUpdates);
} catch (err) {
+ trafficOk = false;
console.error(`[Collector:${backendId}] Batch write failed:`, err);
}
-
- return { domains: domains.size, rules: rules.size };
+
+ if (trafficOk) {
+ this.buffer.clear();
+ }
+
+ if (geoResults.length > 0) {
+ try {
+ const countryUpdates = geoResults
+ .filter(
+ (r): r is GeoIPResult & { geo: NonNullable<GeoIPResult["geo"]> } =>
+ r.geo !== null,
+ )
+ .map((r) => ({
+ country: r.geo.country,
+ countryName: r.geo.country_name,
+ continent: r.geo.continent,
+ upload: r.upload,
+ download: r.download,
+ }));
+ db.batchUpdateCountryStats(backendId, countryUpdates);
+ } catch (err) {
+ countryOk = false;
+ console.error(`[Collector:${backendId}] Country batch write failed:`, err);
+ }
+ }
+
+ if (countryOk) {
+ this.geoQueue = [];
+ }
+
+ return {
+ domains: domains.size,
+ rules: rules.size,
+ trafficOk,
+ countryOk,
+ hasUpdates: updates.length > 0,
+ };
}
-
+
shouldLog(): boolean {
const now = Date.now();
if (now - this.lastLogTime > 10000) {
@@ -195,7 +239,7 @@ class BatchBuffer {
}
return false;
}
-
+
incrementLogCounter(): number {
return ++this.logCounter;
}
@@ -216,12 +260,12 @@ interface TrackedConnection {
}
export function createCollector(
- db: StatsDatabase,
- url: string,
+ db: StatsDatabase,
+ url: string,
token?: string,
geoService?: GeoIPService,
onTrafficUpdate?: () => void,
- backendId?: number // Backend ID for data isolation
+ backendId?: number, // Backend ID for data isolation
) {
const id = backendId || 0;
const activeConnections = new Map<string, TrackedConnection>();
@@ -229,17 +273,26 @@ export function createCollector(
let lastBroadcastTime = 0;
const broadcastThrottleMs = 500;
let flushInterval: NodeJS.Timeout | null = null;
- const FLUSH_INTERVAL_MS = parseInt(process.env.FLUSH_INTERVAL_MS || '5000');
+ const FLUSH_INTERVAL_MS = parseInt(process.env.FLUSH_INTERVAL_MS || "30000");
// Start batch flush interval
flushInterval = setInterval(() => {
const stats = batchBuffer.flush(db, geoService, id);
+ if (stats.trafficOk) {
+ realtimeStore.clearTraffic(id);
+ }
+ if (stats.countryOk) {
+ realtimeStore.clearCountries(id);
+ }
+
if (batchBuffer.shouldLog() && (stats.domains > 0 || stats.rules > 0)) {
- console.log(`[Collector:${id}] Active: ${activeConnections.size}, Domains: ${stats.domains}, Rules: ${stats.rules}`);
+ console.log(
+ `[Collector:${id}] Active: ${activeConnections.size}, Domains: ${stats.domains}, Rules: ${stats.rules}`,
+ );
}
}, FLUSH_INTERVAL_MS);
-
+
const collector = new OpenClashCollector(id, {
url,
token,
@@ -249,44 +302,48 @@ export function createCollector(
console.warn(`[Collector:${id}] Received null/undefined data`);
return;
}
-
+
// Some backends send empty messages or keepalive packets
if (!data.connections) {
// Silently ignore - this is normal for some backends
return;
}
-
+
if (!Array.isArray(data.connections)) {
- console.warn(`[Collector:${id}] Invalid connections format: ${typeof data.connections}`);
+ console.warn(
+ `[Collector:${id}] Invalid connections format: ${typeof data.connections}`,
+ );
return;
}
-
+
const now = Date.now();
- const currentIds = new Set(data.connections.map(c => c?.id).filter(Boolean));
+ const currentIds = new Set(
+ data.connections.map((c) => c?.id).filter(Boolean),
+ );
let hasNewTraffic = false;
-
+
// Process all current connections
for (const conn of data.connections) {
// Skip invalid connection entries - be more lenient
- if (!conn || typeof conn !== 'object') {
+ if (!conn || typeof conn !== "object") {
continue;
}
-
+
// Some backends may not have all fields
if (!conn.id) {
continue;
}
-
+
// Ensure metadata exists with defaults
const metadata = conn.metadata || {};
- const domain = metadata.host || metadata.sniffHost || '';
- const ip = metadata.destinationIP || '';
- const chains = Array.isArray(conn.chains) ? conn.chains : ['DIRECT'];
- const rule = conn.rule || 'Match';
- const rulePayload = conn.rulePayload || '';
-
+ const domain = metadata.host || metadata.sniffHost || "";
+ const ip = metadata.destinationIP || "";
+ const chains = Array.isArray(conn.chains) ? conn.chains : ["DIRECT"];
+ const rule = conn.rule || "Match";
+ const rulePayload = conn.rulePayload || "";
+
const existing = activeConnections.get(conn.id);
-
+
if (!existing) {
// New connection - track it and record initial traffic
activeConnections.set(conn.id, {
@@ -301,83 +358,136 @@ export function createCollector(
totalUpload: conn.upload,
totalDownload: conn.download,
});
-
+
// Record initial traffic for new connection (add to batch buffer)
if (conn.upload > 0 || conn.download > 0) {
batchBuffer.add(id, {
domain,
ip,
- chain: chains[0] || 'DIRECT',
+ chain: chains[0] || "DIRECT",
chains,
rule,
rulePayload,
upload: conn.upload,
download: conn.download,
});
+ realtimeStore.recordTraffic(
+ id,
+ {
+ domain,
+ ip,
+ chains,
+ rule,
+ rulePayload,
+ upload: conn.upload,
+ download: conn.download,
+ },
+ 1,
+ now
+ );
// Queue GeoIP lookup
if (geoService && ip) {
- geoService.getGeoLocation(ip).then((geo) => {
- if (geo) {
- batchBuffer.addGeoResult({
- ip,
- geo,
- upload: conn.upload,
- download: conn.download,
- });
- }
- }).catch(() => {
- // Silently fail for GeoIP errors
- });
+ geoService
+ .getGeoLocation(ip)
+ .then((geo) => {
+ if (geo) {
+ batchBuffer.addGeoResult({
+ ip,
+ geo,
+ upload: conn.upload,
+ download: conn.download,
+ });
+ realtimeStore.recordCountryTraffic(
+ id,
+ geo,
+ conn.upload,
+ conn.download,
+ 1,
+ now,
+ );
+ }
+ })
+ .catch(() => {
+ // Silently fail for GeoIP errors
+ });
}
-
+
hasNewTraffic = true;
}
} else {
// Existing connection - calculate delta and add to batch
const uploadDelta = Math.max(0, conn.upload - existing.lastUpload);
- const downloadDelta = Math.max(0, conn.download - existing.lastDownload);
-
+ const downloadDelta = Math.max(
+ 0,
+ conn.download - existing.lastDownload,
+ );
+
if (uploadDelta > 0 || downloadDelta > 0) {
// Update accumulated traffic for this connection
existing.totalUpload += uploadDelta;
existing.totalDownload += downloadDelta;
-
+
// Add delta to batch buffer
batchBuffer.add(id, {
domain: existing.domain,
ip: existing.ip,
- chain: existing.chains[0] || 'DIRECT',
+ chain: existing.chains[0] || "DIRECT",
chains: existing.chains,
- rule: existing.rule || 'Match',
- rulePayload: existing.rulePayload || '',
+ rule: existing.rule || "Match",
+ rulePayload: existing.rulePayload || "",
upload: uploadDelta,
download: downloadDelta,
});
+ realtimeStore.recordTraffic(
+ id,
+ {
+ domain: existing.domain,
+ ip: existing.ip,
+ chains: existing.chains,
+ rule: existing.rule || 'Match',
+ rulePayload: existing.rulePayload || '',
+ upload: uploadDelta,
+ download: downloadDelta,
+ },
+ 1,
+ now
+ );
// Queue GeoIP lookup for delta
if (geoService && existing.ip) {
- geoService.getGeoLocation(existing.ip).then((geo) => {
- if (geo) {
- batchBuffer.addGeoResult({
- ip: existing.ip,
- geo,
- upload: uploadDelta,
- download: downloadDelta,
- });
- }
- }).catch(() => {
- // Silently fail for GeoIP errors
- });
+ geoService
+ .getGeoLocation(existing.ip)
+ .then((geo) => {
+ if (geo) {
+ batchBuffer.addGeoResult({
+ ip: existing.ip,
+ geo,
+ upload: uploadDelta,
+ download: downloadDelta,
+ });
+ realtimeStore.recordCountryTraffic(
+ id,
+ geo,
+ uploadDelta,
+ downloadDelta,
+ 1,
+ now,
+ );
+ }
+ })
+ .catch(() => {
+ // Silently fail for GeoIP errors
+ });
}
-
+
existing.lastUpload = conn.upload;
existing.lastDownload = conn.download;
hasNewTraffic = true;
}
}
}
-
+
// Find closed connections and remove them
for (const [connId, tracked] of activeConnections) {
if (!currentIds.has(connId)) {
@@ -385,18 +495,22 @@ export function createCollector(
activeConnections.delete(connId);
}
}
-
+
// Broadcast to WebSocket clients if there's new traffic (with throttling)
- if (hasNewTraffic && onTrafficUpdate && now - lastBroadcastTime > broadcastThrottleMs) {
+ if (
+ hasNewTraffic &&
+ onTrafficUpdate &&
+ now - lastBroadcastTime > broadcastThrottleMs
+ ) {
lastBroadcastTime = now;
onTrafficUpdate();
}
},
onError: (err) => {
console.error(`[Collector:${id}] Error:`, err);
- }
+ },
});
-
+
// Override disconnect to clear interval
const originalDisconnect = collector.disconnect.bind(collector);
collector.disconnect = () => {
@@ -404,10 +518,16 @@ export function createCollector(
clearInterval(flushInterval);
flushInterval = null;
// Final flush
- batchBuffer.flush(db, geoService, id);
+ const stats = batchBuffer.flush(db, geoService, id);
+ if (stats.trafficOk) {
+ realtimeStore.clearTraffic(id);
+ }
+ if (stats.countryOk) {
+ realtimeStore.clearCountries(id);
+ }
}
originalDisconnect();
};
-
+
return collector;
}
diff --git a/apps/collector/src/realtime.ts b/apps/collector/src/realtime.ts
new file mode 100644
index 0000000..69edbea
--- /dev/null
+++ b/apps/collector/src/realtime.ts
@@ -0,0 +1,544 @@
+import type {
+ CountryStats,
+ DomainStats,
+ IPStats,
+ ProxyStats,
+ StatsSummary,
+ TrafficTrendPoint,
+} from '@clashmaster/shared';
+
+type SummaryDelta = {
+ upload: number;
+ download: number;
+ connections: number;
+ lastUpdated: number;
+};
+
+type MinuteBucket = {
+ upload: number;
+ download: number;
+ lastUpdated: number;
+};
+
+type ProxyDelta = {
+ chain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+};
+
+type CountryDelta = {
+ country: string;
+ countryName: string;
+ continent: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+};
+
+type DomainDelta = {
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: Set<string>;
+ rules: Set<string>;
+ chains: Set<string>;
+};
+
+type IPDelta = {
+ ip: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ domains: Set<string>;
+ chains: Set<string>;
+};
+
+export type TrafficMeta = {
+ domain: string;
+ ip: string;
+ chains: string[];
+ rule: string;
+ rulePayload: string;
+ upload: number;
+ download: number;
+};
+
+function toMinuteKey(tsMs: number): string {
+ const iso = new Date(tsMs).toISOString();
+ return `${iso.slice(0, 16)}:00`;
+}
+
+function bucketMinuteKey(minuteKey: string, bucketMinutes: number): string {
+ if (bucketMinutes <= 1) return minuteKey;
+ const minute = parseInt(minuteKey.slice(14, 16), 10);
+ const bucketMinute = Math.floor(minute / bucketMinutes) * bucketMinutes;
+ return `${minuteKey.slice(0, 14)}${String(bucketMinute).padStart(2, '0')}:00`;
+}
+
+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 countryByBackend = new Map<number, Map<string, CountryDelta>>();
+ private maxMinutes: number;
+
+ constructor(maxMinutes = parseInt(process.env.REALTIME_MAX_MINUTES || '180', 10)) {
+ this.maxMinutes = Number.isFinite(maxMinutes) ? Math.max(30, maxMinutes) : 180;
+ }
+
+ recordTraffic(
+ backendId: number,
+ meta: TrafficMeta,
+ connections = 1,
+ timestamp = Date.now()
+ ): void {
+ if (meta.upload <= 0 && meta.download <= 0) return;
+
+ const summary = this.summaryByBackend.get(backendId) || {
+ upload: 0,
+ download: 0,
+ connections: 0,
+ lastUpdated: 0,
+ };
+ summary.upload += meta.upload;
+ summary.download += meta.download;
+ summary.connections += connections;
+ summary.lastUpdated = timestamp;
+ this.summaryByBackend.set(backendId, summary);
+
+ const minuteKey = toMinuteKey(timestamp);
+ let minuteMap = this.minuteByBackend.get(backendId);
+ if (!minuteMap) {
+ minuteMap = new Map();
+ this.minuteByBackend.set(backendId, minuteMap);
+ }
+ const bucket = minuteMap.get(minuteKey) || { upload: 0, download: 0, lastUpdated: 0 };
+ bucket.upload += meta.upload;
+ bucket.download += meta.download;
+ bucket.lastUpdated = timestamp;
+ minuteMap.set(minuteKey, bucket);
+
+ this.pruneOldBuckets(minuteMap, timestamp);
+
+ const ruleName =
+ meta.chains.length > 1
+ ? meta.chains[meta.chains.length - 1]
+ : meta.rulePayload
+ ? `${meta.rule}(${meta.rulePayload})`
+ : meta.rule;
+ const fullChain = meta.chains.join(' > ');
+ const lastSeen = new Date(timestamp).toISOString();
+
+ if (meta.domain) {
+ let domainMap = this.domainByBackend.get(backendId);
+ if (!domainMap) {
+ domainMap = new Map();
+ this.domainByBackend.set(backendId, 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 ipMap = this.ipByBackend.get(backendId);
+ if (!ipMap) {
+ ipMap = new Map();
+ this.ipByBackend.set(backendId, 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>(),
+ };
+
+ ipDelta.totalUpload += meta.upload;
+ ipDelta.totalDownload += meta.download;
+ ipDelta.totalConnections += connections;
+ ipDelta.lastSeen = lastSeen;
+ const ipDomain = meta.domain || 'unknown';
+ if (ipDomain) ipDelta.domains.add(ipDomain);
+ if (fullChain) ipDelta.chains.add(fullChain);
+ ipMap.set(meta.ip, ipDelta);
+ }
+
+ const proxyChain = meta.chains[0] || 'DIRECT';
+ let proxyMap = this.proxyByBackend.get(backendId);
+ if (!proxyMap) {
+ proxyMap = new Map();
+ this.proxyByBackend.set(backendId, proxyMap);
+ }
+
+ const proxyDelta = proxyMap.get(proxyChain) || {
+ chain: proxyChain,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ };
+
+ proxyDelta.totalUpload += meta.upload;
+ proxyDelta.totalDownload += meta.download;
+ proxyDelta.totalConnections += connections;
+ proxyDelta.lastSeen = lastSeen;
+ proxyMap.set(proxyChain, proxyDelta);
+ }
+
+ recordCountryTraffic(
+ backendId: number,
+ geo: { country: string; country_name: string; continent: string },
+ upload: number,
+ download: number,
+ connections = 1,
+ timestamp = Date.now(),
+ ): void {
+ if (upload <= 0 && download <= 0) return;
+
+ const lastSeen = new Date(timestamp).toISOString();
+ let countryMap = this.countryByBackend.get(backendId);
+ if (!countryMap) {
+ countryMap = new Map();
+ this.countryByBackend.set(backendId, countryMap);
+ }
+
+ const key = geo.country || 'Unknown';
+ const countryDelta = countryMap.get(key) || {
+ country: key,
+ countryName: geo.country_name || geo.country || 'Unknown',
+ continent: geo.continent || 'Unknown',
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ };
+
+ countryDelta.totalUpload += upload;
+ countryDelta.totalDownload += download;
+ countryDelta.totalConnections += connections;
+ countryDelta.lastSeen = lastSeen;
+ countryMap.set(key, countryDelta);
+ }
+
+ getSummaryDelta(backendId: number): SummaryDelta {
+ return this.summaryByBackend.get(backendId) || {
+ upload: 0,
+ download: 0,
+ connections: 0,
+ lastUpdated: 0,
+ };
+ }
+
+ getTodayDelta(backendId: number, nowMs = Date.now()): { upload: number; download: number } {
+ const minuteMap = this.minuteByBackend.get(backendId);
+ if (!minuteMap || minuteMap.size === 0) return { upload: 0, download: 0 };
+
+ const todayPrefix = new Date(nowMs).toISOString().slice(0, 10);
+ let upload = 0;
+ let download = 0;
+
+ for (const [minuteKey, bucket] of minuteMap) {
+ if (minuteKey.startsWith(todayPrefix)) {
+ upload += bucket.upload;
+ download += bucket.download;
+ }
+ }
+
+ return { upload, download };
+ }
+
+ applySummaryDelta<T extends { totalUpload: number; totalDownload: number; totalConnections: number }>(
+ backendId: number,
+ base: T,
+ ): T {
+ const delta = this.getSummaryDelta(backendId);
+ if (delta.upload === 0 && delta.download === 0 && delta.connections === 0) {
+ return base;
+ }
+
+ return {
+ ...base,
+ totalUpload: base.totalUpload + delta.upload,
+ totalDownload: base.totalDownload + delta.download,
+ totalConnections: base.totalConnections + delta.connections,
+ };
+ }
+
+ mergeTrend(
+ backendId: number,
+ basePoints: TrafficTrendPoint[],
+ minutes: number,
+ bucketMinutes = 1,
+ nowMs = Date.now(),
+ ): TrafficTrendPoint[] {
+ const minuteMap = this.minuteByBackend.get(backendId);
+ if (!minuteMap || minuteMap.size === 0) return basePoints;
+
+ const cutoffKey = toMinuteKey(nowMs - minutes * 60 * 1000);
+ const deltaMap = new Map<string, { upload: number; download: number }>();
+
+ for (const [minuteKey, bucket] of minuteMap) {
+ if (minuteKey < cutoffKey) continue;
+ const bucketKey = bucketMinuteKey(minuteKey, bucketMinutes);
+ const existing = deltaMap.get(bucketKey);
+ if (existing) {
+ existing.upload += bucket.upload;
+ existing.download += bucket.download;
+ } else {
+ deltaMap.set(bucketKey, { upload: bucket.upload, download: bucket.download });
+ }
+ }
+
+ if (deltaMap.size === 0) return basePoints;
+
+ const merged = new Map<string, { upload: number; download: number }>();
+ for (const point of basePoints) {
+ merged.set(point.time, { upload: point.upload, download: point.download });
+ }
+
+ for (const [time, delta] of deltaMap) {
+ const existing = merged.get(time);
+ if (existing) {
+ existing.upload += delta.upload;
+ existing.download += delta.download;
+ } else {
+ merged.set(time, { upload: delta.upload, download: delta.download });
+ }
+ }
+
+ return Array.from(merged.entries())
+ .map(([time, data]) => ({ time, upload: data.upload, download: data.download }))
+ .sort((a, b) => a.time.localeCompare(b.time));
+ }
+
+ mergeTopDomains(backendId: number, base: DomainStats[], limit: number): 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 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);
+ }
+
+ mergeTopIPs(backendId: number, base: IPStats[], limit: number): 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 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);
+ }
+
+ mergeProxyStats(backendId: number, base: ProxyStats[]): ProxyStats[] {
+ const proxyMap = this.proxyByBackend.get(backendId);
+ if (!proxyMap || proxyMap.size === 0) return base;
+
+ const merged = new Map<string, ProxyStats>();
+ for (const item of base) {
+ merged.set(item.chain, { ...item });
+ }
+
+ for (const [chain, delta] of proxyMap) {
+ const existing = merged.get(chain);
+ 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(chain, {
+ chain,
+ 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),
+ );
+ }
+
+ mergeCountryStats(backendId: number, base: CountryStats[]): CountryStats[] {
+ const countryMap = this.countryByBackend.get(backendId);
+ if (!countryMap || countryMap.size === 0) return base;
+
+ const merged = new Map<string, CountryStats>();
+ for (const item of base) {
+ merged.set(item.country, { ...item });
+ }
+
+ for (const [country, delta] of countryMap) {
+ const existing = merged.get(country);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (!existing.countryName && delta.countryName) {
+ existing.countryName = delta.countryName;
+ }
+ if (!existing.continent && delta.continent) {
+ existing.continent = delta.continent;
+ }
+ if (delta.lastSeen && (!existing.lastSeen || delta.lastSeen > existing.lastSeen)) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ } else {
+ merged.set(country, {
+ country,
+ countryName: delta.countryName,
+ continent: delta.continent,
+ 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),
+ );
+ }
+
+ clearTraffic(backendId: number): void {
+ this.summaryByBackend.delete(backendId);
+ this.minuteByBackend.delete(backendId);
+ this.domainByBackend.delete(backendId);
+ this.ipByBackend.delete(backendId);
+ this.proxyByBackend.delete(backendId);
+ }
+
+ clearCountries(backendId: number): void {
+ this.countryByBackend.delete(backendId);
+ }
+
+ clearBackend(backendId: number): void {
+ this.clearTraffic(backendId);
+ this.clearCountries(backendId);
+ }
+
+ private pruneOldBuckets(minuteMap: Map<string, MinuteBucket>, nowMs: number): void {
+ const cutoffKey = toMinuteKey(nowMs - this.maxMinutes * 60 * 1000);
+ for (const key of minuteMap.keys()) {
+ if (key < cutoffKey) {
+ minuteMap.delete(key);
+ }
+ }
+ }
+}
+
+export const realtimeStore = new RealtimeStore();
diff --git a/apps/collector/src/websocket.ts b/apps/collector/src/websocket.ts
index 14ad7a2..47c04a3 100644
--- a/apps/collector/src/websocket.ts
+++ b/apps/collector/src/websocket.ts
@@ -1,6 +1,7 @@
import { WebSocketServer as WSServer, WebSocket } from 'ws';
import type { StatsSummary } from '@clashmaster/shared';
import type { StatsDatabase } from './db.js';
+import { realtimeStore } from './realtime.js';
export interface WebSocketMessage {
type: 'stats' | 'ping' | 'pong' | 'subscribe';
@@ -99,13 +100,24 @@ export class StatsWebSocketServer {
}
const summary = this.db.getSummary(backendId);
- const topDomains = this.db.getTopDomains(backendId, 100);
- const topIPs = this.db.getTopIPs(backendId, 100);
- const proxyStats = this.db.getProxyStats(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);
- return {
+ const stats: StatsSummary = {
totalUpload: summary.totalUpload,
totalDownload: summary.totalDownload,
totalConnections: summary.totalConnections,
@@ -118,6 +130,7 @@ export class StatsWebSocketServer {
ruleStats,
hourlyStats: hourly
};
+ return realtimeStore.applySummaryDelta(backendId, stats);
}
private async sendStatsToClient(ws: WebSocket) {
diff --git a/apps/web/components/backend-config-dialog.tsx b/apps/web/components/backend-config-dialog.tsx
index abda8c3..66eef22 100644
--- a/apps/web/components/backend-config-dialog.tsx
+++ b/apps/web/components/backend-config-dialog.tsx
@@ -555,14 +555,24 @@ export function BackendConfigDialog({
const handleUpdate = async (id: number) => {
setLoading(true);
try {
- const url = buildUrl(editFormData.host, editFormData.port, editFormData.ssl);
+ const url = buildUrl(
+ editFormData.host,
+ editFormData.port,
+ editFormData.ssl,
+ );
await api.updateBackend(id, {
name: editFormData.name,
url,
token: editFormData.token || undefined,
});
setEditingId(null);
- setEditFormData({ name: "", host: "", port: "9090", ssl: false, token: "" });
+ setEditFormData({
+ name: "",
+ host: "",
+ port: "9090",
+ ssl: false,
+ token: "",
+ });
await loadBackends();
await onBackendChange?.();
} catch (error: any) {
@@ -707,7 +717,13 @@ export function BackendConfigDialog({
const cancelEdit = () => {
setEditingId(null);
- setEditFormData({ name: "", host: "", port: "9090", ssl: false, token: "" });
+ setEditFormData({
+ name: "",
+ host: "",
+ port: "9090",
+ ssl: false,
+ token: "",
+ });
};
if (!open) return null;
@@ -823,7 +839,10 @@ export function BackendConfigDialog({
<Switch
checked={editFormData.ssl}
onCheckedChange={(checked) =>
- setEditFormData({ ...editFormData, ssl: checked })
+ setEditFormData({
+ ...editFormData,
+ ssl: checked,
+ })
}
/>
<label className="text-sm">{t("useSsl")}</label>
@@ -1071,7 +1090,13 @@ export function BackendConfigDialog({
variant="ghost"
onClick={() => {
setShowAddForm(false);
- setFormData({ name: "", host: "", port: "9090", ssl: false, token: "" });
+ setFormData({
+ name: "",
+ host: "",
+ port: "9090",
+ ssl: false,
+ token: "",
+ });
}}
className="flex-shrink-0">
<X className="w-4 h-4 mr-2" />
diff --git a/apps/web/components/navigation.tsx b/apps/web/components/navigation.tsx
index 43324fd..032c74c 100644
--- a/apps/web/components/navigation.tsx
+++ b/apps/web/components/navigation.tsx
@@ -205,7 +205,7 @@ export function Navigation({
<Card className="w-full max-w-[420px]">
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="flex items-center gap-2">
- <Info className="w-5 h-5 text-primary" />
+ <Info className="w-5 h-5" />
{aboutT("title")}
</CardTitle>
<button
@@ -282,8 +282,9 @@ export function Navigation({
{aboutT("checkingUpdate")}
</span>
) : latestVersion ? (
- <span className="text-sm text-muted-foreground">
- ✓ {aboutT("upToDate")}
+ <span className="text-sm text-muted-foreground flex items-center gap-1.5">
+ <span className="font-mono tabular-nums">v{latestVersion}</span>
+ <span className="text-emerald-500">✓</span>
</span>
) : (
<Button