Skip to content

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

fix(collector,agent,web): data-loss, stability and config fixes

luolei60315924728f
diff --git a/apps/agent/internal/agent/runner.go b/apps/agent/internal/agent/runner.go
index c0068eb..3f9e8c8 100644
--- a/apps/agent/internal/agent/runner.go
+++ b/apps/agent/internal/agent/runner.go
@@ -480,15 +480,17 @@ func (r *Runner) ingestSnapshots(snapshots []domain.FlowSnapshot, nowMs int64) {
deltaUp := s.Upload
deltaDown := s.Download
if hasPrev {
- if s.Upload >= prev.LastUpload {
- deltaUp = s.Upload - prev.LastUpload
+ if s.Upload < prev.LastUpload || s.Download < prev.LastDown {
+ // Counter reset (gateway restart / connection id reuse): the
+ // counter went backwards. Match the direct gateway collector and
+ // treat the current value as new traffic instead of silently
+ // dropping it, and re-count the connection.
+ deltaUp = s.Upload
+ deltaDown = s.Download
+ counted = false
} else {
- deltaUp = 0
- }
- if s.Download >= prev.LastDown {
+ deltaUp = s.Upload - prev.LastUpload
deltaDown = s.Download - prev.LastDown
- } else {
- deltaDown = 0
}
}
diff --git a/apps/agent/internal/agent/runner_test.go b/apps/agent/internal/agent/runner_test.go
index 1f54150..83d359e 100644
--- a/apps/agent/internal/agent/runner_test.go
+++ b/apps/agent/internal/agent/runner_test.go
@@ -71,9 +71,18 @@ func TestIngestSnapshotsDeltaCalculation(t *testing.T) {
Rule: "MATCH",
}}, 3000)
+ // Counter reset (upload went backwards 25 -> 5): match the direct gateway
+ // collector and count the current value as new traffic, re-counting the
+ // connection, instead of silently dropping it.
third := runner.takeBatch(10)
- if len(third) != 0 {
- t.Fatalf("expected third batch len 0 when counters reset, got %d", len(third))
+ if len(third) != 1 {
+ t.Fatalf("expected third batch len 1 when counters reset, got %d", len(third))
+ }
+ if third[0].Upload != 5 || third[0].Download != 3 {
+ t.Fatalf("expected reset to count current 5/3 as new traffic, got %d/%d", third[0].Upload, third[0].Download)
+ }
+ if third[0].Connections != 1 {
+ t.Fatalf("expected reset to re-count connection (1), got %d", third[0].Connections)
}
}
diff --git a/apps/collector/src/database/repositories/backend.repository.ts b/apps/collector/src/database/repositories/backend.repository.ts
index 4d807c5..122f644 100644
--- a/apps/collector/src/database/repositories/backend.repository.ts
+++ b/apps/collector/src/database/repositories/backend.repository.ts
@@ -171,7 +171,12 @@ export class BackendRepository {
* Delete a backend and all its associated data
*/
deleteBackend(id: number): void {
- // Due to ON DELETE CASCADE, all associated stats will be deleted automatically
+ // ON DELETE CASCADE is declared on the child tables, but `PRAGMA
+ // foreign_keys` defaults OFF in better-sqlite3 (and enabling it globally
+ // would interfere with the table-rebuild migrations), so the cascade never
+ // fires. Explicitly delete all associated data first to avoid orphaned
+ // rows accumulating after a backend is removed.
+ this.deleteBackendData(id);
const stmt = this.db.prepare(`DELETE FROM backend_configs WHERE id = ?`);
stmt.run(id);
}
@@ -203,6 +208,10 @@ export class BackendRepository {
this.db.prepare(`DELETE FROM device_stats WHERE backend_id = ?`).run(id);
this.db.prepare(`DELETE FROM device_domain_stats WHERE backend_id = ?`).run(id);
this.db.prepare(`DELETE FROM device_ip_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM backend_health_logs WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM surge_policy_cache WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM agent_heartbeats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM agent_snapshots WHERE backend_id = ?`).run(id);
this.db.exec('COMMIT');
} catch (error) {
this.db.exec('ROLLBACK');
diff --git a/apps/collector/src/modules/clickhouse/clickhouse.writer.ts b/apps/collector/src/modules/clickhouse/clickhouse.writer.ts
index 19011fd..00f6364 100644
--- a/apps/collector/src/modules/clickhouse/clickhouse.writer.ts
+++ b/apps/collector/src/modules/clickhouse/clickhouse.writer.ts
@@ -147,6 +147,9 @@ export class ClickHouseWriter {
this.pendingRows + safeRowCount > this.maxPendingRows
) {
this.metrics.failures += 1;
+ // A full queue means ClickHouse cannot keep up; count it toward the
+ // unhealthy threshold so callers resume durable SQLite writes.
+ this.consecutiveFailures += 1;
this.maybeLogMetrics();
console.warn(
`[ClickHouse Writer] Dropped batch because pending queue is full (batches=${this.pendingBatches}/${this.maxPendingBatches}, rows=${this.pendingRows}/${this.maxPendingRows})`,
@@ -228,6 +231,11 @@ export class ClickHouseWriter {
);
}
+ // Both detail and agg committed: ClickHouse is accepting writes again.
+ if (this.consecutiveFailures > 0) {
+ console.info('[ClickHouse Writer] Recovered from failure, marking healthy again.');
+ this.consecutiveFailures = 0;
+ }
return { detailOk: true, aggOk: true };
}
@@ -259,10 +267,9 @@ export class ClickHouseWriter {
throw new Error(`status=${response.status} body=${text.slice(0, 200)}`);
}
- if (this.consecutiveFailures > 0) {
- console.info('[ClickHouse Writer] Recovered from failure, marking healthy again.');
- this.consecutiveFailures = 0;
- }
+ // Note: health is reset only after a *complete* traffic batch succeeds
+ // (see writeTrafficTables); resetting here on any single-table success
+ // would mask a table that fails persistently while another succeeds.
if (metricType === 'traffic') {
this.metrics.trafficBatches += 1;
this.metrics.trafficRows += rows.length;
diff --git a/apps/collector/src/modules/collector/batch-buffer.ts b/apps/collector/src/modules/collector/batch-buffer.ts
index 0f7e33b..cda04b0 100644
--- a/apps/collector/src/modules/collector/batch-buffer.ts
+++ b/apps/collector/src/modules/collector/batch-buffer.ts
@@ -51,6 +51,16 @@ export function toMinuteKey(timestampMs?: number): string {
return `${date.slice(0, 16)}:00`;
}
+export interface CountryUpdate {
+ country: string;
+ countryName: string;
+ continent: string;
+ upload: number;
+ download: number;
+ connections: number;
+ timestampMs?: number;
+}
+
export interface FlushResult {
domains: number;
rules: number;
@@ -63,6 +73,17 @@ export interface FlushResult {
pendingTrafficWrite?: Promise<TrafficWriteOutcome>;
/** Pending country write */
pendingCountryWrite?: Promise<void>;
+ /**
+ * Whether SQLite stats writes were skipped this flush because ClickHouse
+ * was considered healthy. When true and the ClickHouse write later fails,
+ * the caller must persist `updates`/`countryUpdates` to SQLite as a durable
+ * fallback to avoid silent data loss.
+ */
+ sqliteSkipped: boolean;
+ /** Snapshot of the traffic updates flushed this round (for fallback) */
+ updates: TrafficUpdate[];
+ /** Snapshot of the country updates flushed this round (for fallback) */
+ countryUpdates: CountryUpdate[];
}
export class BatchBuffer {
@@ -144,6 +165,7 @@ export class BatchBuffer {
let countryOk = true;
const hasTrafficUpdates = updates.length > 0;
let hasCountryUpdates = false;
+ let countryUpdates: CountryUpdate[] = [];
let pendingTrafficWrite: Promise<TrafficWriteOutcome> | undefined;
let pendingCountryWrite: Promise<void> | undefined;
@@ -171,7 +193,7 @@ export class BatchBuffer {
if (geoResults.length > 0) {
try {
- const countryUpdates = geoResults
+ countryUpdates = geoResults
.filter(
(r): r is GeoIPResult & { geo: NonNullable<GeoIPResult["geo"]> } =>
r.geo !== null,
@@ -220,6 +242,9 @@ export class BatchBuffer {
hasUpdates: hasTrafficUpdates || hasCountryUpdates,
pendingTrafficWrite,
pendingCountryWrite,
+ sqliteSkipped: skipSqliteStatsWrites,
+ updates,
+ countryUpdates,
};
}
diff --git a/apps/collector/src/modules/collector/gateway.collector.ts b/apps/collector/src/modules/collector/gateway.collector.ts
index 900791a..e3e6ccd 100644
--- a/apps/collector/src/modules/collector/gateway.collector.ts
+++ b/apps/collector/src/modules/collector/gateway.collector.ts
@@ -4,6 +4,7 @@ import { StatsDatabase } from "../db/db.js";
import { GeoIPService } from "../geo/geo.service.js";
import { TrafficWriteError } from "../clickhouse/clickhouse.writer.js";
import { realtimeStore } from "../realtime/realtime.store.js";
+import { calculateBackoffDelay } from "../../shared/utils/backoff.js";
import { BatchBuffer } from "./batch-buffer.js";
// Stale connection cleanup constants
@@ -33,6 +34,8 @@ export class GatewayCollector {
private url: string;
private token?: string;
private reconnectInterval: number;
+ private maxReconnectInterval: number;
+ private reconnectAttempts = 0;
private heartbeatInterval: number;
private heartbeatTimeout: number;
private onData?: (data: ConnectionsData) => void;
@@ -48,6 +51,10 @@ export class GatewayCollector {
this.url = options.url;
this.token = options.token;
this.reconnectInterval = options.reconnectInterval || 5000;
+ this.maxReconnectInterval = Math.max(
+ this.reconnectInterval,
+ parseInt(process.env.WS_MAX_RECONNECT_INTERVAL_MS || "60000", 10) || 60000,
+ );
this.heartbeatInterval =
options.heartbeatInterval ??
parseInt(
@@ -84,6 +91,7 @@ export class GatewayCollector {
this.ws.on("open", () => {
console.log(`[Collector:${this.backendId}] WebSocket connected`);
+ this.reconnectAttempts = 0;
this.startHeartbeat();
});
@@ -161,13 +169,21 @@ export class GatewayCollector {
private scheduleReconnect() {
if (this.reconnectTimer) return;
+ // Exponential backoff with jitter so a down/flapping backend is not
+ // hammered every 5s in lockstep across collectors (thundering herd).
+ const delay = calculateBackoffDelay(
+ this.reconnectAttempts,
+ this.reconnectInterval,
+ this.maxReconnectInterval,
+ );
+ this.reconnectAttempts += 1;
console.log(
- `[Collector:${this.backendId}] Reconnecting in ${this.reconnectInterval}ms...`,
+ `[Collector:${this.backendId}] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})...`,
);
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.connect();
- }, this.reconnectInterval);
+ }, delay);
}
disconnect() {
@@ -271,6 +287,30 @@ export function createCollector(
}
}
+ // Durable fallback: SQLite writes were skipped because ClickHouse was
+ // considered healthy, but the ClickHouse write failed. Persist the
+ // snapshot to SQLite so the data is not silently lost.
+ if (
+ stats.hasTrafficUpdates &&
+ stats.trafficOk &&
+ stats.sqliteSkipped &&
+ (!trafficDetailOk || !trafficAggOk)
+ ) {
+ try {
+ db.batchUpdateTrafficStats(id, stats.updates, false);
+ trafficDetailOk = true;
+ trafficAggOk = true;
+ console.warn(
+ `[Collector:${id}] ClickHouse traffic write failed; persisted ${stats.updates.length} updates to SQLite as fallback`,
+ );
+ } catch (fallbackErr) {
+ console.error(
+ `[Collector:${id}] SQLite fallback for traffic also failed; retaining realtime store`,
+ fallbackErr,
+ );
+ }
+ }
+
if (stats.hasTrafficUpdates && stats.trafficOk) {
if (trafficDetailOk && trafficAggOk) {
realtimeStore.clearTraffic(id);
@@ -296,6 +336,26 @@ export function createCollector(
}
}
+ if (
+ stats.hasCountryUpdates &&
+ stats.countryOk &&
+ stats.sqliteSkipped &&
+ !countryWriteOk
+ ) {
+ try {
+ db.batchUpdateCountryStats(id, stats.countryUpdates);
+ countryWriteOk = true;
+ console.warn(
+ `[Collector:${id}] ClickHouse country write failed; persisted to SQLite as fallback`,
+ );
+ } catch (fallbackErr) {
+ console.error(
+ `[Collector:${id}] SQLite fallback for country also failed; retaining realtime store`,
+ fallbackErr,
+ );
+ }
+ }
+
if (stats.hasCountryUpdates && stats.countryOk && countryWriteOk) {
realtimeStore.clearCountries(id);
}
@@ -597,7 +657,7 @@ export function createCollector(
// Override disconnect to clear intervals
const originalDisconnect = collector.disconnect.bind(collector);
- const waitForFlushThenDisconnect = async () => {
+ const waitForFlushThenStop = async () => {
while (isFlushing) {
await new Promise((resolve) => setTimeout(resolve, 25));
}
@@ -612,9 +672,13 @@ export function createCollector(
clearInterval(cleanupInterval);
cleanupInterval = null;
}
- void waitForFlushThenDisconnect().finally(() => {
- originalDisconnect();
- });
+ // Tear down the socket synchronously FIRST: this sets isClosing=true,
+ // clears the reconnect timer and closes the WebSocket immediately, so a
+ // credential/URL change (stop + start with new config) can never leave the
+ // old socket reconnecting with the stale token. Drain the buffer afterward.
+ // See issue #65.
+ originalDisconnect();
+ void waitForFlushThenStop();
};
const collectorWithReset = collector as GatewayCollector & {
diff --git a/apps/collector/src/modules/collector/surge.collector.ts b/apps/collector/src/modules/collector/surge.collector.ts
index c234532..1b06d73 100644
--- a/apps/collector/src/modules/collector/surge.collector.ts
+++ b/apps/collector/src/modules/collector/surge.collector.ts
@@ -325,6 +325,30 @@ export function createSurgeCollector(
}
}
+ // Durable fallback: SQLite writes were skipped because ClickHouse was
+ // considered healthy, but the ClickHouse write failed. Persist the
+ // snapshot to SQLite so the data is not silently lost.
+ if (
+ stats.hasTrafficUpdates &&
+ stats.trafficOk &&
+ stats.sqliteSkipped &&
+ (!trafficDetailOk || !trafficAggOk)
+ ) {
+ try {
+ db.batchUpdateTrafficStats(id, stats.updates, false);
+ trafficDetailOk = true;
+ trafficAggOk = true;
+ console.warn(
+ `[SurgeCollector:${id}] ClickHouse traffic write failed; persisted ${stats.updates.length} updates to SQLite as fallback`,
+ );
+ } catch (fallbackErr) {
+ console.error(
+ `[SurgeCollector:${id}] SQLite fallback for traffic also failed; retaining realtime store`,
+ fallbackErr,
+ );
+ }
+ }
+
if (stats.hasTrafficUpdates && stats.trafficOk) {
if (trafficDetailOk && trafficAggOk) {
realtimeStore.clearTraffic(id);
@@ -348,6 +372,26 @@ export function createSurgeCollector(
}
}
+ if (
+ stats.hasCountryUpdates &&
+ stats.countryOk &&
+ stats.sqliteSkipped &&
+ !countryWriteOk
+ ) {
+ try {
+ db.batchUpdateCountryStats(id, stats.countryUpdates);
+ countryWriteOk = true;
+ console.warn(
+ `[SurgeCollector:${id}] ClickHouse country write failed; persisted to SQLite as fallback`,
+ );
+ } catch (fallbackErr) {
+ console.error(
+ `[SurgeCollector:${id}] SQLite fallback for country also failed; retaining realtime store`,
+ fallbackErr,
+ );
+ }
+ }
+
if (stats.hasCountryUpdates && stats.countryOk && countryWriteOk) {
realtimeStore.clearCountries(id);
}
diff --git a/apps/collector/src/shared/utils/backoff.test.ts b/apps/collector/src/shared/utils/backoff.test.ts
new file mode 100644
index 0000000..a5f9eea
--- /dev/null
+++ b/apps/collector/src/shared/utils/backoff.test.ts
@@ -0,0 +1,32 @@
+import { describe, it, expect } from 'vitest';
+import { calculateBackoffDelay } from './backoff.js';
+
+describe('calculateBackoffDelay', () => {
+ it('grows exponentially and caps at maxDelay (no jitter)', () => {
+ expect(calculateBackoffDelay(0, 1000, 60000, false)).toBe(1000);
+ expect(calculateBackoffDelay(1, 1000, 60000, false)).toBe(2000);
+ expect(calculateBackoffDelay(2, 1000, 60000, false)).toBe(4000);
+ // 1000 * 2^10 = 1024000, capped at 60000
+ expect(calculateBackoffDelay(10, 1000, 60000, false)).toBe(60000);
+ });
+
+ it('with jitter stays within [capped/2, capped]', () => {
+ for (let attempt = 0; attempt < 8; attempt++) {
+ const capped = Math.min(1000 * 2 ** attempt, 60000);
+ for (let i = 0; i < 200; i++) {
+ const delay = calculateBackoffDelay(attempt, 1000, 60000);
+ expect(delay).toBeGreaterThanOrEqual(Math.floor(capped / 2));
+ expect(delay).toBeLessThanOrEqual(capped);
+ }
+ }
+ });
+
+ it('jitter produces varied delays (not lockstep)', () => {
+ const values = new Set<number>();
+ for (let i = 0; i < 100; i++) {
+ values.add(calculateBackoffDelay(3, 1000, 60000));
+ }
+ // With jitter over a 4000ms window, repeated calls must not all be equal.
+ expect(values.size).toBeGreaterThan(1);
+ });
+});
diff --git a/apps/collector/src/shared/utils/backoff.ts b/apps/collector/src/shared/utils/backoff.ts
index 9a21cd9..b0bf95a 100644
--- a/apps/collector/src/shared/utils/backoff.ts
+++ b/apps/collector/src/shared/utils/backoff.ts
@@ -1,11 +1,21 @@
/**
- * 指数退避计算器
+ * 指数退避计算器(带抖动)
+ *
+ * Adds "equal jitter" by default so that many collectors failing at the same
+ * time (e.g. a shared upstream outage) do not retry in lockstep and create a
+ * thundering-herd against the recovering backend. The returned delay is in
+ * `[capped/2, capped]` where `capped = min(baseDelay * 2^attempt, maxDelay)`.
*/
export function calculateBackoffDelay(
attempt: number,
baseDelay: number,
- maxDelay: number
+ maxDelay: number,
+ jitter = true,
): number {
- const delay = baseDelay * Math.pow(2, attempt);
- return Math.min(delay, maxDelay);
+ const capped = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
+ if (!jitter) {
+ return capped;
+ }
+ const half = capped / 2;
+ return Math.round(half + Math.random() * half);
}
diff --git a/apps/web/app/[locale]/layout.tsx b/apps/web/app/[locale]/layout.tsx
index 3defedf..f596f12 100644
--- a/apps/web/app/[locale]/layout.tsx
+++ b/apps/web/app/[locale]/layout.tsx
@@ -1,4 +1,5 @@
import type { Metadata, Viewport } from "next";
+import Script from "next/script";
import { Geist, Geist_Mono } from "next/font/google";
import "../globals.css";
import { ThemeProvider } from "@/components/providers/theme-provider";
@@ -76,7 +77,13 @@ export default async function RootLayout({
content="black-translucent"
/>
<meta name="apple-mobile-web-app-title" content="Neko Master" />
- <script src="/runtime-config.js" />
+ {/*
+ Load runtime config (real external ports/URLs written by
+ docker-start.sh) BEFORE the app bundle, so the WebSocket client reads
+ window.__RUNTIME_CONFIG__.WS_PORT instead of racing and falling back
+ to the build-time default. See issue #61.
+ */}
+ <Script src="/runtime-config.js" strategy="beforeInteractive" />
</head>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts
index 4815f05..b86192f 100644
--- a/apps/web/next.config.ts
+++ b/apps/web/next.config.ts
@@ -65,6 +65,19 @@ const nextConfig: NextConfig = {
},
],
},
+ {
+ // runtime-config.js is rewritten at container start with the real
+ // external ports / URLs (docker-start.sh). It must never be cached or
+ // the browser keeps using the stale build-time default, ignoring
+ // WS_EXTERNAL_PORT / API_EXTERNAL_PORT. See issue #61.
+ source: "/runtime-config.js",
+ headers: [
+ {
+ key: "Cache-Control",
+ value: "no-store, no-cache, must-revalidate",
+ },
+ ],
+ },
];
},
};
@@ -82,7 +95,9 @@ if (process.env.NODE_ENV === "production") {
register: true,
skipWaiting: true,
disable: false,
- buildExcludes: [/middleware-manifest.json$/],
+ // Never precache runtime-config.js — it is rewritten at container start
+ // with the real ports/URLs and must always be fetched fresh (issue #61).
+ buildExcludes: [/middleware-manifest.json$/, /runtime-config\.js$/],
})(finalConfig);
} catch {
// PWA not available, use base config