Skip to content

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

feat: Integrate real-time rule chain traffic data by adding a new store and merging it with historical flow data in queries.

luolei2a71da068d61
diff --git a/apps/collector/src/clickhouse-reader.ts b/apps/collector/src/clickhouse-reader.ts
index 8cc0976..f358809 100644
--- a/apps/collector/src/clickhouse-reader.ts
+++ b/apps/collector/src/clickhouse-reader.ts
@@ -615,9 +615,35 @@ ORDER BY rule ASC
rule: string,
start?: string,
end?: string,
+ realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>,
): Promise<RuleChainFlow | null> {
- const rows = await this.getRuleChainTrafficRows(backendId, start, end, rule);
- if (rows === null) return null;
+ const rawRows = await this.getRuleChainTrafficRows(backendId, start, end, rule);
+ if (rawRows === null) return null;
+ const rows = [...rawRows];
+
+ if (realtimeRows) {
+ for (const rt of realtimeRows) {
+ if (rt.rule !== rule) continue;
+ const index = rows.findIndex((r) => r.chain === rt.chain);
+ if (index >= 0) {
+ rows[index].totalUpload += rt.totalUpload;
+ rows[index].totalDownload += rt.totalDownload;
+ rows[index].totalConnections += rt.totalConnections;
+ } else {
+ rows.push({
+ rule: rt.rule,
+ chain: rt.chain,
+ totalUpload: rt.totalUpload,
+ totalDownload: rt.totalDownload,
+ totalConnections: rt.totalConnections,
+ });
+ }
+ }
+ }
+
+ if (rows.length === 0) {
+ return { nodes: [], links: [] };
+ }
const nodeMap = new Map<
string,
@@ -676,9 +702,34 @@ ORDER BY rule ASC
backendId: number,
start?: string,
end?: string,
+ realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>,
): Promise<RuleChainFlowAll | null> {
- const rows = await this.getRuleChainTrafficRows(backendId, start, end);
- if (rows === null) return null;
+ const rawRows = await this.getRuleChainTrafficRows(backendId, start, end);
+ if (rawRows === null) return null;
+ const rows = [...rawRows];
+
+ if (realtimeRows) {
+ for (const rt of realtimeRows) {
+ const index = rows.findIndex((r) => r.rule === rt.rule && r.chain === rt.chain);
+ if (index >= 0) {
+ rows[index].totalUpload += rt.totalUpload;
+ rows[index].totalDownload += rt.totalDownload;
+ rows[index].totalConnections += rt.totalConnections;
+ } else {
+ rows.push({
+ rule: rt.rule,
+ chain: rt.chain,
+ totalUpload: rt.totalUpload,
+ totalDownload: rt.totalDownload,
+ totalConnections: rt.totalConnections,
+ });
+ }
+ }
+ }
+
+ if (rows.length === 0) {
+ return { nodes: [], links: [], rulePaths: {}, maxLayer: 0 };
+ }
const nodeMap = new Map<
string,
diff --git a/apps/collector/src/database/repositories/rule.repository.ts b/apps/collector/src/database/repositories/rule.repository.ts
index 5b96ba7..061926a 100644
--- a/apps/collector/src/database/repositories/rule.repository.ts
+++ b/apps/collector/src/database/repositories/rule.repository.ts
@@ -305,6 +305,7 @@ export class RuleRepository extends BaseRepository {
getRuleChainFlow(
backendId: number, rule: string, start?: string, end?: string,
+ realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>,
): { nodes: Array<{ name: string; totalUpload: number; totalDownload: number; totalConnections: number }>; links: Array<{ source: number; target: number }> } {
const range = this.parseMinuteRange(start, end);
let rows: Array<{ chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>;
@@ -339,6 +340,25 @@ export class RuleRepository extends BaseRepository {
rows = stmt.all(backendId, rule) as typeof rows;
}
+ if (realtimeRows) {
+ for (const rt of realtimeRows) {
+ if (rt.rule !== rule) continue;
+ const index = rows.findIndex((r) => r.chain === rt.chain);
+ if (index >= 0) {
+ rows[index].totalUpload += rt.totalUpload;
+ rows[index].totalDownload += rt.totalDownload;
+ rows[index].totalConnections += rt.totalConnections;
+ } else {
+ rows.push({
+ chain: rt.chain,
+ totalUpload: rt.totalUpload,
+ totalDownload: rt.totalDownload,
+ totalConnections: rt.totalConnections,
+ });
+ }
+ }
+ }
+
const nodeMap = new Map<string, { name: string; totalUpload: number; totalDownload: number; totalConnections: number }>();
const linkSet = new Set<string>();
@@ -379,6 +399,7 @@ export class RuleRepository extends BaseRepository {
getAllRuleChainFlows(
backendId: number, start?: string, end?: string,
+ realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>,
): {
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[] }>;
@@ -412,6 +433,25 @@ export class RuleRepository extends BaseRepository {
rows = stmt.all(backendId) as typeof rows;
}
+ if (realtimeRows) {
+ for (const rt of realtimeRows) {
+ const index = rows.findIndex((r) => r.rule === rt.rule && r.chain === rt.chain);
+ if (index >= 0) {
+ rows[index].totalUpload += rt.totalUpload;
+ rows[index].totalDownload += rt.totalDownload;
+ rows[index].totalConnections += rt.totalConnections;
+ } else {
+ rows.push({
+ rule: rt.rule,
+ chain: rt.chain,
+ totalUpload: rt.totalUpload,
+ totalDownload: rt.totalDownload,
+ totalConnections: rt.totalConnections,
+ });
+ }
+ }
+ }
+
const nodeMap = new Map<string, {
totalUpload: number; totalDownload: number; totalConnections: number;
rules: Set<string>; layer: number;
diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.ts
index 5b76e78..22a5d4e 100644
--- a/apps/collector/src/db.ts
+++ b/apps/collector/src/db.ts
@@ -748,8 +748,8 @@ export class StatsDatabase {
}
getRuleIPProxyStats(backendId: number, rule: string, ip: string, start?: string, end?: string) { return this.repos.rule.getRuleIPProxyStats(backendId, rule, ip, start, end); }
getRuleIPDomainDetails(backendId: number, rule: string, ip: string, start?: string, end?: string, limit?: number) { return this.repos.rule.getRuleIPDomainDetails(backendId, rule, ip, start, end, limit); }
- getRuleChainFlow(backendId: number, rule: string, start?: string, end?: string) { return this.repos.rule.getRuleChainFlow(backendId, rule, start, end); }
- getAllRuleChainFlows(backendId: number, start?: string, end?: string) { return this.repos.rule.getAllRuleChainFlows(backendId, start, end); }
+ getRuleChainFlow(backendId: number, rule: string, start?: string, end?: string, realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>) { return this.repos.rule.getRuleChainFlow(backendId, rule, start, end, realtimeRows); }
+ getAllRuleChainFlows(backendId: number, start?: string, end?: string, realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>) { return this.repos.rule.getAllRuleChainFlows(backendId, start, end, realtimeRows); }
// ==================== Private helpers (kept for getSummary) ====================
private toMinuteKey(date: Date): string {
diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.ts
index 9abf250..77cf60d 100644
--- a/apps/collector/src/index.ts
+++ b/apps/collector/src/index.ts
@@ -23,6 +23,7 @@ let wsServer: StatsWebSocketServer;
import { APIServer } from './app.js';
import { GeoIPService } from './geo-service.js';
+import { StatsService } from './modules/stats/index.js';
import {
ensureClickHouseReady,
ensureClickHouseSchema,
@@ -67,7 +68,8 @@ async function main() {
// Initialize WebSocket server for real-time updates
console.log('[Main] Starting WebSocket server on port', COLLECTOR_WS_PORT);
- wsServer = new StatsWebSocketServer(COLLECTOR_WS_PORT, db);
+ const statsService = new StatsService(db, realtimeStore);
+ wsServer = new StatsWebSocketServer(COLLECTOR_WS_PORT, db, statsService);
wsServer.start();
// Initialize policy sync service
diff --git a/apps/collector/src/modules/backend/backend.service.ts b/apps/collector/src/modules/backend/backend.service.ts
index 05c38d6..9d36144 100644
--- a/apps/collector/src/modules/backend/backend.service.ts
+++ b/apps/collector/src/modules/backend/backend.service.ts
@@ -19,6 +19,7 @@ import type {
} from './backend.types.js';
import { isAgentBackendUrl } from '@neko-master/shared';
import { loadClickHouseConfig, runClickHouseQuery } from '../../clickhouse.js';
+import type { ClickHouseConfig } from '../../clickhouse.js';
import type { AuthService } from '../auth/auth.service.js';
@@ -359,21 +360,61 @@ export class BackendService {
return { message: 'Backend data cleared successfully' };
}
+ private getClickHouseBaseTables(): readonly string[] {
+ return ['traffic_minute', 'traffic_agg', 'traffic_detail', 'country_minute'] as const;
+ }
+
+ private async deleteClickHouseBackendRows(
+ config: ClickHouseConfig,
+ backendId: number,
+ ): Promise<void> {
+ for (const table of this.getClickHouseBaseTables()) {
+ await runClickHouseQuery(
+ config,
+ `ALTER TABLE ${config.database}.${table} DELETE WHERE backend_id = ${backendId} SETTINGS mutations_sync = 2`,
+ );
+ }
+ }
+
+ private scheduleClickHouseBackendDeleteRetry(
+ config: ClickHouseConfig,
+ backendId: number,
+ ): void {
+ // Buffer tables flush asynchronously (max_time defaults to 60s).
+ // Run one delayed cleanup pass to remove late-flushed rows for this backend.
+ const delayMs = Math.max(
+ 30_000,
+ Number.parseInt(process.env.CH_BACKEND_CLEAR_RETRY_DELAY_MS || '70000', 10) || 70_000,
+ );
+ const timer = setTimeout(() => {
+ void this.deleteClickHouseBackendRows(config, backendId)
+ .then(() => {
+ console.info(
+ `[BackendService] Completed delayed ClickHouse cleanup for backend ${backendId}`,
+ );
+ })
+ .catch((error: unknown) => {
+ const message = error instanceof Error ? error.message : String(error);
+ console.warn(
+ `[BackendService] Delayed ClickHouse cleanup failed for backend ${backendId}: ${message}`,
+ );
+ });
+ }, delayMs);
+ timer.unref?.();
+ }
+
private async clearClickHouseBackendData(backendId: number): Promise<void> {
const config = loadClickHouseConfig();
+ console.info(`[BackendService] clearClickHouseBackendData called for backend ${backendId}, CH_ENABLED=${config.enabled}, host=${config.host}:${config.port}`);
if (!config.enabled) {
+ console.info('[BackendService] ClickHouse not enabled, skipping clear');
return;
}
try {
- await runClickHouseQuery(
- config,
- `ALTER TABLE ${config.database}.traffic_minute DELETE WHERE backend_id = ${backendId} SETTINGS mutations_sync = 2`,
- );
- await runClickHouseQuery(
- config,
- `ALTER TABLE ${config.database}.country_minute DELETE WHERE backend_id = ${backendId} SETTINGS mutations_sync = 2`,
- );
+ // Do not drop global buffer tables here: that can lose writes for other backends.
+ await this.deleteClickHouseBackendRows(config, backendId);
+ this.scheduleClickHouseBackendDeleteRetry(config, backendId);
console.info(`[BackendService] Cleared ClickHouse stats for backend ${backendId}`);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
diff --git a/apps/collector/src/modules/config/config.controller.ts b/apps/collector/src/modules/config/config.controller.ts
index 0210840..8b60a71 100644
--- a/apps/collector/src/modules/config/config.controller.ts
+++ b/apps/collector/src/modules/config/config.controller.ts
@@ -69,15 +69,36 @@ async function cleanupClickHouseData(
if (!chConfig.enabled) return;
const database = chConfig.database.replace(/'/g, "''");
- const tables = ["traffic_minute", "country_minute"] as const;
+ const baseTables = ["traffic_minute", "traffic_agg", "traffic_detail", "country_minute"] as const;
+ const bufferDefs = [
+ { name: "traffic_agg_buffer", base: "traffic_agg" },
+ { name: "traffic_detail_buffer", base: "traffic_detail" },
+ { name: "country_buffer", base: "country_minute" },
+ ];
if (days === 0 && backendId === undefined) {
- for (const table of tables) {
+ // Full wipe: DROP buffers → TRUNCATE base → recreate buffers
+ for (const buf of bufferDefs) {
+ try { await runClickHouseQuery(chConfig, `DROP TABLE IF EXISTS ${database}.${buf.name}`); } catch { /* ignore */ }
+ }
+ for (const table of baseTables) {
await runClickHouseQuery(chConfig, `TRUNCATE TABLE ${database}.${table}`);
}
+ for (const buf of bufferDefs) {
+ try {
+ await runClickHouseQuery(
+ chConfig,
+ `CREATE TABLE IF NOT EXISTS ${database}.${buf.name} AS ${database}.${buf.base}
+ENGINE = Buffer('${database}', '${buf.base}', 4, 10, 60, 100, 10000, 10000, 1000000)`,
+ );
+ } catch { /* ignore */ }
+ }
return;
}
+ // Partial cleanup: delete matching rows from base tables only.
+ // Avoid dropping global buffer tables here, which can affect active writers
+ // from other backends.
const conditions: string[] = [];
if (backendId !== undefined) {
conditions.push(`backend_id = ${backendId}`);
@@ -92,7 +113,7 @@ async function cleanupClickHouseData(
}
const whereClause = conditions.join(" AND ");
- for (const table of tables) {
+ for (const table of baseTables) {
await runClickHouseQuery(
chConfig,
`ALTER TABLE ${database}.${table} DELETE WHERE ${whereClause} SETTINGS mutations_sync = 2`,
diff --git a/apps/collector/src/modules/realtime/realtime.store.ts b/apps/collector/src/modules/realtime/realtime.store.ts
index e2967b7..d881911 100644
--- a/apps/collector/src/modules/realtime/realtime.store.ts
+++ b/apps/collector/src/modules/realtime/realtime.store.ts
@@ -23,6 +23,7 @@ export class RealtimeStore {
public deviceDomainByBackend = new Map<number, Map<string, Map<string, DomainDelta>>>();
public deviceIPByBackend = new Map<number, Map<string, Map<string, IPDelta>>>();
public ruleByBackend = new Map<number, Map<string, RuleDelta>>();
+ public ruleChainByBackend = new Map<number, Map<string, { rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number; lastSeen: string }>>();
public countryByBackend = new Map<number, Map<string, CountryDelta>>();
private maxMinutes: number;
@@ -287,6 +288,30 @@ export class RealtimeStore {
ruleDelta.totalConnections += connections;
ruleDelta.lastSeen = lastSeen;
ruleMap.set(ruleName, ruleDelta);
+
+ // 8. Rule Chain
+ if (ruleName && fullChain) {
+ let ruleChainMap = this.ruleChainByBackend.get(backendId);
+ if (!ruleChainMap) {
+ ruleChainMap = new Map();
+ this.ruleChainByBackend.set(backendId, ruleChainMap);
+ }
+
+ const rcKey = `${ruleName}::${fullChain}`;
+ const rcDelta = ruleChainMap.get(rcKey) || {
+ rule: ruleName,
+ chain: fullChain,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ };
+ rcDelta.totalUpload += meta.upload;
+ rcDelta.totalDownload += meta.download;
+ rcDelta.totalConnections += connections;
+ rcDelta.lastSeen = lastSeen;
+ ruleChainMap.set(rcKey, rcDelta);
+ }
}
recordCountryTraffic(
@@ -324,6 +349,12 @@ export class RealtimeStore {
countryMap.set(key, countryDelta);
}
+ getRuleChainRows(backendId: number): Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }> {
+ const ruleChainMap = this.ruleChainByBackend.get(backendId);
+ if (!ruleChainMap) return [];
+ return Array.from(ruleChainMap.values()).map(r => ({ ...r }));
+ }
+
getSummaryDelta(backendId: number): SummaryDelta {
return this.summaryByBackend.get(backendId) || {
upload: 0,
diff --git a/apps/collector/src/modules/stats/stats.service.ts b/apps/collector/src/modules/stats/stats.service.ts
index a716ee4..668f1c5 100644
--- a/apps/collector/src/modules/stats/stats.service.ts
+++ b/apps/collector/src/modules/stats/stats.service.ts
@@ -1081,7 +1081,8 @@ export class StatsService {
* Get rule chain flow for a specific rule
*/
getRuleChainFlow(backendId: number, rule: string, timeRange: TimeRange): any {
- return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end);
+ const realtimeRows = this.shouldIncludeRealtime(timeRange) ? this.realtimeStore.getRuleChainRows(backendId) : undefined;
+ return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end, realtimeRows);
}
async getRuleChainFlowWithRouting(
@@ -1090,12 +1091,15 @@ export class StatsService {
timeRange: TimeRange,
): Promise<any> {
const shouldUseCH = this.shouldUseClickHouseForOptionalRange(timeRange);
+ const realtimeRows = this.shouldIncludeRealtime(timeRange) ? this.realtimeStore.getRuleChainRows(backendId) : undefined;
+
if (shouldUseCH) {
const ch = await this.clickHouseReader.getRuleChainFlow(
backendId,
rule,
timeRange.start,
timeRange.end,
+ realtimeRows,
);
if (ch) {
this.recordRoute('rules.chain-flow', 'clickhouse');
@@ -1105,14 +1109,15 @@ export class StatsService {
this.failIfStrictFallback('rules.chain-flow');
this.recordRoute('rules.chain-flow', 'sqlite');
- return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end);
+ return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end, realtimeRows);
}
/**
* Get all rule chain flows merged into unified DAG
*/
getAllRuleChainFlows(backendId: number, timeRange: TimeRange): any {
- return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end);
+ const realtimeRows = this.shouldIncludeRealtime(timeRange) ? this.realtimeStore.getRuleChainRows(backendId) : undefined;
+ return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end, realtimeRows);
}
async getAllRuleChainFlowsWithRouting(
@@ -1120,11 +1125,14 @@ export class StatsService {
timeRange: TimeRange,
): Promise<any> {
const shouldUseCH = this.shouldUseClickHouseForOptionalRange(timeRange);
+ const realtimeRows = this.shouldIncludeRealtime(timeRange) ? this.realtimeStore.getRuleChainRows(backendId) : undefined;
+
if (shouldUseCH) {
const ch = await this.clickHouseReader.getAllRuleChainFlows(
backendId,
timeRange.start,
timeRange.end,
+ realtimeRows,
);
if (ch) {
this.recordRoute('rules.chain-flow-all', 'clickhouse');
@@ -1134,7 +1142,7 @@ export class StatsService {
this.failIfStrictFallback('rules.chain-flow-all');
this.recordRoute('rules.chain-flow-all', 'sqlite');
- return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end);
+ return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end, realtimeRows);
}
/**
diff --git a/apps/collector/src/realtime.ts b/apps/collector/src/realtime.ts
index 791f203..f4d1199 100644
--- a/apps/collector/src/realtime.ts
+++ b/apps/collector/src/realtime.ts
@@ -216,12 +216,14 @@ export class RealtimeStore {
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 ruleChainByBackend = new Map<number, Map<string, { rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number; lastSeen: string }>>();
private countryByBackend = new Map<number, Map<string, CountryDelta>>();
private maxMinutes: number;
// Memory bounds: max entries per map before eviction of smallest-traffic entries
private static readonly MAX_DOMAIN_ENTRIES = 50_000;
private static readonly MAX_IP_ENTRIES = 50_000;
+ private static readonly MAX_RULE_CHAIN_ENTRIES = 50_000;
private static readonly MAX_DEVICE_DETAIL_ENTRIES = 10_000;
constructor(maxMinutes = parseInt(process.env.REALTIME_MAX_MINUTES || '180', 10)) {
@@ -456,6 +458,29 @@ export class RealtimeStore {
ruleDelta.totalConnections += connections;
ruleDelta.lastSeen = lastSeen;
ruleMap.set(ruleName, ruleDelta);
+
+ if (ruleName && fullChain) {
+ let ruleChainMap = this.ruleChainByBackend.get(backendId);
+ if (!ruleChainMap) {
+ ruleChainMap = new Map();
+ this.ruleChainByBackend.set(backendId, ruleChainMap);
+ }
+
+ const rcKey = `${ruleName}::${fullChain}`;
+ const rcDelta = ruleChainMap.get(rcKey) || {
+ rule: ruleName,
+ chain: fullChain,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ };
+ rcDelta.totalUpload += meta.upload;
+ rcDelta.totalDownload += meta.download;
+ rcDelta.totalConnections += connections;
+ rcDelta.lastSeen = lastSeen;
+ ruleChainMap.set(rcKey, rcDelta);
+ }
}
recordCountryTraffic(
@@ -493,6 +518,12 @@ export class RealtimeStore {
countryMap.set(key, countryDelta);
}
+ getRuleChainRows(backendId: number): Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }> {
+ const ruleChainMap = this.ruleChainByBackend.get(backendId);
+ if (!ruleChainMap) return [];
+ return Array.from(ruleChainMap.values()).map(r => ({ ...r }));
+ }
+
getSummaryDelta(backendId: number): SummaryDelta {
return this.summaryByBackend.get(backendId) || {
upload: 0,
@@ -1291,6 +1322,7 @@ export class RealtimeStore {
this.deviceDomainByBackend.delete(backendId);
this.deviceIPByBackend.delete(backendId);
this.ruleByBackend.delete(backendId);
+ this.ruleChainByBackend.delete(backendId);
}
clearCountries(backendId: number): void {
@@ -1344,6 +1376,11 @@ export class RealtimeStore {
const ipMap = this.ipByBackend.get(backendId);
if (ipMap) this.evictIfNeeded(ipMap, RealtimeStore.MAX_IP_ENTRIES);
+ const ruleChainMap = this.ruleChainByBackend.get(backendId);
+ if (ruleChainMap) {
+ this.evictIfNeeded(ruleChainMap, RealtimeStore.MAX_RULE_CHAIN_ENTRIES);
+ }
+
// Device detail maps (per source IP × domain/IP) can be deeply nested
const deviceDomainMap = this.deviceDomainByBackend.get(backendId);
if (deviceDomainMap) {
diff --git a/apps/collector/src/websocket.ts b/apps/collector/src/websocket.ts
index 21144ab..afaa915 100644
--- a/apps/collector/src/websocket.ts
+++ b/apps/collector/src/websocket.ts
@@ -1,7 +1,7 @@
import { WebSocketServer as WSServer, WebSocket } from 'ws';
import type { StatsSummary, DomainStats, IPStats, ProxyStats, CountryStats, DeviceStats, RuleStats, HourlyStats } from '@neko-master/shared';
import type { StatsDatabase } from './db.js';
-import { realtimeStore } from './realtime.js';
+import type { StatsService } from './modules/stats/stats.service.js';
import { AuthService } from './modules/auth/auth.service.js';
import { IncomingMessage } from 'http';
import { URL } from 'url';
@@ -100,6 +100,7 @@ interface ClientInfo {
export class StatsWebSocketServer {
private wss: WSServer | null = null;
private db: StatsDatabase;
+ private statsService: StatsService;
private authService: AuthService;
private clients: Map<WebSocket, ClientInfo> = new Map();
private port: number;
@@ -140,9 +141,10 @@ export class StatsWebSocketServer {
broadcastSentClients: 0,
};
- constructor(port: number, db: StatsDatabase) {
+ constructor(port: number, db: StatsDatabase, statsService: StatsService) {
this.port = port;
this.db = db;
+ this.statsService = statsService;
this.authService = new AuthService(db);
}
@@ -777,7 +779,7 @@ export class StatsWebSocketServer {
return activeBackend?.id ?? null;
}
- private getStatsForBackend(
+ private async getStatsForBackend(
backendId: number | null,
range: ClientRange,
trend: ClientTrend,
@@ -787,23 +789,14 @@ export class StatsWebSocketServer {
includeRuleChainFlow: boolean,
domainsPage: ClientDomainsPage,
ipsPage: ClientIPsPage,
- ): StatsSummary | null {
+ wantsFullSummary = true,
+ ): Promise<StatsSummary | null> {
this.wsMetrics.getStatsCalls += 1;
const resolvedBackendId = this.resolveBackendId(backendId);
if (resolvedBackendId === null) {
return null;
}
- const includeRealtime = this.shouldIncludeRealtime(range);
- const wantsFullSummary =
- !trend &&
- !deviceDetail &&
- !proxyDetail &&
- !ruleDetail &&
- !includeRuleChainFlow &&
- !domainsPage &&
- !ipsPage;
-
if (wantsFullSummary) {
this.wsMetrics.fullSummaryCalls += 1;
}
@@ -816,29 +809,10 @@ export class StatsWebSocketServer {
}
const cacheTTL = this.getBaseSummaryCacheTTL(range);
-
- const summary = wantsFullSummary
- ? (() => {
- const baseCacheKey = `${resolvedBackendId}|${range.start || ''}|${range.end || ''}`;
- const cached = this.baseSummaryCache.get(baseCacheKey);
- if (cached && Date.now() - cached.ts < cacheTTL) {
- return cached.summary;
- }
- const result = this.db.getSummary(resolvedBackendId, range.start, range.end);
- return result;
- })()
- : {
- totalUpload: 0,
- totalDownload: 0,
- totalConnections: 0,
- uniqueDomains: 0,
- uniqueIPs: 0,
- };
-
- // Use cached base summary data to avoid repeated expensive DB queries
const baseCacheKey = `${resolvedBackendId}|${range.start || ''}|${range.end || ''}`;
- const baseCached = this.baseSummaryCache.get(baseCacheKey);
+ let baseCached = this.baseSummaryCache.get(baseCacheKey);
const baseCacheValid = baseCached && Date.now() - baseCached.ts < cacheTTL;
+
if (wantsFullSummary) {
if (baseCacheValid) {
this.wsMetrics.baseCacheHit += 1;
@@ -847,77 +821,43 @@ export class StatsWebSocketServer {
}
}
- const dbTopDomains = wantsFullSummary
- ? (baseCacheValid ? baseCached!.topDomains : this.db.getTopDomainsLight(resolvedBackendId, 100, range.start, range.end))
- : undefined;
- const topDomains = wantsFullSummary && dbTopDomains
- ? includeRealtime
- ? realtimeStore.mergeTopDomains(resolvedBackendId, dbTopDomains, 100)
- : dbTopDomains
- : [];
-
- const dbTopIPs = wantsFullSummary
- ? (baseCacheValid ? baseCached!.topIPs : this.db.getTopIPsLight(resolvedBackendId, 100, range.start, range.end))
- : undefined;
- const topIPs = wantsFullSummary && dbTopIPs
- ? includeRealtime
- ? realtimeStore.mergeTopIPs(resolvedBackendId, dbTopIPs, 100)
- : dbTopIPs
- : [];
-
- const dbProxyStats = wantsFullSummary
- ? (baseCacheValid ? baseCached!.proxyStats : this.db.getProxyStats(resolvedBackendId, range.start, range.end))
- : undefined;
- const proxyStats = wantsFullSummary && dbProxyStats
- ? includeRealtime
- ? realtimeStore.mergeProxyStats(resolvedBackendId, dbProxyStats)
- : dbProxyStats
- : [];
-
- const dbCountryStats = wantsFullSummary
- ? (baseCacheValid ? baseCached!.countryStats : this.db.getCountryStats(resolvedBackendId, 50, range.start, range.end))
- : undefined;
- const countryStats = wantsFullSummary && dbCountryStats
- ? includeRealtime
- ? realtimeStore.mergeCountryStats(resolvedBackendId, dbCountryStats)
- : dbCountryStats
- : undefined;
-
- const dbDeviceStats = wantsFullSummary
- ? (baseCacheValid ? baseCached!.deviceStats : this.db.getDevices(resolvedBackendId, 50, range.start, range.end))
- : undefined;
- const deviceStats = wantsFullSummary && dbDeviceStats
- ? includeRealtime
- ? realtimeStore.mergeDeviceStats(resolvedBackendId, dbDeviceStats, 50)
- : dbDeviceStats
- : undefined;
-
- const dbRuleStats = wantsFullSummary
- ? (baseCacheValid ? baseCached!.ruleStats : this.db.getRuleStats(resolvedBackendId, range.start, range.end))
- : undefined;
- const ruleStats = wantsFullSummary && dbRuleStats
- ? includeRealtime
- ? realtimeStore.mergeRuleStats(resolvedBackendId, dbRuleStats)
- : dbRuleStats
- : undefined;
- const hourlyStats = wantsFullSummary
- ? (baseCacheValid ? baseCached!.hourlyStats : this.db.getHourlyStats(resolvedBackendId, 24, range.start, range.end))
- : [];
-
- // Update base summary cache for future broadcasts
+ const now = new Date();
+ // Default to the year 2000 for "all time" start, and 24 hours into the future for "all time" end
+ // This allows ClickHouse to perform a full-range aggregation without failing over to SQLite
+ const defaultStart = new Date('2000-01-01T00:00:00.000Z').toISOString();
+ const defaultEnd = new Date(now.getTime() + 86400000).toISOString();
+ const timeRange = {
+ start: range.start || defaultStart,
+ end: range.end || defaultEnd,
+ active: true
+ };
+
if (wantsFullSummary && !baseCacheValid) {
- this.baseSummaryCache.set(baseCacheKey, {
- summary,
- topDomains: dbTopDomains!,
- topIPs: dbTopIPs!,
- proxyStats: dbProxyStats!,
- countryStats: dbCountryStats!,
- deviceStats: dbDeviceStats!,
- ruleStats: dbRuleStats!,
- hourlyStats,
+ const [summaryRes, countryStats, deviceStats] = await Promise.all([
+ this.statsService.getSummaryWithRouting(resolvedBackendId, timeRange),
+ this.statsService.getCountryStatsWithRouting(resolvedBackendId, timeRange, 50),
+ this.statsService.getDeviceStatsWithRouting(resolvedBackendId, timeRange, 50),
+ ]);
+
+ baseCached = {
+ summary: {
+ totalConnections: summaryRes.totalConnections,
+ totalUpload: summaryRes.totalUpload,
+ totalDownload: summaryRes.totalDownload,
+ uniqueDomains: summaryRes.totalDomains,
+ uniqueIPs: summaryRes.totalIPs,
+ },
+ topDomains: summaryRes.topDomains,
+ topIPs: summaryRes.topIPs,
+ proxyStats: summaryRes.proxyStats,
+ ruleStats: summaryRes.ruleStats || [],
+ hourlyStats: summaryRes.hourlyStats,
+ countryStats,
+ deviceStats,
ts: Date.now(),
- });
- // Evict stale entries
+ };
+
+ this.baseSummaryCache.set(baseCacheKey, baseCached);
for (const [key, val] of this.baseSummaryCache) {
if (Date.now() - val.ts > cacheTTL * 2) {
this.baseSummaryCache.delete(key);
@@ -925,178 +865,53 @@ export class StatsWebSocketServer {
}
}
- 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 = {
+ const summary = wantsFullSummary ? baseCached!.summary : { totalUpload: 0, totalDownload: 0, totalConnections: 0, uniqueDomains: 0, uniqueIPs: 0 };
+ const topDomains = wantsFullSummary ? baseCached!.topDomains : [];
+ const topIPs = wantsFullSummary ? baseCached!.topIPs : [];
+ const proxyStats = wantsFullSummary ? baseCached!.proxyStats : [];
+ const countryStats = wantsFullSummary ? baseCached!.countryStats : undefined;
+ const deviceStats = wantsFullSummary ? baseCached!.deviceStats : undefined;
+ const ruleStats = wantsFullSummary ? baseCached!.ruleStats : undefined;
+ const hourlyStats = wantsFullSummary ? baseCached!.hourlyStats : [];
+
+ const fetches: Promise<void>[] = [];
+
+ let trendStats: any;
+ if (trend) fetches.push(this.statsService.getTrafficTrendAggregatedWithRouting(resolvedBackendId, timeRange, trend.minutes, trend.bucketMinutes).then((r: any) => { trendStats = r; }));
+
+ let deviceDomains: any;
+ if (deviceDetail) fetches.push(this.statsService.getDeviceDomainsWithRouting(resolvedBackendId, deviceDetail.sourceIP, timeRange, deviceDetail.limit).then((r: any) => { deviceDomains = r; }));
+
+ let deviceIPs: any;
+ if (deviceDetail) fetches.push(this.statsService.getDeviceIPsWithRouting(resolvedBackendId, deviceDetail.sourceIP, timeRange, deviceDetail.limit).then((r: any) => { deviceIPs = r; }));
+
+ let proxyDomains: any;
+ if (proxyDetail) fetches.push(this.statsService.getProxyDomainsWithRouting(resolvedBackendId, proxyDetail.chain, timeRange, proxyDetail.limit).then((r: any) => { proxyDomains = r; }));
+
+ let proxyIPs: any;
+ if (proxyDetail) fetches.push(this.statsService.getProxyIPsWithRouting(resolvedBackendId, proxyDetail.chain, timeRange, proxyDetail.limit).then((r: any) => { proxyIPs = r; }));
+
+ let ruleDomains: any;
+ if (ruleDetail) fetches.push(this.statsService.getRuleDomainsWithRouting(resolvedBackendId, ruleDetail.rule, timeRange, ruleDetail.limit).then((r: any) => { ruleDomains = r; }));
+
+ let ruleIPs: any;
+ if (ruleDetail) fetches.push(this.statsService.getRuleIPsWithRouting(resolvedBackendId, ruleDetail.rule, timeRange, ruleDetail.limit).then((r: any) => { ruleIPs = r; }));
+
+ let ruleChainFlowAll: any;
+ if (includeRuleChainFlow) fetches.push(this.statsService.getAllRuleChainFlowsWithRouting(resolvedBackendId, timeRange).then((r: any) => { ruleChainFlowAll = r; }));
+
+ let domainsPageData: any;
+ if (domainsPage) fetches.push(this.statsService.getDomainStatsPaginatedWithRouting(resolvedBackendId, timeRange, { offset: domainsPage.offset, limit: domainsPage.limit, sortBy: domainsPage.sortBy, sortOrder: domainsPage.sortOrder, search: domainsPage.search }).then((r: any) => { domainsPageData = r; }));
+
+ let ipsPageData: any;
+ if (ipsPage) fetches.push(this.statsService.getIPStatsPaginatedWithRouting(resolvedBackendId, timeRange, { offset: ipsPage.offset, limit: ipsPage.limit, sortBy: ipsPage.sortBy, sortOrder: ipsPage.sortOrder, search: ipsPage.search }).then((r: any) => { ipsPageData = r; }));
+
+ await Promise.all(fetches);
+
+ // Trend data returned by statsService already includes realtime merge when applicable.
+ const mergedTrendStats = trendStats;
+
+ return {
totalUpload: summary.totalUpload,
totalDownload: summary.totalDownload,
totalConnections: summary.totalConnections,
@@ -1127,20 +942,16 @@ export class StatsWebSocketServer {
ruleStats,
hourlyStats,
};
-
- return includeRealtime && wantsFullSummary
- ? realtimeStore.applySummaryDelta(resolvedBackendId, baseStats)
- : baseStats;
}
- private sendStatsToClient(ws: WebSocket) {
+ private async sendStatsToClient(ws: WebSocket) {
if (ws.readyState !== WebSocket.OPEN) return;
const clientInfo = this.clients.get(ws);
if (!clientInfo) return;
try {
- const stats = this.getStatsForBackend(
+ const stats = await this.getStatsForBackend(
clientInfo.backendId,
clientInfo.range,
clientInfo.trend,
@@ -1150,10 +961,10 @@ export class StatsWebSocketServer {
clientInfo.includeRuleChainFlow,
clientInfo.domainsPage,
clientInfo.ipsPage,
+ true,
);
- if (!stats) {
- return;
- }
+
+ if (!stats) return;
const message: WebSocketMessage = {
type: 'stats',
@@ -1170,6 +981,10 @@ export class StatsWebSocketServer {
// Broadcast stats snapshot to subscribed clients.
broadcastStats(changedBackendId?: number, force = false) {
+ void this.broadcastStatsInternal(changedBackendId, force);
+ }
+
+ private async broadcastStatsInternal(changedBackendId?: number, force = false): Promise<void> {
const now = Date.now();
if (!force && now - this.lastBroadcastTime < this.broadcastThrottleMs) {
@@ -1182,8 +997,8 @@ export class StatsWebSocketServer {
this.wsMetrics.broadcastCalls += 1;
let sentCount = 0;
- // Cache serialized JSON per unique query combo to avoid repeated JSON.stringify
- const jsonCache = new Map<string, string | null>();
+ // Cache serialized JSON per unique query combo to avoid repeated stats fetch + JSON.stringify
+ const jsonCache = new Map<string, Promise<string | null>>();
const ts = new Date().toISOString();
for (const [ws, clientInfo] of this.clients) {
@@ -1225,25 +1040,28 @@ export class StatsWebSocketServer {
: '';
const cacheKey = `${resolvedBackendId}|${clientInfo.range.start || ''}|${clientInfo.range.end || ''}|${trendKey}|${deviceDetailKey}|${proxyDetailKey}|${ruleDetailKey}|${ruleChainFlowKey}|${domainsPageKey}|${ipsPageKey}`;
if (!jsonCache.has(cacheKey)) {
- const stats = this.getStatsForBackend(
- resolvedBackendId,
- clientInfo.range,
- clientInfo.trend,
- clientInfo.deviceDetail,
- clientInfo.proxyDetail,
- clientInfo.ruleDetail,
- clientInfo.includeRuleChainFlow,
- clientInfo.domainsPage,
- clientInfo.ipsPage,
- );
- // Serialize once per unique query; reuse for all clients with same params
jsonCache.set(
cacheKey,
- stats ? JSON.stringify({ type: 'stats', data: stats, timestamp: ts }) : null,
+ this.getStatsForBackend(
+ resolvedBackendId,
+ clientInfo.range,
+ clientInfo.trend,
+ clientInfo.deviceDetail,
+ clientInfo.proxyDetail,
+ clientInfo.ruleDetail,
+ clientInfo.includeRuleChainFlow,
+ clientInfo.domainsPage,
+ clientInfo.ipsPage,
+ ).then((stats) => (
+ stats ? JSON.stringify({ type: 'stats', data: stats, timestamp: ts }) : null
+ )).catch((err) => {
+ console.error('[WebSocket] Error building broadcast payload:', err);
+ return null;
+ }),
);
}
- const json = jsonCache.get(cacheKey);
+ const json = await jsonCache.get(cacheKey);
if (!json) continue;
ws.send(json);