Skip to content

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

feat: Introduce ClickHouse-only write mode and enhance stats query routing with partial data fallback to SQLite and ClickHouse writer row limits.

luoleic35c86cfc918
diff --git a/apps/collector/src/app.ts b/apps/collector/src/app.ts
index 44010a4..324d868 100644
--- a/apps/collector/src/app.ts
+++ b/apps/collector/src/app.ts
@@ -13,6 +13,8 @@ import type { RealtimeStore } from './realtime.js';
import { buildGatewayHeaders, getGatewayBaseUrl, isAgentBackendUrl, parseSurgeRule } from '@neko-master/shared';
import type { TrafficUpdate } from './db.js';
import { SurgePolicySyncService } from './modules/surge/surge-policy-sync.js';
+import { getClickHouseWriter } from './clickhouse-writer.js';
+import { shouldSkipSqliteStatsWrites } from './stats-write-mode.js';
// Import modules
import { BackendService, backendController } from './modules/backend/index.js';
@@ -454,7 +456,14 @@ export async function createApp(options: AppOptions) {
return { success: true, backendId, accepted: 0, dropped: picked.length };
}
- db.batchUpdateTrafficStats(backendId, updates);
+ const clickHouseWriter = getClickHouseWriter();
+ const skipSqliteStatsWrites = shouldSkipSqliteStatsWrites(clickHouseWriter.isEnabled());
+ if (!skipSqliteStatsWrites) {
+ db.batchUpdateTrafficStats(backendId, updates);
+ }
+ if (clickHouseWriter.isEnabled()) {
+ clickHouseWriter.writeTrafficBatch(backendId, updates);
+ }
for (const update of updates) {
realtimeStore.recordTraffic(
backendId,
diff --git a/apps/collector/src/batch-buffer.ts b/apps/collector/src/batch-buffer.ts
index 57b1fa2..be8f519 100644
--- a/apps/collector/src/batch-buffer.ts
+++ b/apps/collector/src/batch-buffer.ts
@@ -7,6 +7,7 @@
import type { StatsDatabase } from "./db.js";
import type { GeoIPService } from "./geo-service.js";
import { getClickHouseWriter } from "./clickhouse-writer.js";
+import { shouldSkipSqliteStatsWrites } from "./stats-write-mode.js";
export interface TrafficUpdate {
domain: string;
@@ -98,6 +99,9 @@ export class BatchBuffer {
logPrefix = "Collector",
): FlushResult {
const clickHouseWriter = getClickHouseWriter();
+ const skipSqliteStatsWrites = shouldSkipSqliteStatsWrites(
+ clickHouseWriter.isEnabled(),
+ );
const updates = Array.from(this.buffer.values());
const geoResults = [...this.geoQueue];
@@ -119,7 +123,10 @@ export class BatchBuffer {
if (updates.length > 0) {
try {
- db.batchUpdateTrafficStats(backendId, updates);
+ const reduceSQLiteWrites = clickHouseWriter.isEnabled() && process.env.CH_DISABLE_SQLITE_REDUCTION !== '1';
+ if (!skipSqliteStatsWrites) {
+ db.batchUpdateTrafficStats(backendId, updates, reduceSQLiteWrites);
+ }
if (clickHouseWriter.isEnabled()) {
clickHouseWriter.writeTrafficBatch(backendId, updates);
}
@@ -148,7 +155,9 @@ export class BatchBuffer {
download: r.download,
timestampMs: r.timestampMs,
}));
- db.batchUpdateCountryStats(backendId, countryUpdates);
+ if (!skipSqliteStatsWrites) {
+ db.batchUpdateCountryStats(backendId, countryUpdates);
+ }
if (clickHouseWriter.isEnabled()) {
clickHouseWriter.writeCountryBatch(backendId, countryUpdates);
}
diff --git a/apps/collector/src/clickhouse-writer.ts b/apps/collector/src/clickhouse-writer.ts
index 1545c76..e650e42 100644
--- a/apps/collector/src/clickhouse-writer.ts
+++ b/apps/collector/src/clickhouse-writer.ts
@@ -22,8 +22,13 @@ class ClickHouseWriter {
10,
Number.parseInt(process.env.CH_WRITE_MAX_PENDING_BATCHES || '200', 10) || 200,
);
+ private readonly maxPendingRows = Math.max(
+ 1000,
+ Number.parseInt(process.env.CH_WRITE_MAX_PENDING_ROWS || '200000', 10) || 200000,
+ );
private writeChain: Promise<void> = Promise.resolve();
private pendingBatches = 0;
+ private pendingRows = 0;
private metricsWindowStartedAt = Date.now();
private metrics = {
trafficBatches: 0,
@@ -58,7 +63,7 @@ class ClickHouseWriter {
connections: 1,
}));
- this.enqueue(() => this.insertRows('traffic_minute', rows, 'traffic'));
+ this.enqueue(() => this.insertRows('traffic_minute', rows, 'traffic'), rows.length);
}
writeCountryBatch(backendId: number, updates: CountryMinuteUpdate[]): void {
@@ -75,20 +80,25 @@ class ClickHouseWriter {
connections: 1,
}));
- this.enqueue(() => this.insertRows('country_minute', rows, 'country'));
+ this.enqueue(() => this.insertRows('country_minute', rows, 'country'), rows.length);
}
- private enqueue(task: () => Promise<void>): void {
- if (this.pendingBatches >= this.maxPendingBatches) {
+ private enqueue(task: () => Promise<void>, rowCount: number): void {
+ const safeRowCount = Math.max(0, rowCount);
+ if (
+ this.pendingBatches >= this.maxPendingBatches ||
+ this.pendingRows + safeRowCount > this.maxPendingRows
+ ) {
this.metrics.failures += 1;
this.maybeLogMetrics();
console.warn(
- `[ClickHouse Writer] Dropped batch because pending queue is full (${this.pendingBatches}/${this.maxPendingBatches})`,
+ `[ClickHouse Writer] Dropped batch because pending queue is full (batches=${this.pendingBatches}/${this.maxPendingBatches}, rows=${this.pendingRows}/${this.maxPendingRows})`,
);
return;
}
this.pendingBatches += 1;
+ this.pendingRows += safeRowCount;
this.writeChain = this.writeChain
.then(() => task())
.catch((error) => {
@@ -97,6 +107,7 @@ class ClickHouseWriter {
})
.finally(() => {
this.pendingBatches = Math.max(0, this.pendingBatches - 1);
+ this.pendingRows = Math.max(0, this.pendingRows - safeRowCount);
});
}
@@ -158,7 +169,7 @@ class ClickHouseWriter {
const elapsedSec = Math.max(1, elapsedMs / 1000);
console.info(
- `[ClickHouse Writer] traffic_batches=${this.metrics.trafficBatches} traffic_rows=${this.metrics.trafficRows} country_batches=${this.metrics.countryBatches} country_rows=${this.metrics.countryRows} failures=${this.metrics.failures} pending_batches=${this.pendingBatches} rows_per_sec=${((this.metrics.trafficRows + this.metrics.countryRows) / elapsedSec).toFixed(1)} window_sec=${elapsedSec.toFixed(1)}`,
+ `[ClickHouse Writer] traffic_batches=${this.metrics.trafficBatches} traffic_rows=${this.metrics.trafficRows} country_batches=${this.metrics.countryBatches} country_rows=${this.metrics.countryRows} failures=${this.metrics.failures} pending_batches=${this.pendingBatches} pending_rows=${this.pendingRows} rows_per_sec=${((this.metrics.trafficRows + this.metrics.countryRows) / elapsedSec).toFixed(1)} window_sec=${elapsedSec.toFixed(1)}`,
);
this.metricsWindowStartedAt = now;
diff --git a/apps/collector/src/database/repositories/traffic-writer.repository.ts b/apps/collector/src/database/repositories/traffic-writer.repository.ts
index 61e0674..b7ced68 100644
--- a/apps/collector/src/database/repositories/traffic-writer.repository.ts
+++ b/apps/collector/src/database/repositories/traffic-writer.repository.ts
@@ -185,7 +185,7 @@ export class TrafficWriterRepository extends BaseRepository {
transaction();
}
- batchUpdateTrafficStats(backendId: number, updates: TrafficUpdate[]) {
+ batchUpdateTrafficStats(backendId: number, updates: TrafficUpdate[], reduceWrites = false) {
if (updates.length === 0) return;
const now = new Date();
@@ -420,30 +420,31 @@ export class TrafficWriterRepository extends BaseRepository {
// Sub-transaction 2: Detail tables + minute/hourly tables
const tx2 = this.db.transaction(() => {
- const ruleDomainStmt = this.db.prepare(`
- INSERT INTO rule_domain_traffic (backend_id, rule, domain, total_upload, total_download, total_connections, last_seen)
- VALUES (@backendId, @rule, @domain, @upload, @download, @count, @timestamp)
- ON CONFLICT(backend_id, rule, domain) DO UPDATE SET
- total_upload = total_upload + @upload, total_download = total_download + @download,
- total_connections = total_connections + @count, last_seen = @timestamp
- `);
- for (const [, data] of ruleDomainMap) { ruleDomainStmt.run({ backendId, rule: data.rule, domain: data.domain, upload: data.upload, download: data.download, count: data.count, timestamp }); }
-
- const ruleIPStmt = this.db.prepare(`
- INSERT INTO rule_ip_traffic (backend_id, rule, ip, total_upload, total_download, total_connections, last_seen)
- VALUES (@backendId, @rule, @ip, @upload, @download, @count, @timestamp)
- ON CONFLICT(backend_id, rule, ip) DO UPDATE SET
- total_upload = total_upload + @upload, total_download = total_download + @download,
- total_connections = total_connections + @count, last_seen = @timestamp
- `);
- for (const [, data] of ruleIPMap) { ruleIPStmt.run({ backendId, rule: data.rule, ip: data.ip, upload: data.upload, download: data.download, count: data.count, timestamp }); }
-
const minuteStmt = this.db.prepare(`
INSERT INTO minute_stats (backend_id, minute, upload, download, connections) VALUES (@backendId, @minute, @upload, @download, @connections)
ON CONFLICT(backend_id, minute) DO UPDATE SET upload = upload + @upload, download = download + @download, connections = connections + @connections
`);
for (const [minute, data] of minuteMap) { minuteStmt.run({ backendId, minute, upload: data.upload, download: data.download, connections: data.connections }); }
+ if (!reduceWrites) {
+ const ruleDomainStmt = this.db.prepare(`
+ INSERT INTO rule_domain_traffic (backend_id, rule, domain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @rule, @domain, @upload, @download, @count, @timestamp)
+ ON CONFLICT(backend_id, rule, domain) DO UPDATE SET
+ total_upload = total_upload + @upload, total_download = total_download + @download,
+ total_connections = total_connections + @count, last_seen = @timestamp
+ `);
+ for (const [, data] of ruleDomainMap) { ruleDomainStmt.run({ backendId, rule: data.rule, domain: data.domain, upload: data.upload, download: data.download, count: data.count, timestamp }); }
+
+ const ruleIPStmt = this.db.prepare(`
+ INSERT INTO rule_ip_traffic (backend_id, rule, ip, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @rule, @ip, @upload, @download, @count, @timestamp)
+ ON CONFLICT(backend_id, rule, ip) DO UPDATE SET
+ total_upload = total_upload + @upload, total_download = total_download + @download,
+ total_connections = total_connections + @count, last_seen = @timestamp
+ `);
+ for (const [, data] of ruleIPMap) { ruleIPStmt.run({ backendId, rule: data.rule, ip: data.ip, upload: data.upload, download: data.download, count: data.count, timestamp }); }
+
const minuteDimStmt = this.db.prepare(`
INSERT INTO minute_dim_stats (backend_id, minute, domain, ip, source_ip, chain, rule, upload, download, connections)
VALUES (@backendId, @minute, @domain, @ip, @sourceIP, @chain, @rule, @upload, @download, @connections)
@@ -490,11 +491,13 @@ export class TrafficWriterRepository extends BaseRepository {
for (const domain of data.domains) { ipProxyDomainStmt.run({ backendId, ip: data.ip, chain: data.chain, domain }); }
}
}
+ }
});
tx2();
// Sub-transaction 3: Device tables
- const tx3 = this.db.transaction(() => {
+ if (!reduceWrites) {
+ const tx3 = this.db.transaction(() => {
const deviceStmt = this.db.prepare(`
INSERT INTO device_stats (backend_id, source_ip, total_upload, total_download, total_connections, last_seen)
VALUES (@backendId, @sourceIP, @upload, @download, @count, @timestamp)
@@ -521,7 +524,8 @@ export class TrafficWriterRepository extends BaseRepository {
total_connections = total_connections + @count, last_seen = @timestamp
`);
for (const [, data] of deviceIPMap) { deviceIPStmt.run({ backendId, sourceIP: data.sourceIP, ip: data.ip, upload: data.upload, download: data.download, count: data.count, timestamp }); }
- });
- tx3();
+ });
+ tx3();
+ }
}
}
diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.ts
index e95ed91..5b76e78 100644
--- a/apps/collector/src/db.ts
+++ b/apps/collector/src/db.ts
@@ -552,7 +552,7 @@ export class StatsDatabase {
// ==================== Traffic Writer ====================
updateTrafficStats(backendId: number, update: TrafficUpdate) { this.repos.trafficWriter.updateTrafficStats(backendId, update); }
- batchUpdateTrafficStats(backendId: number, updates: TrafficUpdate[]) { this.repos.trafficWriter.batchUpdateTrafficStats(backendId, updates); }
+ batchUpdateTrafficStats(backendId: number, updates: TrafficUpdate[], reduceWrites = false) { this.repos.trafficWriter.batchUpdateTrafficStats(backendId, updates, reduceWrites); }
// ==================== Domain ====================
getDomainByName(backendId: number, domain: string) { return this.repos.domain.getDomainByName(backendId, domain); }
diff --git a/apps/collector/src/modules/backend/backend.service.ts b/apps/collector/src/modules/backend/backend.service.ts
index 4d77fe6..05c38d6 100644
--- a/apps/collector/src/modules/backend/backend.service.ts
+++ b/apps/collector/src/modules/backend/backend.service.ts
@@ -351,8 +351,8 @@ export class BackendService {
* Clear all data for a specific backend
*/
async clearBackendData(id: number): Promise<{ message: string }> {
- this.db.deleteBackendData(id);
await this.clearClickHouseBackendData(id);
+ this.db.deleteBackendData(id);
// Also clear realtime cache
this.realtimeStore.clearBackend(id);
this.onBackendDataCleared?.(id);
@@ -377,6 +377,11 @@ export class BackendService {
console.info(`[BackendService] Cleared ClickHouse stats for backend ${backendId}`);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
+ if (config.required || process.env.CH_STRICT_STATS === '1') {
+ throw new Error(
+ `[BackendService] Failed to clear ClickHouse stats for backend ${backendId}: ${message}`,
+ );
+ }
console.warn(
`[BackendService] Failed to clear ClickHouse stats for backend ${backendId}: ${message}`,
);
diff --git a/apps/collector/src/modules/stats/stats.service.test.ts b/apps/collector/src/modules/stats/stats.service.test.ts
index d209565..f29e19b 100644
--- a/apps/collector/src/modules/stats/stats.service.test.ts
+++ b/apps/collector/src/modules/stats/stats.service.test.ts
@@ -202,4 +202,79 @@ describe('StatsService', () => {
})).toBe(false);
});
});
+
+ describe('strict mode routing', () => {
+ it('should use clickhouse for aggregated trend when range is inactive', async () => {
+ const prevStrict = process.env.CH_STRICT_STATS;
+ process.env.CH_STRICT_STATS = '1';
+
+ try {
+ const strictService = new StatsService(db, realtimeStore) as any;
+ strictService.clickHouseReader = {
+ shouldUse: () => true,
+ shouldUseForRange: () => true,
+ getTrafficTrendAggregated: async (
+ _backendId: number,
+ _bucketMinutes: number,
+ start: string,
+ end: string,
+ ) => ([
+ { time: start, upload: 1, download: 2 },
+ { time: end, upload: 3, download: 4 },
+ ]),
+ };
+
+ const result = await strictService.getTrafficTrendAggregatedWithRouting(
+ backendId,
+ { active: false },
+ 30,
+ 1,
+ );
+
+ expect(result.length).toBeGreaterThan(0);
+ } finally {
+ if (prevStrict === undefined) {
+ delete process.env.CH_STRICT_STATS;
+ } else {
+ process.env.CH_STRICT_STATS = prevStrict;
+ }
+ }
+ });
+ });
+
+ describe('summary routing consistency', () => {
+ it('should fallback the whole summary response to sqlite when clickhouse results are partial', async () => {
+ seedTraffic();
+
+ const now = Date.now();
+ const partialService = new StatsService(db, realtimeStore) as any;
+ partialService.clickHouseReader = {
+ shouldUseForRange: () => true,
+ getSummary: async () => ({
+ totalConnections: 999999,
+ totalUpload: 999999,
+ totalDownload: 999999,
+ uniqueDomains: 999999,
+ uniqueIPs: 999999,
+ }),
+ getTopDomainsLight: async () => null,
+ getTopIPsLight: async () => [],
+ getProxyStats: async () => [],
+ getRuleStats: async () => [],
+ getHourlyStats: async () => [],
+ getTrafficInRange: async () => ({ upload: 999999, download: 999999 }),
+ };
+
+ const result = await partialService.getSummaryWithRouting(backendId, {
+ active: true,
+ start: new Date(now - 60_000).toISOString(),
+ end: new Date(now + 60_000).toISOString(),
+ });
+
+ expect(result.totalUpload).toBe(800);
+ expect(result.totalDownload).toBe(5300);
+ expect(result.totalDomains).toBe(3);
+ expect(result.totalIPs).toBe(3);
+ });
+ });
});
diff --git a/apps/collector/src/modules/stats/stats.service.ts b/apps/collector/src/modules/stats/stats.service.ts
index 7cb893d..a716ee4 100644
--- a/apps/collector/src/modules/stats/stats.service.ts
+++ b/apps/collector/src/modules/stats/stats.service.ts
@@ -67,6 +67,32 @@ export class StatsService {
return this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end);
}
+ private buildRelativeRange(windowMinutes: number): { start: string; end: string } {
+ const safeWindowMinutes = Math.max(1, Math.floor(windowMinutes));
+ const end = new Date();
+ const start = new Date(end.getTime() - safeWindowMinutes * 60_000);
+ return {
+ start: start.toISOString(),
+ end: end.toISOString(),
+ };
+ }
+
+ private resolveQueryRange(
+ timeRange: TimeRange,
+ fallbackWindowMinutes: number,
+ ): { start: string; end: string } | null {
+ if (timeRange.active) {
+ if (!timeRange.start || !timeRange.end) {
+ return null;
+ }
+ return {
+ start: timeRange.start,
+ end: timeRange.end,
+ };
+ }
+ return this.buildRelativeRange(fallbackWindowMinutes);
+ }
+
private isStrictStatsEnabled(): boolean {
return this.strictStats && this.clickHouseReader.shouldUse();
}
@@ -292,60 +318,60 @@ export class StatsService {
),
]);
- const summary =
- summaryCH || this.db.getSummary(backendId, timeRange.start, timeRange.end);
+ const allCHReady =
+ !!summaryCH &&
+ !!topDomainsCH &&
+ !!topIPsCH &&
+ !!proxyStatsCH &&
+ !!ruleStatsCH &&
+ !!hourlyStatsCH &&
+ !!trafficInRangeCH;
+ if (!allCHReady) {
+ const hasAnyCH =
+ !!summaryCH ||
+ !!topDomainsCH ||
+ !!topIPsCH ||
+ !!proxyStatsCH ||
+ !!ruleStatsCH ||
+ !!hourlyStatsCH ||
+ !!trafficInRangeCH;
+ if (hasAnyCH) {
+ console.warn(
+ '[StatsService] Partial ClickHouse summary data detected, falling back to SQLite for consistency',
+ );
+ }
+ this.failIfStrictFallback('summary');
+ this.recordRoute('summary', 'sqlite');
+ return this.getSummary(backendId, timeRange);
+ }
+
+ const summary = summaryCH;
const summaryWithRealtime = includeRealtime
? this.realtimeStore.applySummaryDelta(backendId, summary)
: summary;
- const dbTopDomains =
- topDomainsCH ||
- this.db.getTopDomainsLight(backendId, 10, timeRange.start, timeRange.end);
const topDomains = includeRealtime
- ? this.realtimeStore.mergeTopDomains(backendId, dbTopDomains, 10)
- : dbTopDomains;
+ ? this.realtimeStore.mergeTopDomains(backendId, topDomainsCH, 10)
+ : topDomainsCH;
- const dbTopIPs =
- topIPsCH || this.db.getTopIPsLight(backendId, 10, timeRange.start, timeRange.end);
const topIPs = includeRealtime
- ? this.realtimeStore.mergeTopIPs(backendId, dbTopIPs, 10)
- : dbTopIPs;
+ ? this.realtimeStore.mergeTopIPs(backendId, topIPsCH, 10)
+ : topIPsCH;
- const dbProxyStats =
- proxyStatsCH ||
- this.db.getProxyStats(backendId, timeRange.start, timeRange.end);
const proxyStats = includeRealtime
- ? this.realtimeStore.mergeProxyStats(backendId, dbProxyStats)
- : dbProxyStats;
+ ? this.realtimeStore.mergeProxyStats(backendId, proxyStatsCH)
+ : proxyStatsCH;
- const dbRuleStats =
- ruleStatsCH ||
- this.db.getRuleStats(backendId, timeRange.start, timeRange.end);
const ruleStats = includeRealtime
- ? this.realtimeStore.mergeRuleStats(backendId, dbRuleStats)
- : dbRuleStats;
+ ? this.realtimeStore.mergeRuleStats(backendId, ruleStatsCH)
+ : ruleStatsCH;
- const hourlyStats =
- hourlyStatsCH ||
- this.db.getHourlyStats(backendId, 24, timeRange.start, timeRange.end);
- const todayTraffic =
- trafficInRangeCH ||
- this.db.getTrafficInRange(backendId, timeRange.start, timeRange.end);
+ const hourlyStats = hourlyStatsCH;
+ const todayTraffic = trafficInRangeCH;
const todayDelta = includeRealtime
? this.realtimeStore.getTodayDelta(backendId)
: { upload: 0, download: 0 };
- const usedCH =
- !!summaryCH ||
- !!topDomainsCH ||
- !!topIPsCH ||
- !!proxyStatsCH ||
- !!ruleStatsCH ||
- !!hourlyStatsCH ||
- !!trafficInRangeCH;
- if (!usedCH) {
- this.failIfStrictFallback('summary');
- }
- this.recordRoute('summary', usedCH ? 'clickhouse' : 'sqlite');
+ this.recordRoute('summary', 'clickhouse');
return {
backend: {
@@ -1297,21 +1323,24 @@ export class StatsService {
timeRange: TimeRange,
hours: number,
): Promise<HourlyStats[]> {
+ const queryRange = this.resolveQueryRange(timeRange, Math.max(1, hours) * 60);
const shouldUseCH =
- timeRange.active &&
- this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end);
- if (shouldUseCH && timeRange.start && timeRange.end) {
+ !!queryRange &&
+ this.clickHouseReader.shouldUseForRange(queryRange.start, queryRange.end);
+ if (shouldUseCH && queryRange) {
const chStats = await this.clickHouseReader.getHourlyStats(
backendId,
hours,
- timeRange.start,
- timeRange.end,
+ queryRange.start,
+ queryRange.end,
);
if (chStats) {
this.recordRoute('hourly', 'clickhouse');
return chStats;
}
}
+
+ this.failIfStrictFallback('hourly');
this.recordRoute('hourly', 'sqlite');
return this.db.getHourlyStats(backendId, hours, timeRange.start, timeRange.end);
}
@@ -1332,21 +1361,25 @@ export class StatsService {
timeRange: TimeRange,
minutes: number,
): Promise<TrafficTrendPoint[]> {
+ const queryRange = this.resolveQueryRange(timeRange, Math.max(1, minutes));
const shouldUseCH =
- timeRange.active &&
- this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end);
+ !!queryRange &&
+ this.clickHouseReader.shouldUseForRange(queryRange.start, queryRange.end);
const chBase =
- shouldUseCH && timeRange.start && timeRange.end
+ shouldUseCH && queryRange
? await this.clickHouseReader.getTrafficTrend(
backendId,
- timeRange.start,
- timeRange.end,
+ queryRange.start,
+ queryRange.end,
)
: null;
const base =
chBase ||
this.db.getTrafficTrend(backendId, minutes, timeRange.start, timeRange.end);
+ if (!chBase) {
+ this.failIfStrictFallback('trend');
+ }
this.recordRoute('trend', chBase ? 'clickhouse' : 'sqlite');
if (!this.shouldIncludeRealtime(timeRange)) {
@@ -1377,17 +1410,18 @@ export class StatsService {
minutes: number,
bucketMinutes: number,
): Promise<TrafficTrendPoint[]> {
+ const queryRange = this.resolveQueryRange(timeRange, Math.max(1, minutes));
const shouldUseCH =
- timeRange.active &&
- this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end);
+ !!queryRange &&
+ this.clickHouseReader.shouldUseForRange(queryRange.start, queryRange.end);
const chBase =
- shouldUseCH && timeRange.start && timeRange.end
+ shouldUseCH && queryRange
? await this.clickHouseReader.getTrafficTrendAggregated(
backendId,
bucketMinutes,
- timeRange.start,
- timeRange.end,
+ queryRange.start,
+ queryRange.end,
)
: null;
const base =
@@ -1399,6 +1433,9 @@ export class StatsService {
timeRange.start,
timeRange.end,
);
+ if (!chBase) {
+ this.failIfStrictFallback('trend.aggregated');
+ }
this.recordRoute('trend.aggregated', chBase ? 'clickhouse' : 'sqlite');
if (!this.shouldIncludeRealtime(timeRange)) {
diff --git a/apps/collector/src/stats-write-mode.test.ts b/apps/collector/src/stats-write-mode.test.ts
new file mode 100644
index 0000000..9d05bc5
--- /dev/null
+++ b/apps/collector/src/stats-write-mode.test.ts
@@ -0,0 +1,43 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+describe('stats-write-mode', () => {
+ const prevMode = process.env.CH_ONLY_MODE;
+
+ beforeEach(() => {
+ vi.resetModules();
+ delete process.env.CH_ONLY_MODE;
+ });
+
+ afterEach(() => {
+ if (prevMode === undefined) {
+ delete process.env.CH_ONLY_MODE;
+ } else {
+ process.env.CH_ONLY_MODE = prevMode;
+ }
+ vi.restoreAllMocks();
+ });
+
+ it('should keep sqlite writes when CH_ONLY_MODE is disabled', async () => {
+ const mode = await import('./stats-write-mode.js');
+ expect(mode.shouldSkipSqliteStatsWrites(true)).toBe(false);
+ expect(mode.shouldSkipSqliteStatsWrites(false)).toBe(false);
+ });
+
+ it('should keep sqlite writes and warn when writer is disabled', async () => {
+ process.env.CH_ONLY_MODE = '1';
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const mode = await import('./stats-write-mode.js');
+
+ expect(mode.shouldSkipSqliteStatsWrites(false)).toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ });
+
+ it('should skip sqlite writes when writer is enabled', async () => {
+ process.env.CH_ONLY_MODE = '1';
+ const info = vi.spyOn(console, 'info').mockImplementation(() => {});
+ const mode = await import('./stats-write-mode.js');
+
+ expect(mode.shouldSkipSqliteStatsWrites(true)).toBe(true);
+ expect(info).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/collector/src/stats-write-mode.ts b/apps/collector/src/stats-write-mode.ts
new file mode 100644
index 0000000..6daa3d7
--- /dev/null
+++ b/apps/collector/src/stats-write-mode.ts
@@ -0,0 +1,31 @@
+let warnedMissingWriter = false;
+let warnedEnabled = false;
+
+export function isClickHouseOnlyModeEnabled(): boolean {
+ return process.env.CH_ONLY_MODE === '1';
+}
+
+export function shouldSkipSqliteStatsWrites(clickHouseWriterEnabled: boolean): boolean {
+ if (!isClickHouseOnlyModeEnabled()) {
+ return false;
+ }
+
+ if (!clickHouseWriterEnabled) {
+ if (!warnedMissingWriter) {
+ warnedMissingWriter = true;
+ console.warn(
+ '[Stats Write Mode] CH_ONLY_MODE=1 but CH writer is disabled; keep SQLite writes to avoid data loss',
+ );
+ }
+ return false;
+ }
+
+ if (!warnedEnabled) {
+ warnedEnabled = true;
+ console.info(
+ '[Stats Write Mode] CH_ONLY_MODE=1 enabled; skip SQLite traffic/country stats writes',
+ );
+ }
+
+ return true;
+}
diff --git a/docs/clickhouse-review-report.md b/docs/clickhouse-review-report.md
new file mode 100644
index 0000000..ba33c65
--- /dev/null
+++ b/docs/clickhouse-review-report.md
@@ -0,0 +1,60 @@
+# ClickHouse 改造代码评审与性能分析报告
+
+## 1. 业务流程与数据全链路分析
+
+在引入 ClickHouse 之前,系统的数据链路为:
+**Agent / 采集端** -> `BatchBuffer` (内存聚合) -> `SQLite` (全量写入与查询)。
+在此模型下,所有高频的分钟级、小时级聚合数据(`minute_dim_stats`, `domain_stats` 等)均在 SQLite 中进行 UPSERT 操作。虽然在 `main` 分支后期已经引入了 `BatchBuffer` 内存批处理并在 SQLite 中启用了 `WAL` 模式与 `synchronous = NORMAL` 来降低写盘频率,但在面对极其庞大的并发连接数与海量分析查询时,SQLite 的读写锁竞争(读者阻塞写者或写者阻塞读者)仍然会导致性能瓶颈,尤其是管理面板进行复杂的多维度关联查询(如 `getDomainStatsPaginated`, `getRuleChainFlow`)时会消耗大量磁盘 I/O 和 CPU。
+
+**引入 ClickHouse 后的新链路:**
+**Agent / 采集端** -> `BatchBuffer` -> **双写路由**:
+1. **持久化与实时状态 (SQLite)**:仍然写入 SQLite,保障系统无缝降级与核心关系型状态存在。
+2. **海量分析数据存储 (ClickHouse)**:通过 `ClickHouseWriter` 异步缓冲并批量写入 ClickHouse(`traffic_minute` 和 `country_minute` 表)。
+
+**查询链路改造 (`StatsService`)**:
+实现了读写分离。所有的厚重统计或大范围时间范围的查询通过 `StatsService.shouldUseClickHouse()` 判断,将读请求路由至 `ClickHouseReader`,由 ClickHouse 这类具有强力 MPP 架构的列式数据库承担聚合(SummingMergeTree)与过滤计算,并与 `RealtimeStore` 中的最新分钟内存数据进行合并(Merge)。这极大解放了 SQLite 的读压力。
+
+## 2. 性能提升分析(缓解硬盘 I/O 问题)
+
+**通过本次改造,确实能够显著缓解原先 SQLite 的硬盘 I/O 读盘过多及锁竞争问题:**
+1. **读写分离**:最消耗 I/O 的是管理界面的数据分析图表(如几十万行的流量表聚合)。将其转移至 ClickHouse 查询,使得 SQLite 的核心任务变成了单一的追加更新,不再因为大量的随机读查询导致 Page Cache 频繁换页和磁盘暴增。
+2. **聚合机制的改变**:ClickHouse 使用了 `SummingMergeTree` 引擎。对于分析型数据,ClickHouse 通过后台 `Merge` 异步聚合 `upload`, `download`, `connections` 数据,而非像 SQLite 在每次 Insert 时执行高昂的 `ON CONFLICT DO UPDATE` B-Tree 更新。
+3. **批量插入容错**:`ClickHouseWriter` 实现了严格的队列管控(`maxPendingBatches`),并在满载时丢弃旧批次记录至 `metrics.failures`,这是非常科学的监控系统降级策略,能在遭遇极其严重的 I/O 风暴时保护 Node.js 主进程不因 OOM 崩溃。
+
+## 3. 具体源码 Review 与潜在优化点
+
+### 3.1 优秀设计
+- **ClickHouseWriter 的任务链式控制**:使用了基于 `Promise.then` 的 `writeChain` 进行串行批量写入,并在队列堆积超过 `maxPendingBatches` 时主动丢弃数据。避免了并发 POST 请求压垮下游。
+- **Realtime 实时补偿**:虽然查询走 ClickHouse,但依然使用 `includeRealtime` 和 `realtimeStore` 补偿最新一分钟的数据延迟,巧妙地规避了 ClickHouse 即时查询能力相对较弱的缺点。
+- **降级与容灾容错**:`StatsService` 中实现了自动 Fallback。当 ClickHouse `CH_STRICT_STATS` 没开启时,ClickHouse 若查询失败会降级到 SQLite(通过捕获或空值兜底)。
+
+### 3.2 潜在隐患与可优化点(依据最新复核更新)
+
+在详细审查代码后,发现了以下几个细节可以进一步优化与加固:
+
+1. **路由结果合并产生的非原子回退 (StatsService)**:[中优先度修复]
+ 在 `getSummaryWithRouting` 并发查询多个 ClickHouse 指标时,当前代码是逐项执行 `|| this.db.get...`:
+ ```typescript
+ const summary = summaryCH || this.db.getSummary(...);
+ const dbTopDomains = topDomainsCH || this.db.getTopDomainsLight(...);
+ ```
+ 如果中间某个 ClickHouse 并发请求(如 topDomainsCH)因为偶发的超时返回 null,它会立即单点 Fallback 到读 SQLite。由于 SQLite 和 ClickHouse 是异步落库的,这会导致在同一个 Dashboard 上展示的汇总数据(使用 ClickHouse 的值)和下方的 Top 列表(使用 SQLite 的值)出现时间窗口上的数据不一致。建议改为**原子回退**(如果任一 ClickHouse 关键查询失败,则整体降级为使用 SQLite 数据)。
+
+2. **双写造成的 SQLite 写放大 (BatchBuffer)**:[中优先度修复]
+ **问题表现**:虽然 ClickHouse 承担了查询,当前的 `BatchBuffer` 依旧会将全部监控流水全量写往 SQLite 的几十张表中(如 `minute_dim_stats` 等)。SQLite 的写放大和 I/O 更新依然存在。
+ **建议**:在确保 ClickHouse 稳定的前提下,可以**有条件地减少 SQLite 写负载**(例如关闭对部分高频明细分析表的 SQLite UPSERT)。**注意**:目前不建议一刀切彻底关闭 SQLite 统计写入(不宜直接做全局 CH_ONLY_MODE),因为例如当 `timeRange.active=false` 时,默认路由依然会读取 SQLite `getSummary`,若彻底停写 SQLite 会引发功能回退与数据缺失。
+
+3. **ClickHouseWriter 的内存压力风险 (非内存泄漏)**:[低优先度关注]
+ 在 `clickhouse-writer.ts` 中,数据被压入 `writeChain` 队列。虽然代码中已通过 `maxPendingBatches`(默认 200)设定了内存堆积上限,并不会导致无限增长(即不算内存泄漏)。但在极端大批次数据到来且下游 ClickHouse 卡顿时,200 个满载 Batch 驻留中仍会给 V8 引擎带来可观的内存堆积压力。
+
+4. **ClickHouse 查询的参数化加固 (ClickHouseReader)**:[低优先度关注]
+ 在 `clickhouse-reader.ts` 中,字符串拼接目前使用了简单的 `this.esc` 进行单引号转义,这在大多数场景下能够防注入。但为了获得绝对的稳定与防误截断能力,长远看更为稳妥的方案是引入 ClickHouse 官方的**参数化查询 (Parameterized Queries)**,将其作为后续代码加固的一个防线。
+
+## 4. 结论与总结
+
+本次向 ClickHouse 的技术栈扩展是非常成功的重构。它架构清晰地完成了:
+- **流量路由分离**:通过 `StatsService` 的中间层拦截。
+- **高并发写入优化**:利用了 ClickHouse 的批量与合并树能力。
+- **历史瓶颈解放**:极大地减轻了管理面板刷新的延迟。
+
+**实施建议**:可以在近期版本上线。后续的演进建议按优先级处理:首要修复 `getSummaryWithRouting` 的非原子回退导致的页面数据不一致,随后在保障默认查询可用性的前提下,逐步有条件地精简 SQLite 的冗余双写,以彻底追求极致的 I/O 解放。代码整体结构严谨,无明显的语法与业务流阻断错误。