Skip to content

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

feat: Implement ClickHouse storage stats, enhance `formatBytes` utility, and introduce backend data clear event.

luoleib0d8699bbf6b
diff --git a/apps/collector/src/app.ts b/apps/collector/src/app.ts
index df9f7f9..44010a4 100644
--- a/apps/collector/src/app.ts
+++ b/apps/collector/src/app.ts
@@ -38,6 +38,7 @@ export interface AppOptions {
policySyncService?: SurgePolicySyncService;
autoListen?: boolean;
onTrafficIngested?: (backendId: number) => void;
+ onBackendDataCleared?: (backendId: number) => void;
}
type AgentTrafficUpdatePayload = {
@@ -81,6 +82,7 @@ export async function createApp(options: AppOptions) {
policySyncService,
autoListen = true,
onTrafficIngested,
+ onBackendDataCleared,
} = options;
// Create Fastify instance
@@ -110,7 +112,12 @@ export async function createApp(options: AppOptions) {
// Create services
const authService = new AuthService(db);
- const backendService = new BackendService(db, realtimeStore, authService);
+ const backendService = new BackendService(
+ db,
+ realtimeStore,
+ authService,
+ onBackendDataCleared,
+ );
const statsService = new StatsService(db, realtimeStore);
// Decorate Fastify instance with services
@@ -911,6 +918,7 @@ export class APIServer {
private port: number;
private policySyncService?: SurgePolicySyncService;
private onTrafficIngested?: (backendId: number) => void;
+ private onBackendDataCleared?: (backendId: number) => void;
constructor(
port: number,
@@ -918,12 +926,14 @@ export class APIServer {
realtimeStore: RealtimeStore,
policySyncService?: SurgePolicySyncService,
onTrafficIngested?: (backendId: number) => void,
+ onBackendDataCleared?: (backendId: number) => void,
) {
this.port = port;
this.db = db;
this.realtimeStore = realtimeStore;
this.policySyncService = policySyncService;
this.onTrafficIngested = onTrafficIngested;
+ this.onBackendDataCleared = onBackendDataCleared;
}
async start() {
@@ -933,6 +943,7 @@ export class APIServer {
realtimeStore: this.realtimeStore,
policySyncService: this.policySyncService,
onTrafficIngested: this.onTrafficIngested,
+ onBackendDataCleared: this.onBackendDataCleared,
logger: false,
});
return this.app;
diff --git a/apps/collector/src/clickhouse-reader.ts b/apps/collector/src/clickhouse-reader.ts
index c119967..18d1ebf 100644
--- a/apps/collector/src/clickhouse-reader.ts
+++ b/apps/collector/src/clickhouse-reader.ts
@@ -1,8 +1,47 @@
-import type { DomainStats, HourlyStats, IPStats } from '@neko-master/shared';
+import type {
+ DomainStats,
+ HourlyStats,
+ IPStats,
+ ProxyStats,
+ RuleStats,
+} from '@neko-master/shared';
import { loadClickHouseConfig } from './clickhouse.js';
type StatsQuerySource = 'sqlite' | 'clickhouse' | 'auto';
+type RuleChainTrafficRow = {
+ rule: string;
+ chain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+};
+
+type RuleChainFlow = {
+ nodes: Array<{
+ name: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ }>;
+ links: Array<{ source: number; target: number }>;
+};
+
+type 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;
+};
+
export type ClickHouseSummary = {
totalConnections: number;
totalUpload: number;
@@ -14,10 +53,15 @@ export type ClickHouseSummary = {
export class ClickHouseReader {
private readonly config = loadClickHouseConfig();
private readonly source = this.parseSource(process.env.STATS_QUERY_SOURCE);
+ private readonly strictStats = process.env.CH_STRICT_STATS === '1';
- shouldUseForRange(start?: string, end?: string): boolean {
+ shouldUse(): boolean {
if (!this.config.enabled) return false;
- if (this.source === 'sqlite') return false;
+ return this.source !== 'sqlite';
+ }
+
+ shouldUseForRange(start?: string, end?: string): boolean {
+ if (!this.shouldUse()) return false;
if (!start || !end) return false;
const startMs = new Date(start).getTime();
const endMs = new Date(end).getTime();
@@ -415,10 +459,14 @@ LIMIT ${limit} OFFSET ${offset}
return { data, total };
}
- async getProxyStats(backendId: number, start: string, end: string): Promise<any[] | null> {
- const rows = await this.query<any>(`
+ async getProxyStats(
+ backendId: number,
+ start: string,
+ end: string,
+ ): Promise<ProxyStats[] | null> {
+ const rows = await this.query<Record<string, unknown>>(`
SELECT
- chain,
+ arrayElement(splitByString(' > ', chain), 1) AS chain,
toUInt64(SUM(upload)) AS totalUpload,
toUInt64(SUM(download)) AS totalDownload,
toUInt64(SUM(connections)) AS totalConnections,
@@ -431,7 +479,7 @@ GROUP BY chain
ORDER BY (SUM(upload) + SUM(download)) DESC
`);
if (!rows) return null;
- return rows.map((row: any) => ({
+ return rows.map((row) => ({
chain: String(row.chain || ''),
totalUpload: Number(row.totalUpload || 0),
totalDownload: Number(row.totalDownload || 0),
@@ -440,11 +488,15 @@ ORDER BY (SUM(upload) + SUM(download)) DESC
}));
}
- async getRuleStats(backendId: number, start: string, end: string): Promise<any[] | null> {
- const rows = await this.query<any>(`
+ async getRuleStats(
+ backendId: number,
+ start: string,
+ end: string,
+ ): Promise<RuleStats[] | null> {
+ const rows = await this.query<Record<string, unknown>>(`
SELECT
rule,
- any(chain) AS finalProxy,
+ arrayElement(splitByString(' > ', any(chain)), 1) AS finalProxy,
toUInt64(SUM(upload)) AS totalUpload,
toUInt64(SUM(download)) AS totalDownload,
toUInt64(SUM(connections)) AS totalConnections,
@@ -453,11 +505,12 @@ FROM ${this.config.database}.traffic_minute
WHERE backend_id = ${backendId}
AND minute >= toDateTime('${this.toDateTime(start)}')
AND minute <= toDateTime('${this.toDateTime(end)}')
+ AND rule != ''
GROUP BY rule
ORDER BY (SUM(upload) + SUM(download)) DESC
`);
if (!rows) return null;
- return rows.map((row: any) => ({
+ return rows.map((row) => ({
rule: String(row.rule || ''),
finalProxy: String(row.finalProxy || ''),
totalUpload: Number(row.totalUpload || 0),
@@ -467,6 +520,322 @@ ORDER BY (SUM(upload) + SUM(download)) DESC
}));
}
+ async getGlobalSummary(backendCount: number): Promise<{
+ totalConnections: number;
+ totalUpload: number;
+ totalDownload: number;
+ uniqueDomains: number;
+ uniqueIPs: number;
+ backendCount: number;
+ } | null> {
+ const rows = await this.query<Record<string, unknown>>(`
+SELECT
+ toUInt64(COALESCE(SUM(connections), 0)) AS totalConnections,
+ toUInt64(COALESCE(SUM(upload), 0)) AS totalUpload,
+ toUInt64(COALESCE(SUM(download), 0)) AS totalDownload,
+ toUInt64(uniqExactIf(domain, domain != '')) AS uniqueDomains,
+ toUInt64(uniqExactIf(ip, ip != '')) AS uniqueIPs
+FROM ${this.config.database}.traffic_minute
+`);
+ if (!rows || rows.length === 0) return null;
+ const row = rows[0];
+ return {
+ totalConnections: Number(row.totalConnections || 0),
+ totalUpload: Number(row.totalUpload || 0),
+ totalDownload: Number(row.totalDownload || 0),
+ uniqueDomains: Number(row.uniqueDomains || 0),
+ uniqueIPs: Number(row.uniqueIPs || 0),
+ backendCount,
+ };
+ }
+
+ async getRuleProxyMap(
+ backendId: number,
+ start?: string,
+ end?: string,
+ ): Promise<Array<{ rule: string; proxies: string[] }> | null> {
+ const timeWhere = this.buildTimeWhere(start, end);
+ const rows = await this.query<Record<string, unknown>>(`
+SELECT
+ rule,
+ groupUniqArray(arrayElement(splitByString(' > ', chain), 1)) AS proxies
+FROM ${this.config.database}.traffic_minute
+WHERE backend_id = ${backendId}
+ AND rule != ''
+ AND chain != ''${timeWhere}
+GROUP BY rule
+ORDER BY rule ASC
+`);
+ if (!rows) return null;
+ return rows.map((row) => ({
+ rule: String(row.rule || ''),
+ proxies: Array.isArray(row.proxies)
+ ? row.proxies.map(String).filter(Boolean).sort((a, b) => a.localeCompare(b))
+ : [],
+ }));
+ }
+
+ async getRuleChainFlow(
+ backendId: number,
+ rule: string,
+ start?: string,
+ end?: string,
+ ): Promise<RuleChainFlow | null> {
+ const rows = await this.getRuleChainTrafficRows(backendId, start, end, rule);
+ if (rows === null) return null;
+
+ const nodeMap = new Map<
+ string,
+ {
+ name: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ }
+ >();
+ const linkSet = new Set<string>();
+
+ for (const row of rows) {
+ const flowPath = this.buildRuleFlowPath(rule, row.chain);
+ if (flowPath.length < 2) continue;
+
+ for (let index = 0; index < flowPath.length; index += 1) {
+ const nodeName = flowPath[index];
+ if (!nodeMap.has(nodeName)) {
+ nodeMap.set(nodeName, {
+ name: nodeName,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ });
+ }
+ const node = nodeMap.get(nodeName)!;
+ node.totalUpload += row.totalUpload;
+ node.totalDownload += row.totalDownload;
+ node.totalConnections += row.totalConnections;
+ }
+
+ for (let index = 0; index < flowPath.length - 1; index += 1) {
+ linkSet.add(this.encodeFlowLinkKey(flowPath[index], flowPath[index + 1]));
+ }
+ }
+
+ const nodes = Array.from(nodeMap.values());
+ const nodeIndexMap = new Map(nodes.map((node, index) => [node.name, index]));
+ const links = Array.from(linkSet)
+ .map((linkKey) => {
+ const decoded = this.decodeFlowLinkKey(linkKey);
+ if (!decoded) return null;
+ const [sourceName, targetName] = decoded;
+ const source = nodeIndexMap.get(sourceName);
+ const target = nodeIndexMap.get(targetName);
+ if (source === undefined || target === undefined) return null;
+ return { source, target };
+ })
+ .filter((link): link is { source: number; target: number } => !!link);
+
+ return { nodes, links };
+ }
+
+ async getAllRuleChainFlows(
+ backendId: number,
+ start?: string,
+ end?: string,
+ ): Promise<RuleChainFlowAll | null> {
+ const rows = await this.getRuleChainTrafficRows(backendId, start, end);
+ if (rows === null) return null;
+
+ const nodeMap = new Map<
+ string,
+ {
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ rules: Set<string>;
+ layer: number;
+ }
+ >();
+ const linkMap = new Map<string, Set<string>>();
+ const rulePathNodes = new Map<string, Set<string>>();
+ const rulePathLinks = new Map<string, Set<string>>();
+ const outgoingByNode = new Map<string, Set<string>>();
+ const incomingByNode = new Map<string, Set<string>>();
+
+ for (const row of rows) {
+ const ruleName = row.rule;
+ if (!rulePathNodes.has(ruleName)) {
+ rulePathNodes.set(ruleName, new Set());
+ rulePathLinks.set(ruleName, new Set());
+ }
+
+ const flowPath = this.buildRuleFlowPath(ruleName, row.chain);
+ if (flowPath.length < 2) continue;
+
+ for (let index = 0; index < flowPath.length; index += 1) {
+ const nodeName = flowPath[index];
+ if (!nodeMap.has(nodeName)) {
+ nodeMap.set(nodeName, {
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ rules: new Set(),
+ layer: index,
+ });
+ }
+ const node = nodeMap.get(nodeName)!;
+ node.totalUpload += row.totalUpload;
+ node.totalDownload += row.totalDownload;
+ node.totalConnections += row.totalConnections;
+ node.rules.add(ruleName);
+ node.layer = Math.max(node.layer, index);
+ rulePathNodes.get(ruleName)!.add(nodeName);
+ }
+
+ for (let index = 0; index < flowPath.length - 1; index += 1) {
+ const sourceName = flowPath[index];
+ const targetName = flowPath[index + 1];
+ const linkKey = this.encodeFlowLinkKey(sourceName, targetName);
+ if (!linkMap.has(linkKey)) {
+ linkMap.set(linkKey, new Set());
+ }
+ linkMap.get(linkKey)!.add(ruleName);
+ rulePathLinks.get(ruleName)!.add(linkKey);
+
+ if (!outgoingByNode.has(sourceName)) {
+ outgoingByNode.set(sourceName, new Set());
+ }
+ outgoingByNode.get(sourceName)!.add(targetName);
+
+ if (!incomingByNode.has(targetName)) {
+ incomingByNode.set(targetName, new Set());
+ }
+ incomingByNode.get(targetName)!.add(sourceName);
+ }
+ }
+
+ const nodeEntries = Array.from(nodeMap.entries());
+ const nodeTypeMap = new Map<string, 'rule' | 'group' | 'proxy'>();
+ let computedMaxLayer = 0;
+
+ const isBuiltInPolicy = (name: string): boolean =>
+ name === 'DIRECT' || name === 'REJECT' || name === 'REJECT-TINY';
+
+ for (const [name, nodeData] of nodeEntries) {
+ const hasOutgoing = (outgoingByNode.get(name)?.size ?? 0) > 0;
+ const hasIncoming = (incomingByNode.get(name)?.size ?? 0) > 0;
+
+ if (!hasIncoming) {
+ nodeTypeMap.set(name, 'rule');
+ nodeData.layer = 0;
+ } else if (!hasOutgoing && !isBuiltInPolicy(name)) {
+ nodeTypeMap.set(name, 'proxy');
+ } else {
+ nodeTypeMap.set(name, 'group');
+ }
+ computedMaxLayer = Math.max(computedMaxLayer, nodeData.layer);
+ }
+
+ for (const [name, nodeData] of nodeEntries) {
+ if (nodeTypeMap.get(name) === 'proxy') {
+ nodeData.layer = computedMaxLayer;
+ }
+ }
+
+ const nodeTypeOrder = (type: 'rule' | 'group' | 'proxy'): number =>
+ type === 'rule' ? 0 : type === 'group' ? 1 : 2;
+
+ const sortedNodeEntries = [...nodeEntries].sort(
+ ([nameA, dataA], [nameB, dataB]) => {
+ if (dataA.layer !== dataB.layer) {
+ return dataA.layer - dataB.layer;
+ }
+ const typeDiff =
+ nodeTypeOrder(nodeTypeMap.get(nameA)!) -
+ nodeTypeOrder(nodeTypeMap.get(nameB)!);
+ if (typeDiff !== 0) {
+ return typeDiff;
+ }
+ return nameA.localeCompare(nameB);
+ },
+ );
+
+ const nodes = sortedNodeEntries.map(([name, data]) => ({
+ name,
+ layer: data.layer,
+ nodeType: nodeTypeMap.get(name)!,
+ totalUpload: data.totalUpload,
+ totalDownload: data.totalDownload,
+ totalConnections: data.totalConnections,
+ rules: Array.from(data.rules),
+ }));
+
+ const nodeIndexMap = new Map(nodes.map((node, index) => [node.name, index]));
+
+ const links = Array.from(linkMap.entries())
+ .map(([key, rules]) => {
+ const decoded = this.decodeFlowLinkKey(key);
+ if (!decoded) return null;
+ const [sourceName, targetName] = decoded;
+ const source = nodeIndexMap.get(sourceName);
+ const target = nodeIndexMap.get(targetName);
+ if (source === undefined || target === undefined) return null;
+ return {
+ sourceName,
+ targetName,
+ source,
+ target,
+ rules: Array.from(rules),
+ };
+ })
+ .filter(
+ (link): link is {
+ sourceName: string;
+ targetName: string;
+ source: number;
+ target: number;
+ rules: string[];
+ } => !!link,
+ )
+ .sort((left, right) => {
+ const sourceDiff = left.sourceName.localeCompare(right.sourceName);
+ if (sourceDiff !== 0) return sourceDiff;
+ return left.targetName.localeCompare(right.targetName);
+ })
+ .map(({ source, target, rules }) => ({ source, target, rules }));
+
+ const rulePaths: Record<string, { nodeIndices: number[]; linkIndices: number[] }> =
+ {};
+ for (const [ruleName, nodeNames] of rulePathNodes) {
+ const nodeIndices = Array.from(nodeNames)
+ .map((name) => nodeIndexMap.get(name)!)
+ .filter((index) => index !== undefined);
+ const linkIndices: number[] = [];
+ const linkKeys = rulePathLinks.get(ruleName)!;
+
+ links.forEach((link, index) => {
+ const sourceName = nodes[link.source].name;
+ const targetName = nodes[link.target].name;
+ if (linkKeys.has(this.encodeFlowLinkKey(sourceName, targetName))) {
+ linkIndices.push(index);
+ }
+ });
+
+ rulePaths[ruleName] = { nodeIndices, linkIndices };
+ }
+
+ const maxLayer = nodes.reduce(
+ (max, node) => Math.max(max, node.layer),
+ 0,
+ );
+
+ return { nodes, links, rulePaths, maxLayer };
+ }
+
+ getRecentConnections(_backendId: number, _limit: number): [] {
+ // connection_logs is deprecated; keep API compatibility.
+ return [];
+ }
+
async getDeviceStats(backendId: number, start: string, end: string, limit: number): Promise<any[] | null> {
const rows = await this.query<any>(`
SELECT
@@ -501,6 +870,7 @@ LIMIT ${Math.max(1, limit)}
limit: number,
filters: {
chain?: string;
+ sourceChain?: string;
rule?: string;
sourceIP?: string;
domain?: string;
@@ -547,6 +917,7 @@ LIMIT ${Math.max(1, limit)}
limit: number,
filters: {
chain?: string;
+ sourceChain?: string;
rule?: string;
sourceIP?: string;
domain?: string;
@@ -590,6 +961,7 @@ LIMIT ${Math.max(1, limit)}
end: string,
filters: {
chain?: string;
+ sourceChain?: string;
rule?: string;
sourceIP?: string;
domain?: string;
@@ -620,6 +992,118 @@ ORDER BY (SUM(upload) + SUM(download)) DESC
}));
}
+ private async getRuleChainTrafficRows(
+ backendId: number,
+ start?: string,
+ end?: string,
+ rule?: string,
+ ): Promise<RuleChainTrafficRow[] | null> {
+ const timeWhere = this.buildTimeWhere(start, end);
+ const ruleWhere = rule ? ` AND rule = '${this.esc(rule)}'` : '';
+ const rows = await this.query<Record<string, unknown>>(`
+SELECT
+ rule,
+ chain,
+ toUInt64(SUM(upload)) AS totalUpload,
+ toUInt64(SUM(download)) AS totalDownload,
+ toUInt64(SUM(connections)) AS totalConnections
+FROM ${this.config.database}.traffic_minute
+WHERE backend_id = ${backendId}
+ AND rule != ''
+ AND chain != ''${timeWhere}${ruleWhere}
+GROUP BY rule, chain
+ORDER BY rule, chain
+`);
+ if (!rows) return null;
+ return rows.map((row) => ({
+ rule: String(row.rule || ''),
+ chain: String(row.chain || ''),
+ totalUpload: Number(row.totalUpload || 0),
+ totalDownload: Number(row.totalDownload || 0),
+ totalConnections: Number(row.totalConnections || 0),
+ }));
+ }
+
+ private buildTimeWhere(start?: string, end?: string): string {
+ if (!start || !end) return '';
+ return `\n AND minute >= toDateTime('${this.toDateTime(start)}')\n AND minute <= toDateTime('${this.toDateTime(end)}')`;
+ }
+
+ private encodeFlowLinkKey(sourceName: string, targetName: string): string {
+ return JSON.stringify([sourceName, targetName]);
+ }
+
+ private decodeFlowLinkKey(
+ key: string,
+ ): [sourceName: string, targetName: string] | null {
+ try {
+ const parsed = JSON.parse(key) as unknown;
+ if (
+ Array.isArray(parsed) &&
+ parsed.length === 2 &&
+ typeof parsed[0] === 'string' &&
+ typeof parsed[1] === 'string'
+ ) {
+ return [parsed[0], parsed[1]];
+ }
+ } catch {
+ return null;
+ }
+ return null;
+ }
+
+ private splitChainParts(chain: string): string[] {
+ return chain
+ .split('>')
+ .map((part) => part.trim())
+ .filter(Boolean);
+ }
+
+ private normalizeFlowLabel(label: string): string {
+ return label
+ .normalize('NFKC')
+ .replace(/^[^\p{L}\p{N}]+/gu, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .toLowerCase();
+ }
+
+ private findRuleIndexInChain(chainParts: string[], rule: string): number {
+ const exactIndex = chainParts.findIndex((part) => part === rule);
+ if (exactIndex !== -1) {
+ return exactIndex;
+ }
+
+ const normalizedRule = this.normalizeFlowLabel(rule);
+ if (!normalizedRule) {
+ return -1;
+ }
+
+ return chainParts.findIndex(
+ (part) => this.normalizeFlowLabel(part) === normalizedRule,
+ );
+ }
+
+ private buildRuleFlowPath(rule: string, chain: string): string[] {
+ const chainParts = this.splitChainParts(chain);
+ if (chainParts.length === 0) {
+ return [];
+ }
+
+ const ruleIndex = this.findRuleIndexInChain(chainParts, rule);
+ if (ruleIndex !== -1) {
+ return chainParts.slice(0, ruleIndex + 1).reverse();
+ }
+
+ const reversed = [...chainParts].reverse();
+ const normalizedRule = this.normalizeFlowLabel(rule);
+ const normalizedHead = this.normalizeFlowLabel(reversed[0] || '');
+ if (normalizedRule && normalizedRule === normalizedHead) {
+ return reversed;
+ }
+ return [rule, ...reversed];
+ }
+
private async query<T>(query: string): Promise<T[] | null> {
if (!this.config.enabled) return null;
const baseUrl = `${this.config.protocol}://${this.config.host}:${this.config.port}`;
@@ -647,7 +1131,7 @@ ORDER BY (SUM(upload) + SUM(download)) DESC
return json.data || [];
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
- if (this.source === 'clickhouse') {
+ if (this.source === 'clickhouse' || this.strictStats) {
throw new Error(`[ClickHouse Reader] strict mode query failed: ${message}`);
}
console.warn(`[ClickHouse Reader] query failed, fallback to sqlite: ${message}`);
@@ -665,7 +1149,14 @@ ORDER BY (SUM(upload) + SUM(download)) DESC
private buildFilters(filters: Record<string, string | undefined>): string {
const clauses: string[] = [];
- if (filters.chain) clauses.push(`chain = '${this.esc(filters.chain)}'`);
+ if (filters.chain) {
+ const chain = this.esc(filters.chain);
+ clauses.push(`(chain = '${chain}' OR startsWith(chain, '${chain} > '))`);
+ }
+ if (filters.sourceChain) {
+ const chain = this.esc(filters.sourceChain);
+ clauses.push(`(chain = '${chain}' OR startsWith(chain, '${chain} > '))`);
+ }
if (filters.rule) clauses.push(`rule = '${this.esc(filters.rule)}'`);
if (filters.sourceIP) clauses.push(`source_ip = '${this.esc(filters.sourceIP)}'`);
if (filters.domain) clauses.push(`domain = '${this.esc(filters.domain)}'`);
@@ -680,9 +1171,20 @@ ORDER BY (SUM(upload) + SUM(download)) DESC
private parseSource(value: string | undefined): StatsQuerySource {
const normalized = String(value || 'sqlite').trim().toLowerCase();
- if (normalized === 'clickhouse' || normalized === 'auto') {
+ if (normalized === 'clickhouse' || normalized === 'auto' || normalized === 'sqlite') {
return normalized;
}
+ // Tolerate common typo to avoid accidental fallback loops.
+ if (normalized === 'clickhous') {
+ console.warn('[ClickHouse Reader] STATS_QUERY_SOURCE=clickhous is invalid, treating it as clickhouse');
+ return 'clickhouse';
+ }
+ if (value && normalized !== 'sqlite') {
+ console.warn(
+ `[ClickHouse Reader] Invalid STATS_QUERY_SOURCE=${value}, fallback to sqlite`,
+ );
+ }
return 'sqlite';
}
+
}
diff --git a/apps/collector/src/clickhouse-writer.ts b/apps/collector/src/clickhouse-writer.ts
index b1e8b9e..1545c76 100644
--- a/apps/collector/src/clickhouse-writer.ts
+++ b/apps/collector/src/clickhouse-writer.ts
@@ -172,8 +172,11 @@ class ClickHouseWriter {
}
}
-const writer = new ClickHouseWriter();
+let writer: ClickHouseWriter | null = null;
export function getClickHouseWriter(): ClickHouseWriter {
+ if (!writer) {
+ writer = new ClickHouseWriter();
+ }
return writer;
}
diff --git a/apps/collector/src/clickhouse.ts b/apps/collector/src/clickhouse.ts
index ce1f957..9cde3b0 100644
--- a/apps/collector/src/clickhouse.ts
+++ b/apps/collector/src/clickhouse.ts
@@ -120,6 +120,21 @@ export async function runClickHouseQuery(
config: ClickHouseConfig,
query: string,
): Promise<void> {
+ await runClickHouseQueryWithResponse(config, query);
+}
+
+export async function runClickHouseTextQuery(
+ config: ClickHouseConfig,
+ query: string,
+): Promise<string> {
+ const response = await runClickHouseQueryWithResponse(config, query);
+ return await response.text();
+}
+
+async function runClickHouseQueryWithResponse(
+ config: ClickHouseConfig,
+ query: string,
+): Promise<Response> {
const baseUrl = buildBaseUrl(config);
const authHeader =
config.password.length > 0
@@ -141,6 +156,8 @@ export async function runClickHouseQuery(
const body = await response.text();
throw new Error(`query failed: status=${response.status} body=${body.slice(0, 160)}`);
}
+
+ return response;
}
export async function ensureClickHouseSchema(config: ClickHouseConfig): Promise<void> {
diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.ts
index a37a45d..e95ed91 100644
--- a/apps/collector/src/db.ts
+++ b/apps/collector/src/db.ts
@@ -864,6 +864,20 @@ export class StatsDatabase {
return value;
}
+ clearRangeQueryCache(backendId?: number): void {
+ if (backendId === undefined) {
+ this.rangeQueryCache.clear();
+ return;
+ }
+
+ const backendMarker = `:${backendId}|`;
+ for (const key of this.rangeQueryCache.keys()) {
+ if (key.includes(backendMarker)) {
+ this.rangeQueryCache.delete(key);
+ }
+ }
+ }
+
private prepareSummaryStmts() {
return {
rangeCombined: this.db.prepare(`
@@ -966,8 +980,14 @@ export class StatsDatabase {
updateBackend(id: number, updates: Partial<Omit<BackendConfig, 'id' | 'created_at'>>) { this.repos.backend.updateBackend(id, updates); }
setActiveBackend(id: number) { this.repos.backend.setActiveBackend(id); }
setBackendListening(id: number, listening: boolean) { this.repos.backend.setBackendListening(id, listening); }
- deleteBackend(id: number) { this.repos.backend.deleteBackend(id); }
- deleteBackendData(id: number) { this.repos.backend.deleteBackendData(id); }
+ deleteBackend(id: number) {
+ this.repos.backend.deleteBackend(id);
+ this.clearRangeQueryCache(id);
+ }
+ deleteBackendData(id: number) {
+ this.repos.backend.deleteBackendData(id);
+ this.clearRangeQueryCache(id);
+ }
getGlobalSummary() { return this.repos.backend.getGlobalSummary(); }
upsertAgentHeartbeat(input: {
diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.ts
index 3b569f4..9abf250 100644
--- a/apps/collector/src/index.ts
+++ b/apps/collector/src/index.ts
@@ -83,6 +83,10 @@ async function main() {
(backendId: number) => {
wsServer.broadcastStats(backendId);
},
+ (backendId: number) => {
+ wsServer.clearBackendCache(backendId);
+ wsServer.broadcastStats(backendId, true);
+ },
);
apiServer.start();
diff --git a/apps/collector/src/modules/backend/backend.controller.ts b/apps/collector/src/modules/backend/backend.controller.ts
index c0990f8..81dd53a 100644
--- a/apps/collector/src/modules/backend/backend.controller.ts
+++ b/apps/collector/src/modules/backend/backend.controller.ts
@@ -98,7 +98,7 @@ const backendController: FastifyPluginAsync = async (fastify: FastifyInstance):
return reply.status(404).send({ error: 'Backend not found' });
}
- const result = service.deleteBackend(backendId);
+ const result = await service.deleteBackend(backendId);
return result;
});
@@ -197,7 +197,7 @@ const backendController: FastifyPluginAsync = async (fastify: FastifyInstance):
return reply.status(404).send({ error: 'Backend not found' });
}
- const result = service.clearBackendData(backendId);
+ const result = await service.clearBackendData(backendId);
return result;
});
};
diff --git a/apps/collector/src/modules/backend/backend.service.ts b/apps/collector/src/modules/backend/backend.service.ts
index 5a8dfaf..4d77fe6 100644
--- a/apps/collector/src/modules/backend/backend.service.ts
+++ b/apps/collector/src/modules/backend/backend.service.ts
@@ -18,6 +18,7 @@ import type {
RotateAgentTokenResult,
} from './backend.types.js';
import { isAgentBackendUrl } from '@neko-master/shared';
+import { loadClickHouseConfig, runClickHouseQuery } from '../../clickhouse.js';
import type { AuthService } from '../auth/auth.service.js';
@@ -53,6 +54,7 @@ export class BackendService {
private db: StatsDatabase,
private realtimeStore: RealtimeStore,
private authService: AuthService,
+ private onBackendDataCleared?: (backendId: number) => void,
) {}
/**
@@ -296,8 +298,11 @@ export class BackendService {
/**
* Delete a backend
*/
- deleteBackend(id: number): { message: string } {
+ async deleteBackend(id: number): Promise<{ message: string }> {
+ await this.clearClickHouseBackendData(id);
this.db.deleteBackend(id);
+ this.realtimeStore.clearBackend(id);
+ this.onBackendDataCleared?.(id);
return { message: 'Backend deleted successfully' };
}
@@ -345,13 +350,39 @@ export class BackendService {
/**
* Clear all data for a specific backend
*/
- clearBackendData(id: number): { message: string } {
+ async clearBackendData(id: number): Promise<{ message: string }> {
this.db.deleteBackendData(id);
+ await this.clearClickHouseBackendData(id);
// Also clear realtime cache
this.realtimeStore.clearBackend(id);
+ this.onBackendDataCleared?.(id);
return { message: 'Backend data cleared successfully' };
}
+ private async clearClickHouseBackendData(backendId: number): Promise<void> {
+ const config = loadClickHouseConfig();
+ if (!config.enabled) {
+ 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`,
+ );
+ console.info(`[BackendService] Cleared ClickHouse stats for backend ${backendId}`);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ console.warn(
+ `[BackendService] Failed to clear ClickHouse stats for backend ${backendId}: ${message}`,
+ );
+ }
+ }
+
/**
* Test connection to a backend (uses stored token)
*/
diff --git a/apps/collector/src/modules/config/config.controller.ts b/apps/collector/src/modules/config/config.controller.ts
index aa28d2a..0210840 100644
--- a/apps/collector/src/modules/config/config.controller.ts
+++ b/apps/collector/src/modules/config/config.controller.ts
@@ -1,6 +1,7 @@
import type { FastifyInstance, FastifyPluginAsync } from "fastify";
import type { StatsDatabase, GeoLookupConfig, GeoLookupProvider } from "../../db.js";
import type { RealtimeStore } from "../../realtime.js";
+import { loadClickHouseConfig, runClickHouseQuery, runClickHouseTextQuery } from "../../clickhouse.js";
declare module "fastify" {
interface FastifyInstance {
@@ -32,12 +33,123 @@ function toGeoLookupResponse(config: GeoLookupConfig) {
};
}
+function parseNonNegativeIntText(raw: string): number | null {
+ const value = raw.trim();
+ if (!value) return null;
+ if (!/^\d+$/.test(value)) return null;
+
+ try {
+ const bigintValue = BigInt(value);
+ if (bigintValue > BigInt(Number.MAX_SAFE_INTEGER)) {
+ return Number.MAX_SAFE_INTEGER;
+ }
+ return Number(bigintValue);
+ } catch {
+ return null;
+ }
+}
+
+type ClickHouseStorageStats = {
+ trafficRows: number;
+ trafficSize: number;
+ countrySize: number;
+};
+
+function formatUtcMinuteCutoff(days: number): string {
+ const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
+ return `${cutoff.slice(0, 16).replace("T", " ")}:00`;
+}
+
+async function cleanupClickHouseData(
+ fastify: FastifyInstance,
+ days: number,
+ backendId?: number,
+): Promise<void> {
+ const chConfig = loadClickHouseConfig();
+ if (!chConfig.enabled) return;
+
+ const database = chConfig.database.replace(/'/g, "''");
+ const tables = ["traffic_minute", "country_minute"] as const;
+
+ if (days === 0 && backendId === undefined) {
+ for (const table of tables) {
+ await runClickHouseQuery(chConfig, `TRUNCATE TABLE ${database}.${table}`);
+ }
+ return;
+ }
+
+ const conditions: string[] = [];
+ if (backendId !== undefined) {
+ conditions.push(`backend_id = ${backendId}`);
+ }
+ if (days > 0) {
+ const cutoff = formatUtcMinuteCutoff(days).replace(/'/g, "''");
+ conditions.push(`minute < toDateTime('${cutoff}')`);
+ }
+
+ if (conditions.length === 0) {
+ return;
+ }
+
+ const whereClause = conditions.join(" AND ");
+ for (const table of tables) {
+ await runClickHouseQuery(
+ chConfig,
+ `ALTER TABLE ${database}.${table} DELETE WHERE ${whereClause} SETTINGS mutations_sync = 2`,
+ );
+ }
+}
+
+async function resolveClickHouseStorageStats(
+ fastify: FastifyInstance,
+): Promise<ClickHouseStorageStats | null> {
+ const chConfig = loadClickHouseConfig();
+ if (!chConfig.enabled) {
+ return null;
+ }
+
+ try {
+ const database = chConfig.database.replace(/'/g, "''");
+ const [rowsText, trafficBytesText, countryBytesText] = await Promise.all([
+ runClickHouseTextQuery(
+ chConfig,
+ `SELECT toUInt64(COALESCE(sum(rows), 0)) FROM system.parts WHERE active = 1 AND database = '${database}' AND table = 'traffic_minute'`,
+ ),
+ runClickHouseTextQuery(
+ chConfig,
+ `SELECT toUInt64(COALESCE(sum(bytes_on_disk), 0)) FROM system.parts WHERE active = 1 AND database = '${database}' AND table = 'traffic_minute'`,
+ ),
+ runClickHouseTextQuery(
+ chConfig,
+ `SELECT toUInt64(COALESCE(sum(bytes_on_disk), 0)) FROM system.parts WHERE active = 1 AND database = '${database}' AND table = 'country_minute'`,
+ ),
+ ]);
+
+ return {
+ trafficRows: parseNonNegativeIntText(rowsText) ?? 0,
+ trafficSize: parseNonNegativeIntText(trafficBytesText) ?? 0,
+ countrySize: parseNonNegativeIntText(countryBytesText) ?? 0,
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ fastify.log.warn(`[Config] Failed to load ClickHouse storage stats: ${message}`);
+ return null;
+ }
+}
+
const configController: FastifyPluginAsync = async (fastify: FastifyInstance): Promise<void> => {
// Compatibility routes: DB management
fastify.get("/stats", async () => {
+ const sqliteSize = fastify.db.getDatabaseSize();
+ const sqliteCount = fastify.db.getTotalConnectionLogsCount();
+ const chStats = await resolveClickHouseStorageStats(fastify);
+ const clickhouseSize = chStats ? chStats.trafficSize + chStats.countrySize : 0;
+
return {
- size: fastify.db.getDatabaseSize(),
- totalConnectionsCount: fastify.db.getTotalConnectionLogsCount(),
+ size: sqliteSize + clickhouseSize,
+ sqliteSize,
+ clickhouseSize,
+ totalConnectionsCount: chStats ? chStats.trafficRows : sqliteCount,
};
});
@@ -54,10 +166,19 @@ const configController: FastifyPluginAsync = async (fastify: FastifyInstance): P
return reply.status(400).send({ error: "Valid days parameter required" });
}
+ try {
+ await cleanupClickHouseData(fastify, days, backendId);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ fastify.log.error(`[Config] ClickHouse cleanup failed: ${message}`);
+ return reply.status(500).send({ error: `ClickHouse cleanup failed: ${message}` });
+ }
+
const result = fastify.db.cleanupOldData(backendId ?? null, days);
+ fastify.db.clearRangeQueryCache(backendId);
if (days === 0) {
- if (backendId) {
+ if (backendId !== undefined) {
fastify.realtimeStore.clearBackend(backendId);
} else {
const backends = fastify.db.getAllBackends();
diff --git a/apps/collector/src/modules/stats/stats.controller.ts b/apps/collector/src/modules/stats/stats.controller.ts
index fefc852..7fa4ddf 100644
--- a/apps/collector/src/modules/stats/stats.controller.ts
+++ b/apps/collector/src/modules/stats/stats.controller.ts
@@ -213,6 +213,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr
domain,
timeRange,
sourceIP,
+ sourceChain,
);
});
@@ -242,6 +243,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr
timeRange,
effectiveLimit,
sourceIP,
+ sourceChain,
);
});
@@ -269,6 +271,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr
ip,
timeRange,
sourceIP,
+ sourceChain,
);
});
@@ -298,6 +301,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr
timeRange,
effectiveLimit,
sourceIP,
+ sourceChain,
);
});
diff --git a/apps/collector/src/modules/stats/stats.service.ts b/apps/collector/src/modules/stats/stats.service.ts
index 1ee0655..7cb893d 100644
--- a/apps/collector/src/modules/stats/stats.service.ts
+++ b/apps/collector/src/modules/stats/stats.service.ts
@@ -35,6 +35,7 @@ type RoutedSource = 'clickhouse' | 'sqlite';
export class StatsService {
private clickHouseReader: ClickHouseReader;
+ private readonly strictStats = process.env.CH_STRICT_STATS === '1';
private routeMetricsIntervalMs = Math.max(
1000,
Number.parseInt(process.env.STATS_ROUTE_METRICS_LOG_INTERVAL_MS || '60000', 10) || 60000,
@@ -56,7 +57,36 @@ export class StatsService {
);
}
+ private shouldUseClickHouseForOptionalRange(timeRange: TimeRange): boolean {
+ if (!this.clickHouseReader.shouldUse()) {
+ return false;
+ }
+ if (!timeRange.active) {
+ return true;
+ }
+ return this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end);
+ }
+
+ private isStrictStatsEnabled(): boolean {
+ return this.strictStats && this.clickHouseReader.shouldUse();
+ }
+
+ private failIfStrictFallback(route: string): void {
+ if (!this.isStrictStatsEnabled()) {
+ return;
+ }
+ throw new Error(
+ `[StatsService] SQLite fallback is disabled by CH_STRICT_STATS=1 (route=${route})`,
+ );
+ }
+
private recordRoute(route: string, source: RoutedSource): void {
+ if (this.isStrictStatsEnabled() && source === 'sqlite') {
+ throw new Error(
+ `[StatsService] SQLite fallback is disabled by CH_STRICT_STATS=1 (route=${route})`,
+ );
+ }
+
const existing = this.routeMetrics[route] || { clickhouse: 0, sqlite: 0 };
existing[source] += 1;
this.routeMetrics[route] = existing;
@@ -219,11 +249,20 @@ export class StatsService {
this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end);
if (!shouldUseCH || !timeRange.start || !timeRange.end) {
+ this.failIfStrictFallback('summary');
this.recordRoute('summary', 'sqlite');
return this.getSummary(backendId, timeRange);
}
- const [summaryCH, topDomainsCH, topIPsCH, hourlyStatsCH, trafficInRangeCH] =
+ const [
+ summaryCH,
+ topDomainsCH,
+ topIPsCH,
+ proxyStatsCH,
+ ruleStatsCH,
+ hourlyStatsCH,
+ trafficInRangeCH,
+ ] =
await Promise.all([
this.clickHouseReader.getSummary(backendId, timeRange.start, timeRange.end),
this.clickHouseReader.getTopDomainsLight(
@@ -238,6 +277,8 @@ export class StatsService {
timeRange.start,
timeRange.end,
),
+ this.clickHouseReader.getProxyStats(backendId, timeRange.start, timeRange.end),
+ this.clickHouseReader.getRuleStats(backendId, timeRange.start, timeRange.end),
this.clickHouseReader.getHourlyStats(
backendId,
24,
@@ -270,12 +311,16 @@ export class StatsService {
? this.realtimeStore.mergeTopIPs(backendId, dbTopIPs, 10)
: dbTopIPs;
- const dbProxyStats = this.db.getProxyStats(backendId, timeRange.start, timeRange.end);
+ const dbProxyStats =
+ proxyStatsCH ||
+ this.db.getProxyStats(backendId, timeRange.start, timeRange.end);
const proxyStats = includeRealtime
? this.realtimeStore.mergeProxyStats(backendId, dbProxyStats)
: dbProxyStats;
- const dbRuleStats = this.db.getRuleStats(backendId, timeRange.start, timeRange.end);
+ const dbRuleStats =
+ ruleStatsCH ||
+ this.db.getRuleStats(backendId, timeRange.start, timeRange.end);
const ruleStats = includeRealtime
? this.realtimeStore.mergeRuleStats(backendId, dbRuleStats)
: dbRuleStats;
@@ -290,7 +335,16 @@ export class StatsService {
? this.realtimeStore.getTodayDelta(backendId)
: { upload: 0, download: 0 };
const usedCH =
- !!summaryCH || !!topDomainsCH || !!topIPsCH || !!hourlyStatsCH || !!trafficInRangeCH;
+ !!summaryCH ||
+ !!topDomainsCH ||
+ !!topIPsCH ||
+ !!proxyStatsCH ||
+ !!ruleStatsCH ||
+ !!hourlyStatsCH ||
+ !!trafficInRangeCH;
+ if (!usedCH) {
+ this.failIfStrictFallback('summary');
+ }
this.recordRoute('summary', usedCH ? 'clickhouse' : 'sqlite');
return {
@@ -324,7 +378,17 @@ export class StatsService {
return this.db.getGlobalSummary();
}
- getGlobalSummaryWithRouting(): GlobalSummary {
+ async getGlobalSummaryWithRouting(): Promise<GlobalSummary> {
+ if (this.clickHouseReader.shouldUse()) {
+ const backendCount = this.db.getAllBackends().length;
+ const ch = await this.clickHouseReader.getGlobalSummary(backendCount);
+ if (ch) {
+ this.recordRoute('global', 'clickhouse');
+ return ch;
+ }
+ }
+
+ this.failIfStrictFallback('global');
this.recordRoute('global', 'sqlite');
return this.db.getGlobalSummary();
}
@@ -481,6 +545,7 @@ export class StatsService {
domain: string,
timeRange: TimeRange,
sourceIP?: string,
+ sourceChain?: string,
): Promise<any[]> {
const shouldUseCH = this.shouldUseClickHouse(timeRange);
if (shouldUseCH && timeRange.start && timeRange.end) {
@@ -488,7 +553,7 @@ export class StatsService {
backendId,
timeRange.start,
timeRange.end,
- { domain, sourceIP },
+ { domain, sourceIP, sourceChain },
);
if (ch) {
this.recordRoute('domains.proxy-stats', 'clickhouse');
@@ -496,7 +561,14 @@ export class StatsService {
}
}
this.recordRoute('domains.proxy-stats', 'sqlite');
- return this.db.getDomainProxyStats(backendId, domain, timeRange.start, timeRange.end, sourceIP);
+ return this.db.getDomainProxyStats(
+ backendId,
+ domain,
+ timeRange.start,
+ timeRange.end,
+ sourceIP,
+ sourceChain,
+ );
}
/**
@@ -519,6 +591,7 @@ export class StatsService {
timeRange: TimeRange,
limit: number,
sourceIP?: string,
+ sourceChain?: string,
): Promise<IPStats[]> {
const shouldUseCH = this.shouldUseClickHouse(timeRange);
if (shouldUseCH && timeRange.start && timeRange.end) {
@@ -527,7 +600,7 @@ export class StatsService {
timeRange.start,
timeRange.end,
limit,
- { domain, sourceIP },
+ { domain, sourceIP, sourceChain },
);
if (ch) {
this.recordRoute('domains.ip-details', 'clickhouse');
@@ -535,7 +608,15 @@ export class StatsService {
}
}
this.recordRoute('domains.ip-details', 'sqlite');
- return this.db.getDomainIPDetails(backendId, domain, timeRange.start, timeRange.end, limit, sourceIP);
+ return this.db.getDomainIPDetails(
+ backendId,
+ domain,
+ timeRange.start,
+ timeRange.end,
+ limit,
+ sourceIP,
+ sourceChain,
+ );
}
/**
@@ -556,6 +637,7 @@ export class StatsService {
ip: string,
timeRange: TimeRange,
sourceIP?: string,
+ sourceChain?: string,
): Promise<any[]> {
const shouldUseCH = this.shouldUseClickHouse(timeRange);
if (shouldUseCH && timeRange.start && timeRange.end) {
@@ -563,7 +645,7 @@ export class StatsService {
backendId,
timeRange.start,
timeRange.end,
- { ip, sourceIP },
+ { ip, sourceIP, sourceChain },
);
if (ch) {
this.recordRoute('ips.proxy-stats', 'clickhouse');
@@ -571,7 +653,14 @@ export class StatsService {
}
}
this.recordRoute('ips.proxy-stats', 'sqlite');
- return this.db.getIPProxyStats(backendId, ip, timeRange.start, timeRange.end, sourceIP);
+ return this.db.getIPProxyStats(
+ backendId,
+ ip,
+ timeRange.start,
+ timeRange.end,
+ sourceIP,
+ sourceChain,
+ );
}
/**
@@ -594,6 +683,7 @@ export class StatsService {
timeRange: TimeRange,
limit: number,
sourceIP?: string,
+ sourceChain?: string,
): Promise<DomainStats[]> {
const shouldUseCH = this.shouldUseClickHouse(timeRange);
if (shouldUseCH && timeRange.start && timeRange.end) {
@@ -602,7 +692,7 @@ export class StatsService {
timeRange.start,
timeRange.end,
limit,
- { ip, sourceIP },
+ { ip, sourceIP, sourceChain },
);
if (ch) {
this.recordRoute('ips.domain-details', 'clickhouse');
@@ -610,7 +700,15 @@ export class StatsService {
}
}
this.recordRoute('ips.domain-details', 'sqlite');
- return this.db.getIPDomainDetails(backendId, ip, timeRange.start, timeRange.end, limit, sourceIP);
+ return this.db.getIPDomainDetails(
+ backendId,
+ ip,
+ timeRange.start,
+ timeRange.end,
+ limit,
+ sourceIP,
+ sourceChain,
+ );
}
/**
@@ -960,7 +1058,26 @@ export class StatsService {
return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end);
}
- getRuleChainFlowWithRouting(backendId: number, rule: string, timeRange: TimeRange): any {
+ async getRuleChainFlowWithRouting(
+ backendId: number,
+ rule: string,
+ timeRange: TimeRange,
+ ): Promise<any> {
+ const shouldUseCH = this.shouldUseClickHouseForOptionalRange(timeRange);
+ if (shouldUseCH) {
+ const ch = await this.clickHouseReader.getRuleChainFlow(
+ backendId,
+ rule,
+ timeRange.start,
+ timeRange.end,
+ );
+ if (ch) {
+ this.recordRoute('rules.chain-flow', 'clickhouse');
+ return ch;
+ }
+ }
+
+ this.failIfStrictFallback('rules.chain-flow');
this.recordRoute('rules.chain-flow', 'sqlite');
return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end);
}
@@ -972,7 +1089,24 @@ export class StatsService {
return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end);
}
- getAllRuleChainFlowsWithRouting(backendId: number, timeRange: TimeRange): any {
+ async getAllRuleChainFlowsWithRouting(
+ backendId: number,
+ timeRange: TimeRange,
+ ): Promise<any> {
+ const shouldUseCH = this.shouldUseClickHouseForOptionalRange(timeRange);
+ if (shouldUseCH) {
+ const ch = await this.clickHouseReader.getAllRuleChainFlows(
+ backendId,
+ timeRange.start,
+ timeRange.end,
+ );
+ if (ch) {
+ this.recordRoute('rules.chain-flow-all', 'clickhouse');
+ return ch;
+ }
+ }
+
+ this.failIfStrictFallback('rules.chain-flow-all');
this.recordRoute('rules.chain-flow-all', 'sqlite');
return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end);
}
@@ -984,7 +1118,16 @@ export class StatsService {
return this.db.getRuleProxyMap(backendId);
}
- getRuleProxyMapWithRouting(backendId: number): any {
+ async getRuleProxyMapWithRouting(backendId: number): Promise<any> {
+ if (this.clickHouseReader.shouldUse()) {
+ const ch = await this.clickHouseReader.getRuleProxyMap(backendId);
+ if (ch) {
+ this.recordRoute('rule-proxy-map', 'clickhouse');
+ return ch;
+ }
+ }
+
+ this.failIfStrictFallback('rule-proxy-map');
this.recordRoute('rule-proxy-map', 'sqlite');
return this.db.getRuleProxyMap(backendId);
}
@@ -1272,6 +1415,12 @@ export class StatsService {
}
getRecentConnectionsWithRouting(backendId: number, limit: number): any[] {
+ if (this.clickHouseReader.shouldUse()) {
+ this.recordRoute('connections', 'clickhouse');
+ return this.clickHouseReader.getRecentConnections(backendId, limit);
+ }
+
+ this.failIfStrictFallback('connections');
this.recordRoute('connections', 'sqlite');
return this.db.getRecentConnections(backendId, limit);
}
diff --git a/apps/collector/src/websocket.ts b/apps/collector/src/websocket.ts
index e4c91fb..21144ab 100644
--- a/apps/collector/src/websocket.ts
+++ b/apps/collector/src/websocket.ts
@@ -1304,6 +1304,15 @@ export class StatsWebSocketServer {
return this.clients.size;
}
+ clearBackendCache(backendId: number): void {
+ const cachePrefix = `${backendId}|`;
+ for (const key of this.baseSummaryCache.keys()) {
+ if (key.startsWith(cachePrefix)) {
+ this.baseSummaryCache.delete(key);
+ }
+ }
+ }
+
stop() {
this.clients.forEach((info) => info.ws.close());
this.clients.clear();
diff --git a/apps/web/components/features/backend/backend-config-dialog.tsx b/apps/web/components/features/backend/backend-config-dialog.tsx
index c481a9f..39e51a8 100644
--- a/apps/web/components/features/backend/backend-config-dialog.tsx
+++ b/apps/web/components/features/backend/backend-config-dialog.tsx
@@ -291,6 +291,8 @@ interface AgentBootstrapInfo {
interface DbStats {
size: number;
+ sqliteSize: number;
+ clickhouseSize: number;
totalConnectionsCount: number;
}
@@ -771,7 +773,12 @@ export function BackendConfigDialog({
const loadDbStats = async () => {
try {
const stats = await api.getDbStats();
- setDbStats(stats);
+ setDbStats({
+ size: stats.size,
+ sqliteSize: stats.sqliteSize ?? stats.size,
+ clickhouseSize: stats.clickhouseSize ?? 0,
+ totalConnectionsCount: stats.totalConnectionsCount,
+ });
} catch (error) {
console.error("Failed to load DB stats:", error);
}
@@ -2289,6 +2296,14 @@ export function BackendConfigDialog({
<div className="text-lg font-semibold">
{dbStats ? formatBytes(dbStats.size) : "--"}
</div>
+ <div className="text-[11px] text-muted-foreground mt-1">
+ {dbStats
+ ? t("dbSizeBreakdown", {
+ sqlite: formatBytes(dbStats.sqliteSize),
+ clickhouse: formatBytes(dbStats.clickhouseSize),
+ })
+ : "--"}
+ </div>
</div>
<div className="p-3 rounded-lg bg-muted flex flex-col justify-between h-full">
<div className="text-xs text-muted-foreground mb-1">
diff --git a/apps/web/components/features/stats/stats-cards.tsx b/apps/web/components/features/stats/stats-cards.tsx
index 861e86f..34b9749 100644
--- a/apps/web/components/features/stats/stats-cards.tsx
+++ b/apps/web/components/features/stats/stats-cards.tsx
@@ -3,7 +3,7 @@
import { useRef, useEffect } from "react";
import { Download, Upload, Globe, Activity, Server, Route } from "lucide-react";
import { useTranslations } from "next-intl";
-import { motion, useSpring, useTransform, useMotionValue } from "framer-motion";
+import { animate, motion, useTransform, useMotionValue } from "framer-motion";
import { formatBytes, cn } from "@/lib/utils";
import type { StatsSummary } from "@neko-master/shared";
@@ -16,7 +16,7 @@ interface StatsCardsProps {
// ---------- Animated number display ----------
-const springConfig = { stiffness: 80, damping: 20, mass: 0.5 };
+const animationConfig = { duration: 0.45, ease: [0.22, 1, 0.36, 1] as const };
function AnimatedValue({
value,
@@ -30,18 +30,30 @@ function AnimatedValue({
title?: string;
}) {
const motionValue = useMotionValue(0);
- const spring = useSpring(motionValue, springConfig);
- const display = useTransform(spring, (v) => formatter(Math.round(v)));
+ const display = useTransform(motionValue, (v) => {
+ const safe = Number.isFinite(v) ? Math.max(0, v) : 0;
+ const bounded = Math.min(safe, Number.MAX_SAFE_INTEGER);
+ const rounded = Math.round(bounded);
+ const formatted = formatter(rounded);
+ if (!formatted || formatted.includes("undefined") || formatted.includes("NaN")) {
+ return formatter(0);
+ }
+ return formatted;
+ });
const isFirstRender = useRef(true);
useEffect(() => {
+ const target = Number.isFinite(value) ? Math.max(0, value) : 0;
+
if (isFirstRender.current) {
// Jump to initial value instantly (no animation on mount)
- motionValue.jump(value);
+ motionValue.jump(target);
isFirstRender.current = false;
- } else {
- motionValue.set(value);
+ return;
}
+
+ const controls = animate(motionValue, target, animationConfig);
+ return () => controls.stop();
}, [value, motionValue]);
return (
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index 25f3db8..678f9e7 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -185,6 +185,8 @@ export interface GeoLookupConfig {
const DEFAULT_DB_STATS = {
size: 0,
+ sqliteSize: 0,
+ clickhouseSize: 0,
totalConnectionsCount: 0,
} as const;
@@ -551,7 +553,12 @@ export const api = {
// Database management
getDbStats: async () => {
try {
- return await fetchJson<{ size: number; totalConnectionsCount: number }>(`${API_BASE}/db/stats`);
+ return await fetchJson<{
+ size: number;
+ sqliteSize: number;
+ clickhouseSize: number;
+ totalConnectionsCount: number;
+ }>(`${API_BASE}/db/stats`);
} catch (error) {
if (isApiStatus(error, 404)) {
return { ...DEFAULT_DB_STATS };
diff --git a/apps/web/lib/utils.ts b/apps/web/lib/utils.ts
index 1de7a77..82689a1 100644
--- a/apps/web/lib/utils.ts
+++ b/apps/web/lib/utils.ts
@@ -6,16 +6,22 @@ export function cn(...inputs: ClassValue[]) {
}
export function formatBytes(bytes: number, decimals = 2): string {
- if (!Number.isFinite(bytes) || bytes === 0) return "0 B";
- if (bytes < 0) return `-${formatBytes(-bytes, decimals)}`;
+ const normalizedBytes = Number(bytes);
+ if (!Number.isFinite(normalizedBytes) || normalizedBytes === 0) return "0 B";
+ if (normalizedBytes < 0) return `-${formatBytes(-normalizedBytes, decimals)}`;
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["B", "KB", "MB", "GB", "TB", "PB"];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
+ const exponent = Math.log(normalizedBytes) / Math.log(k);
+ const rawIndex = Number.isFinite(exponent) ? Math.floor(exponent) : 0;
+ const i = rawIndex < 0 ? 0 : Math.min(rawIndex, sizes.length - 1);
+ const unit = sizes[i] ?? "B";
+ const scaled = normalizedBytes / Math.pow(k, i);
+ const safeScaled = Number.isFinite(scaled) ? scaled : 0;
- return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
+ return `${parseFloat(safeScaled.toFixed(dm))} ${unit}`;
}
export function formatNumber(num: number): string {
diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json
index d077087..a0b03b9 100644
--- a/apps/web/messages/en.json
+++ b/apps/web/messages/en.json
@@ -435,7 +435,8 @@
"testFailed": "Connection failed",
"databaseStats": "Database Statistics",
"dbSize": "Database Size",
- "connectionsCount": "Connections Count",
+ "dbSizeBreakdown": "SQLite {sqlite} + ClickHouse {clickhouse}",
+ "connectionsCount": "Traffic Rows",
"clearLogs": "Clear Logs",
"clearLogsDescription": "Clear old connection logs to free up disk space. This action cannot be undone.",
"clear1Day": "Clear 1 day ago",
diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.json
index 8fb2783..8c97563 100644
--- a/apps/web/messages/zh.json
+++ b/apps/web/messages/zh.json
@@ -434,7 +434,8 @@
"testFailed": "连接失败",
"databaseStats": "数据库统计",
"dbSize": "数据库大小",
- "connectionsCount": "连接记录数",
+ "dbSizeBreakdown": "SQLite {sqlite} + ClickHouse {clickhouse}",
+ "connectionsCount": "流量记录数",
"clearLogs": "清理日志",
"clearLogsDescription": "清理旧的连接日志以释放磁盘空间。此操作不可撤销。",
"clear1Day": "清理1天前",