Skip to content

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

feat: Implement connection counting for country traffic and introduce runtime state clearing for collectors to ensure accurate traffic aggregation.

luoleicb8a59a7ec9b
diff --git a/apps/collector/src/database/repositories/country.repository.ts b/apps/collector/src/database/repositories/country.repository.ts
index 8820a3e..04130d0 100644
--- a/apps/collector/src/database/repositories/country.repository.ts
+++ b/apps/collector/src/database/repositories/country.repository.ts
@@ -77,15 +77,36 @@ export class CountryRepository extends BaseRepository {
return stmt.all(backendId, limit) as CountryStatsRow[];
}
- updateCountryStats(backendId: number, country: string, countryName: string, continent: string, upload: number, download: number, timestampMs?: number): void {
+ updateCountryStats(
+ backendId: number,
+ country: string,
+ countryName: string,
+ continent: string,
+ upload: number,
+ download: number,
+ timestampMs?: number,
+ connections = 1,
+ ): void {
+ const normalizedConnections = Math.max(0, Math.floor(connections));
const stmt = this.db.prepare(`
INSERT INTO country_stats (backend_id, country, country_name, continent, total_upload, total_download, total_connections, last_seen)
- VALUES (?, ?, ?, ?, ?, ?, 1, CURRENT_TIMESTAMP)
+ VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(backend_id, country) DO UPDATE SET
total_upload = total_upload + ?, total_download = total_download + ?,
- total_connections = total_connections + 1, last_seen = CURRENT_TIMESTAMP
+ total_connections = total_connections + ?, last_seen = CURRENT_TIMESTAMP
`);
- stmt.run(backendId, country, countryName, continent, upload, download, upload, download);
+ stmt.run(
+ backendId,
+ country,
+ countryName,
+ continent,
+ upload,
+ download,
+ normalizedConnections,
+ upload,
+ download,
+ normalizedConnections,
+ );
const now = new Date(timestampMs ?? Date.now());
const minute = this.toMinuteKey(now);
@@ -93,31 +114,55 @@ export class CountryRepository extends BaseRepository {
this.db.prepare(`
INSERT INTO minute_country_stats (backend_id, minute, country, country_name, continent, upload, download, connections)
- VALUES (?, ?, ?, ?, ?, ?, ?, 1)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(backend_id, minute, country) DO UPDATE SET
- upload = upload + ?, download = download + ?, connections = connections + 1
- `).run(backendId, minute, country, countryName, continent, upload, download, upload, download);
+ upload = upload + ?, download = download + ?, connections = connections + ?
+ `).run(
+ backendId,
+ minute,
+ country,
+ countryName,
+ continent,
+ upload,
+ download,
+ normalizedConnections,
+ upload,
+ download,
+ normalizedConnections,
+ );
this.db.prepare(`
INSERT INTO hourly_country_stats (backend_id, hour, country, country_name, continent, upload, download, connections)
- VALUES (?, ?, ?, ?, ?, ?, ?, 1)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(backend_id, hour, country) DO UPDATE SET
- upload = upload + ?, download = download + ?, connections = connections + 1
- `).run(backendId, hour, country, countryName, continent, upload, download, upload, download);
+ upload = upload + ?, download = download + ?, connections = connections + ?
+ `).run(
+ backendId,
+ hour,
+ country,
+ countryName,
+ continent,
+ upload,
+ download,
+ normalizedConnections,
+ upload,
+ download,
+ normalizedConnections,
+ );
}
batchUpdateCountryStats(backendId: number, results: Array<{
country: string; countryName: string; continent: string;
- upload: number; download: number; timestampMs?: number;
+ upload: number; download: number; connections?: number; timestampMs?: number;
}>): void {
if (results.length === 0) return;
const cumulativeStmt = this.db.prepare(`
INSERT INTO country_stats (backend_id, country, country_name, continent, total_upload, total_download, total_connections, last_seen)
- VALUES (?, ?, ?, ?, ?, ?, 1, CURRENT_TIMESTAMP)
+ VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(backend_id, country) DO UPDATE SET
total_upload = total_upload + ?, total_download = total_download + ?,
- total_connections = total_connections + 1, last_seen = CURRENT_TIMESTAMP
+ total_connections = total_connections + ?, last_seen = CURRENT_TIMESTAMP
`);
const minuteStmt = this.db.prepare(`
@@ -145,7 +190,19 @@ export class CountryRepository extends BaseRepository {
}>();
for (const r of results) {
- cumulativeStmt.run(backendId, r.country, r.countryName, r.continent, r.upload, r.download, r.upload, r.download);
+ const connections = Math.max(0, Math.floor(r.connections ?? 1));
+ cumulativeStmt.run(
+ backendId,
+ r.country,
+ r.countryName,
+ r.continent,
+ r.upload,
+ r.download,
+ connections,
+ r.upload,
+ r.download,
+ connections,
+ );
const now = new Date(r.timestampMs ?? Date.now());
const minute = this.toMinuteKey(now);
const hour = this.toHourKey(now);
@@ -155,9 +212,9 @@ export class CountryRepository extends BaseRepository {
if (existing) {
existing.upload += r.upload;
existing.download += r.download;
- existing.connections++;
+ existing.connections += connections;
} else {
- minuteMap.set(minuteKey, { minute, country: r.country, countryName: r.countryName, continent: r.continent, upload: r.upload, download: r.download, connections: 1 });
+ minuteMap.set(minuteKey, { minute, country: r.country, countryName: r.countryName, continent: r.continent, upload: r.upload, download: r.download, connections });
}
const hourlyKey = `${hour}:${r.country}`;
@@ -165,9 +222,9 @@ export class CountryRepository extends BaseRepository {
if (existingHourly) {
existingHourly.upload += r.upload;
existingHourly.download += r.download;
- existingHourly.connections++;
+ existingHourly.connections += connections;
} else {
- hourlyMap.set(hourlyKey, { hour, country: r.country, countryName: r.countryName, continent: r.continent, upload: r.upload, download: r.download, connections: 1 });
+ hourlyMap.set(hourlyKey, { hour, country: r.country, countryName: r.countryName, continent: r.continent, upload: r.upload, download: r.download, connections });
}
}
diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.ts
index 56d0646..7b61223 100644
--- a/apps/collector/src/index.ts
+++ b/apps/collector/src/index.ts
@@ -90,6 +90,11 @@ async function main() {
wsServer.broadcastStats(backendId);
},
(backendId: number) => {
+ const collector = collectors.get(backendId) as
+ | (GatewayCollector & { clearRuntimeState?: () => void })
+ | (SurgeCollector & { clearRuntimeState?: () => void })
+ | undefined;
+ collector?.clearRuntimeState?.();
wsServer.clearBackendCache(backendId);
wsServer.broadcastStats(backendId, true);
},
diff --git a/apps/collector/src/modules/app/app.ts b/apps/collector/src/modules/app/app.ts
index 6ef6603..ab3bad5 100644
--- a/apps/collector/src/modules/app/app.ts
+++ b/apps/collector/src/modules/app/app.ts
@@ -16,6 +16,7 @@ import type { TrafficUpdate } from '../db/db.js';
import { SurgePolicySyncService } from '../surge/surge-policy-sync.js';
import type { GeoIPService } from '../geo/geo.service.js';
import { BatchBuffer } from '../collector/batch-buffer.js';
+import { TrafficWriteError } from '../clickhouse/clickhouse.writer.js';
// Import modules
import { BackendService, backendController } from '../backend/index.js';
@@ -30,6 +31,8 @@ declare module 'fastify' {
realtimeStore: RealtimeStore;
backendService: BackendService;
statsService: StatsService;
+ clearAgentRuntimeState?: (backendId?: number) => void;
+ notifyBackendDataCleared?: (backendId: number) => void;
}
}
@@ -130,52 +133,70 @@ export async function createApp(options: AppOptions) {
// interval. Ensures each connection contributes connections=1 exactly once per flush
// interval, consistent with direct mode's countedConnectionIds deduplication.
const agentCountedByBackend = new Map<number, Set<string>>();
+ // Per-backend flush lock — mirrors direct mode's isFlushing to prevent a slow CH write
+ // from letting the next timer tick start a second flush before clearTraffic completes.
+ const agentIsFlushing = new Map<number, boolean>();
const AGENT_FLUSH_INTERVAL_MS = Math.max(
5_000,
Number.parseInt(process.env.AGENT_FLUSH_INTERVAL_MS || '30000', 10) || 30_000,
);
const flushAgentBuffer = async (backendId: number, buffer: BatchBuffer) => {
- if (!buffer.hasPending()) return;
- const stats = buffer.flush(db, geoService, backendId, 'Agent');
+ if (agentIsFlushing.get(backendId) || !buffer.hasPending()) return;
- let trafficDetailOk = true;
- let trafficAggOk = true;
- if (stats.pendingTrafficWrite) {
- try {
- const outcome = await stats.pendingTrafficWrite;
- trafficDetailOk = outcome.detailOk;
- trafficAggOk = outcome.aggOk;
- } catch {
- trafficDetailOk = false;
- trafficAggOk = false;
+ agentIsFlushing.set(backendId, true);
+ try {
+ const stats = buffer.flush(db, geoService, backendId, 'Agent');
+
+ let trafficDetailOk = true;
+ let trafficAggOk = true;
+ if (stats.pendingTrafficWrite) {
+ try {
+ const outcome = await stats.pendingTrafficWrite;
+ trafficDetailOk = outcome.detailOk;
+ trafficAggOk = outcome.aggOk;
+ } catch (err) {
+ if (err instanceof TrafficWriteError) {
+ trafficDetailOk = err.detailOk;
+ trafficAggOk = err.aggOk;
+ } else {
+ trafficDetailOk = false;
+ trafficAggOk = false;
+ }
+ console.warn(
+ `[Agent:${backendId}] ClickHouse traffic write failed detail_ok=${trafficDetailOk} agg_ok=${trafficAggOk}`,
+ err,
+ );
+ }
}
- }
- if (stats.hasTrafficUpdates && stats.trafficOk) {
- if (trafficDetailOk && trafficAggOk) {
- realtimeStore.clearTraffic(backendId);
- agentCountedByBackend.delete(backendId);
- } else if (trafficDetailOk && !trafficAggOk) {
- realtimeStore.clearTrafficDimensions(backendId);
- agentCountedByBackend.delete(backendId);
- } else if (!trafficDetailOk && trafficAggOk) {
- realtimeStore.clearTrafficSummary(backendId);
- agentCountedByBackend.delete(backendId);
+ if (stats.hasTrafficUpdates && stats.trafficOk) {
+ if (trafficDetailOk && trafficAggOk) {
+ realtimeStore.clearTraffic(backendId);
+ agentCountedByBackend.delete(backendId);
+ } else if (trafficDetailOk && !trafficAggOk) {
+ realtimeStore.clearTrafficDimensions(backendId);
+ agentCountedByBackend.delete(backendId);
+ } else if (!trafficDetailOk && trafficAggOk) {
+ realtimeStore.clearTrafficSummary(backendId);
+ agentCountedByBackend.delete(backendId);
+ }
}
- }
- let countryWriteOk = true;
- if (stats.pendingCountryWrite) {
- try {
- await stats.pendingCountryWrite;
- } catch {
- countryWriteOk = false;
+ let countryWriteOk = true;
+ if (stats.pendingCountryWrite) {
+ try {
+ await stats.pendingCountryWrite;
+ } catch {
+ countryWriteOk = false;
+ }
}
- }
- if (stats.hasCountryUpdates && stats.countryOk && countryWriteOk) {
- realtimeStore.clearCountries(backendId);
+ if (stats.hasCountryUpdates && stats.countryOk && countryWriteOk) {
+ realtimeStore.clearCountries(backendId);
+ }
+ } finally {
+ agentIsFlushing.set(backendId, false);
}
};
@@ -186,6 +207,22 @@ export async function createApp(options: AppOptions) {
});
}
}, AGENT_FLUSH_INTERVAL_MS);
+ const clearAgentRuntimeState = (backendId?: number) => {
+ if (backendId !== undefined) {
+ agentBatchBuffers.get(backendId)?.clear();
+ agentBatchBuffers.delete(backendId);
+ agentCountedByBackend.delete(backendId);
+ agentIsFlushing.delete(backendId);
+ return;
+ }
+
+ for (const buffer of agentBatchBuffers.values()) {
+ buffer.clear();
+ }
+ agentBatchBuffers.clear();
+ agentCountedByBackend.clear();
+ agentIsFlushing.clear();
+ };
const REQUEST_ID_TTL_MS = 5 * 60 * 1000;
function isDuplicateRequestId(id: string): boolean {
const now = Date.now();
@@ -241,6 +278,11 @@ export async function createApp(options: AppOptions) {
app.decorate('authService', authService);
app.decorate('db', db);
app.decorate('realtimeStore', realtimeStore);
+ app.decorate('clearAgentRuntimeState', clearAgentRuntimeState);
+ app.decorate(
+ 'notifyBackendDataCleared',
+ (backendId: number) => onBackendDataCleared?.(backendId),
+ );
const getBackendIdFromQuery = (query: Record<string, unknown>): number | null => {
const backendId = typeof query.backendId === 'string' ? query.backendId : undefined;
@@ -622,8 +664,9 @@ export async function createApp(options: AppOptions) {
}
for (const update of updates) {
- // Connection key matches BatchBuffer's deduplication dimensions (minus minuteKey).
- const connectionKey = `${update.domain}:${update.ip}:${update.chains.join(' > ')}:${update.sourceIP || ''}`;
+ // Connection key matches BatchBuffer's deduplication dimensions (minus minuteKey):
+ // domain, ip, full chain, rule, rulePayload, sourceIP.
+ const connectionKey = `${update.domain}:${update.ip}:${update.chains.join(' > ')}:${update.rule}:${update.rulePayload}:${update.sourceIP || ''}`;
const isNewThisFlush = !agentCounted.has(connectionKey);
agentCounted.add(connectionKey);
@@ -708,6 +751,7 @@ export async function createApp(options: AppOptions) {
geo: r.geo,
upload: r.stats.upload,
download: r.stats.download,
+ connections: r.stats.connections,
timestampMs: r.stats.timestampMs,
});
}
diff --git a/apps/collector/src/modules/clickhouse/clickhouse.writer.ts b/apps/collector/src/modules/clickhouse/clickhouse.writer.ts
index 60690b8..3e5b738 100644
--- a/apps/collector/src/modules/clickhouse/clickhouse.writer.ts
+++ b/apps/collector/src/modules/clickhouse/clickhouse.writer.ts
@@ -7,6 +7,7 @@ interface CountryMinuteUpdate {
continent: string;
upload: number;
download: number;
+ connections?: number;
timestampMs?: number;
}
@@ -131,7 +132,7 @@ export class ClickHouseWriter {
continent: item.continent || '',
upload: Math.max(0, Math.floor(item.upload)),
download: Math.max(0, Math.floor(item.download)),
- connections: 1,
+ connections: Math.max(0, Math.floor(item.connections ?? 1)),
}));
return this.enqueue(() => this.insertRows('country_buffer', rows, 'country'), rows.length);
diff --git a/apps/collector/src/modules/collector/batch-buffer.ts b/apps/collector/src/modules/collector/batch-buffer.ts
index a8ed0a8..1d2d52c 100644
--- a/apps/collector/src/modules/collector/batch-buffer.ts
+++ b/apps/collector/src/modules/collector/batch-buffer.ts
@@ -34,6 +34,7 @@ export interface GeoIPResult {
} | null;
upload: number;
download: number;
+ connections?: number;
timestampMs?: number;
}
@@ -101,6 +102,11 @@ export class BatchBuffer {
return this.buffer.size > 0 || this.geoQueue.length > 0;
}
+ clear(): void {
+ this.buffer.clear();
+ this.geoQueue = [];
+ }
+
flush(
db: StatsDatabase,
_geoService: GeoIPService | undefined,
@@ -169,6 +175,7 @@ export class BatchBuffer {
continent: r.geo.continent || 'Unknown',
upload: r.upload,
download: r.download,
+ connections: Math.max(0, Math.floor(r.connections ?? 1)),
timestampMs: r.timestampMs,
}));
hasCountryUpdates = countryUpdates.length > 0;
diff --git a/apps/collector/src/modules/collector/gateway.collector.ts b/apps/collector/src/modules/collector/gateway.collector.ts
index 48d6583..2075246 100644
--- a/apps/collector/src/modules/collector/gateway.collector.ts
+++ b/apps/collector/src/modules/collector/gateway.collector.ts
@@ -469,6 +469,7 @@ export function createCollector(
geo,
upload: traffic.upload,
download: traffic.download,
+ connections: traffic.connections,
timestampMs: now,
});
realtimeStore.recordCountryTraffic(
@@ -528,5 +529,15 @@ export function createCollector(
});
};
- return collector;
+ const collectorWithReset = collector as GatewayCollector & {
+ clearRuntimeState?: () => void;
+ };
+ collectorWithReset.clearRuntimeState = () => {
+ // Keep active connection baselines to avoid replaying historical cumulative
+ // counters after a DB/log wipe. Only clear pending in-memory deltas.
+ batchBuffer.clear();
+ countedConnectionIds.clear();
+ };
+
+ return collectorWithReset;
}
diff --git a/apps/collector/src/modules/collector/surge.collector.ts b/apps/collector/src/modules/collector/surge.collector.ts
index 0522f29..81672fb 100644
--- a/apps/collector/src/modules/collector/surge.collector.ts
+++ b/apps/collector/src/modules/collector/surge.collector.ts
@@ -248,7 +248,10 @@ export function createSurgeCollector(
const id = backendId || 0;
const activeRequests = new Map<string, TrackedRequest>();
const batchBuffer = new BatchBuffer();
-
+ // Track which request IDs have been counted in the realtime store for the current
+ // flush interval — same deduplication as gateway direct mode's countedConnectionIds.
+ const countedConnectionIds = new Set<string>();
+
// Track recently completed requests to prevent double counting
// Key: request ID, Value: completion timestamp
const recentlyCompleted = new Map<string, CompletedRequestInfo>();
@@ -327,10 +330,13 @@ export function createSurgeCollector(
if (stats.hasTrafficUpdates && stats.trafficOk) {
if (trafficDetailOk && trafficAggOk) {
realtimeStore.clearTraffic(id);
+ countedConnectionIds.clear();
} else if (trafficDetailOk && !trafficAggOk) {
realtimeStore.clearTrafficDimensions(id);
+ countedConnectionIds.clear();
} else if (!trafficDetailOk && trafficAggOk) {
realtimeStore.clearTrafficSummary(id);
+ countedConnectionIds.clear();
}
}
@@ -541,6 +547,8 @@ export function createSurgeCollector(
sourceIP,
timestampMs: req.time || now,
});
+ const isNewThisFlush = !countedConnectionIds.has(req.id);
+ countedConnectionIds.add(req.id);
realtimeStore.recordTraffic(
id,
{
@@ -553,7 +561,7 @@ export function createSurgeCollector(
upload: currentUpload,
download: currentDownload,
},
- 1,
+ isNewThisFlush ? 1 : 0,
now
);
@@ -566,7 +574,7 @@ export function createSurgeCollector(
};
existingGeo.upload += currentUpload;
existingGeo.download += currentDownload;
- existingGeo.connections += 1;
+ if (isNewThisFlush) existingGeo.connections += 1;
geoBatchByIp.set(ip, existingGeo);
}
@@ -627,6 +635,8 @@ export function createSurgeCollector(
sourceIP: existing.sourceIP,
timestampMs: req.time || now,
});
+ const isNewThisFlush = !countedConnectionIds.has(req.id);
+ countedConnectionIds.add(req.id);
realtimeStore.recordTraffic(
id,
{
@@ -639,7 +649,7 @@ export function createSurgeCollector(
upload: uploadDelta,
download: downloadDelta,
},
- 1,
+ isNewThisFlush ? 1 : 0,
now
);
@@ -651,7 +661,7 @@ export function createSurgeCollector(
};
existingGeo.upload += uploadDelta;
existingGeo.download += downloadDelta;
- existingGeo.connections += 1;
+ if (isNewThisFlush) existingGeo.connections += 1;
geoBatchByIp.set(existing.ip, existingGeo);
}
@@ -703,6 +713,7 @@ export function createSurgeCollector(
geo,
upload: traffic.upload,
download: traffic.download,
+ connections: traffic.connections,
timestampMs: now,
});
realtimeStore.recordCountryTraffic(
@@ -784,7 +795,17 @@ export function createSurgeCollector(
};
};
- return collector;
+ const collectorWithReset = collector as SurgeCollector & {
+ clearRuntimeState?: () => void;
+ };
+ collectorWithReset.clearRuntimeState = () => {
+ // Keep active request baselines to avoid replaying historical cumulative
+ // counters after a DB/log wipe. Only clear pending in-memory deltas.
+ batchBuffer.clear();
+ countedConnectionIds.clear();
+ };
+
+ return collectorWithReset;
}
/**
diff --git a/apps/collector/src/modules/config/config.controller.ts b/apps/collector/src/modules/config/config.controller.ts
index 98ebbad..a23cc67 100644
--- a/apps/collector/src/modules/config/config.controller.ts
+++ b/apps/collector/src/modules/config/config.controller.ts
@@ -7,6 +7,8 @@ declare module "fastify" {
interface FastifyInstance {
db: StatsDatabase;
realtimeStore: RealtimeStore;
+ clearAgentRuntimeState?: (backendId?: number) => void;
+ notifyBackendDataCleared?: (backendId: number) => void;
}
}
@@ -201,11 +203,16 @@ const configController: FastifyPluginAsync = async (fastify: FastifyInstance): P
if (days === 0) {
if (backendId !== undefined) {
fastify.realtimeStore.clearBackend(backendId);
+ fastify.clearAgentRuntimeState?.(backendId);
+ fastify.notifyBackendDataCleared?.(backendId);
} else {
const backends = fastify.db.getAllBackends();
for (const backend of backends) {
fastify.realtimeStore.clearBackend(backend.id);
+ fastify.clearAgentRuntimeState?.(backend.id);
+ fastify.notifyBackendDataCleared?.(backend.id);
}
+ fastify.clearAgentRuntimeState?.();
}
return {
diff --git a/apps/collector/src/modules/db/db.ts b/apps/collector/src/modules/db/db.ts
index 0530948..28e6d0c 100644
--- a/apps/collector/src/modules/db/db.ts
+++ b/apps/collector/src/modules/db/db.ts
@@ -700,8 +700,8 @@ export class StatsDatabase {
() => this.repos.country.getCountryStats(backendId, limit, start, end),
);
}
- updateCountryStats(backendId: number, country: string, countryName: string, continent: string, upload: number, download: number) { this.repos.country.updateCountryStats(backendId, country, countryName, continent, upload, download); }
- batchUpdateCountryStats(backendId: number, results: Array<{ country: string; countryName: string; continent: string; upload: number; download: number; timestampMs?: number }>) { this.repos.country.batchUpdateCountryStats(backendId, results); }
+ updateCountryStats(backendId: number, country: string, countryName: string, continent: string, upload: number, download: number, timestampMs?: number, connections?: number) { this.repos.country.updateCountryStats(backendId, country, countryName, continent, upload, download, timestampMs, connections); }
+ batchUpdateCountryStats(backendId: number, results: Array<{ country: string; countryName: string; continent: string; upload: number; download: number; connections?: number; timestampMs?: number }>) { this.repos.country.batchUpdateCountryStats(backendId, results); }
// ==================== Device ====================
getDevices(backendId: number, limit?: number, start?: string, end?: string) {
diff --git a/apps/web/components/features/backend/backend-config-dialog.tsx b/apps/web/components/features/backend/backend-config-dialog.tsx
index 4c7aef4..ac20d01 100644
--- a/apps/web/components/features/backend/backend-config-dialog.tsx
+++ b/apps/web/components/features/backend/backend-config-dialog.tsx
@@ -1221,6 +1221,7 @@ export function BackendConfigDialog({
try {
await api.clearLogs(clearLogsDays);
await loadDbStats();
+ await onBackendChange?.();
setClearLogsDialogOpen(false);
toast.success(t("logsCleared"));
} catch (error: any) {