Skip to content

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

fix(web): no rate spikes after a WS reconnect or a late push (#93)

luolei55f353c10ce7
diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.ts
index 338fd1d..c7ae042 100644
--- a/apps/collector/src/index.ts
+++ b/apps/collector/src/index.ts
@@ -94,7 +94,7 @@ async function main() {
// realtime" never misses the flushed interval.
realtimeStore.onCleared((backendId) => {
db.clearRangeQueryCache(backendId);
- wsServer?.invalidateBackendCache(backendId);
+ wsServer?.clearBackendCache(backendId);
});
// Initialize policy sync service
diff --git a/apps/collector/src/modules/websocket/websocket.server.ts b/apps/collector/src/modules/websocket/websocket.server.ts
index 2643d6b..7157b12 100644
--- a/apps/collector/src/modules/websocket/websocket.server.ts
+++ b/apps/collector/src/modules/websocket/websocket.server.ts
@@ -915,14 +915,6 @@ export class StatsWebSocketServer {
};
}
- /** Drop cached persisted summaries of a backend (its realtime deltas were just persisted). */
- invalidateBackendCache(backendId: number): void {
- const prefix = `${backendId}|`;
- for (const key of this.baseSummaryCache.keys()) {
- if (key.startsWith(prefix)) this.baseSummaryCache.delete(key);
- }
- }
-
private getBaseSummaryCacheTTL(range: ClientRange): number {
if (!range.end) return StatsWebSocketServer.BASE_SUMMARY_CACHE_TTL_MS;
const endMs = new Date(range.end).getTime();
@@ -1173,10 +1165,13 @@ export class StatsWebSocketServer {
const clientInfo = this.clients.get(ws);
if (!clientInfo) return;
+ // The range this payload is computed for; the subscription may change
+ // while the query runs.
+ const range = clientInfo.range;
try {
const stats = await this.getStatsForBackend(
clientInfo.backendId,
- clientInfo.range,
+ range,
clientInfo.trend,
clientInfo.deviceDetail,
clientInfo.proxyDetail,
@@ -1196,6 +1191,8 @@ export class StatsWebSocketServer {
summaryFields: clientInfo.includeSummary
? this.buildSummaryFieldList(clientInfo.summaryFields)
: undefined,
+ start: range.start,
+ end: range.end,
data: stats,
timestamp: new Date().toISOString(),
};
@@ -1275,13 +1272,14 @@ export class StatsWebSocketServer {
const ipsPageKey = clientInfo.ipsPage
? `${clientInfo.ipsPage.offset}|${clientInfo.ipsPage.limit}|${clientInfo.ipsPage.sortBy || ''}|${clientInfo.ipsPage.sortOrder || ''}|${clientInfo.ipsPage.search || ''}`
: '';
- const cacheKey = `${resolvedBackendId}|${clientInfo.range.start || ''}|${clientInfo.range.end || ''}|${includeSummaryKey}|${summaryFieldsKey}|${trendKey}|${deviceDetailKey}|${proxyDetailKey}|${ruleDetailKey}|${ruleChainFlowKey}|${domainsPageKey}|${ipsPageKey}`;
+ const range = clientInfo.range;
+ const cacheKey = `${resolvedBackendId}|${range.start || ''}|${range.end || ''}|${includeSummaryKey}|${summaryFieldsKey}|${trendKey}|${deviceDetailKey}|${proxyDetailKey}|${ruleDetailKey}|${ruleChainFlowKey}|${domainsPageKey}|${ipsPageKey}`;
if (!jsonCache.has(cacheKey)) {
jsonCache.set(
cacheKey,
this.getStatsForBackend(
resolvedBackendId,
- clientInfo.range,
+ range,
clientInfo.trend,
clientInfo.deviceDetail,
clientInfo.proxyDetail,
@@ -1296,6 +1294,8 @@ export class StatsWebSocketServer {
? JSON.stringify({
type: 'stats',
backendId: resolvedBackendId,
+ start: range.start,
+ end: range.end,
summaryFields: clientInfo.includeSummary
? this.buildSummaryFieldList(clientInfo.summaryFields)
: undefined,
diff --git a/apps/web/lib/transfer-rate.ts b/apps/web/lib/transfer-rate.ts
index b9d3968..53f97e1 100644
--- a/apps/web/lib/transfer-rate.ts
+++ b/apps/web/lib/transfer-rate.ts
@@ -23,18 +23,18 @@ const MIN_SPAN_MS = 5_000;
const MAX_SAMPLE_AGE_MS = 30_000;
/**
- * Append a sample and drop the window when totals go backwards (range or
- * backend switched underneath us) or when the previous sample is stale.
+ * Append a sample. Within one window cumulative totals never go down, so a
+ * lower value is a stale or inconsistent reading (e.g. an old push shown
+ * again after a reconnect) and is ignored rather than used as a new
+ * baseline. The window restarts when the previous sample is stale.
*/
export function pushSample(samples: TotalsSample[], next: TotalsSample): TotalsSample[] {
const last = samples[samples.length - 1];
- if (
- last &&
- (next.download < last.download ||
- next.upload < last.upload ||
- next.at - last.at > MAX_SAMPLE_AGE_MS ||
- next.at < last.at)
- ) {
+ if (last && next.at - last.at <= MAX_SAMPLE_AGE_MS && next.at >= last.at &&
+ (next.download < last.download || next.upload < last.upload)) {
+ return samples;
+ }
+ if (last && (next.at - last.at > MAX_SAMPLE_AGE_MS || next.at < last.at)) {
return [next];
}
if (last && next.download === last.download && next.upload === last.upload && next.at === last.at) {
@@ -94,8 +94,8 @@ export const initialRateTrackerState: RateTrackerState = {
* baseline and are held back:
* - totals carried over from the old window or backend, which queries keep
* showing while the new one loads;
- * - the first fresh totals, which may come from the HTTP summary (persisted
- * data only) while later pushes also include the realtime buffer.
+ * - the first fresh totals, held back too as a precaution: right after a
+ * switch, HTTP fetches and WS pushes for the new window can still race.
* Either would turn the next jump into a huge spurious rate.
*
* `clear` tells the caller to drop the displayed reading (backend switched or
diff --git a/apps/web/lib/websocket.ts b/apps/web/lib/websocket.ts
index 71d15fc..164621d 100644
--- a/apps/web/lib/websocket.ts
+++ b/apps/web/lib/websocket.ts
@@ -44,12 +44,26 @@ export interface LiveConnection {
interface WebSocketMessage {
type: 'stats' | 'ping' | 'pong';
backendId?: number;
+ /** Range the payload was computed for. */
+ start?: string;
+ end?: string;
summaryFields?: SummaryField[];
data?: StatsSummary;
liveConnections?: LiveConnection[];
timestamp: string;
}
+function sameInstant(a?: string, b?: string): boolean {
+ if (!a || !b) return a === b;
+ return new Date(a).getTime() === new Date(b).getTime();
+}
+
+/** True when the push carries a range that differs from the current subscription. */
+function isOtherRange(message: WebSocketMessage, range?: TimeRange): boolean {
+ if (!range || (message.start === undefined && message.end === undefined)) return false;
+ return !sameInstant(message.start, range.start) || !sameInstant(message.end, range.end);
+}
+
interface UseStatsWebSocketOptions {
backendId?: number;
range?: TimeRange;
@@ -251,6 +265,7 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
const summaryFieldsKeyRef = useRef(summaryFieldsDependencyKey);
const hasSummaryFieldsFilterRef = useRef(!!normalizedSummaryFields);
const backendIdRef = useRef(backendId);
+ const rangeRef = useRef(range);
onMessageRef.current = options.onMessage;
onConnectRef.current = options.onConnect;
onDisconnectRef.current = options.onDisconnect;
@@ -259,6 +274,9 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
summaryFieldsKeyRef.current = summaryFieldsDependencyKey;
hasSummaryFieldsFilterRef.current = !!normalizedSummaryFields;
backendIdRef.current = backendId;
+ useEffect(() => {
+ rangeRef.current = range;
+ }, [range]);
const cleanup = useCallback(() => {
if (reconnectTimerRef.current) {
@@ -339,6 +357,11 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
return;
}
+ // Likewise drop late pushes computed for a previous time range.
+ if (isOtherRange(message, rangeRef.current)) {
+ return;
+ }
+
if (hasSummaryFieldsFilterRef.current) {
const incomingSummaryFieldsKey = summaryFieldsKey(message.summaryFields);
if (
@@ -369,6 +392,11 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
ws.onclose = (event) => {
console.log(`[WebSocket] Disconnected. Code: ${event.code}, Reason: ${event.reason}`);
setStatus('disconnected');
+ // Consumers fall back to HTTP while disconnected; a stale push must not
+ // reappear (as if current) when the socket reconnects.
+ if (trackLastMessageRef.current) {
+ setLastMessage(null);
+ }
onDisconnectRef.current?.();
// Clear ping interval