Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(websocket): keep oversized recovery baseline-free

rcourtman541c9be7fd76
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index 9751889cdb..8549f52046 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -261,6 +261,18 @@ overview must preserve active alert truth while notification delivery is
pending review or snoozed. Notification activation must not clear the browser
active-alert store, suppress resource indicators, lock threshold/history
configuration, or claim that monitoring has stopped.
+The websocket store's raw resource-delta baseline is connection-scoped. Closing
+or replacing a socket invalidates that baseline and its recovery throttle; a
+delta from the replacement connection must not patch the previous connection's
+raw snapshot. Only a full snapshot delivered over that socket may establish
+the new delta baseline. Oversized-state REST recovery may refresh the current
+connection's display state, but it is independently built and must remain
+delta-free; a marker or baseline-less delta observed during hydration must
+coalesce one trailing REST refresh after the throttle window so the latest
+invalidation is not lost. Late socket callbacks and REST responses from a
+retired connection must be ignored, while a current oversized connection
+remains free to hydrate without waiting for the retired connection's request
+to settle.
Operational evidence and lifecycle identity are typed through
`internal/operationaltrust`. Evidence envelopes distinguish completeness,
confidence, permissions, freshness, correlation, and bounded provider detail.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index d7497b1e11..4e32f3cd5d 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -317,6 +317,21 @@ and slow-client eviction must use the same synchronized send/close ownership;
recovering a send-on-closed panic is not a substitute for a race-free channel
lifecycle.
+Browser clients declare their inbound state-frame ceiling on the WebSocket
+upgrade URL before initial-state construction begins. If a complete snapshot
+or a later delta exceeds that ceiling, the hub sends a compact
+`stateTooLarge` marker, clears the per-client delta snapshot, and enters
+baseline-free REST recovery. It must not advance the baseline to the withheld
+state: `GET /api/state` is constructed later and is not provably byte- or
+revision-identical. While recovery is active, coalesced state invalidations
+produce markers rather than deltas. The frontend may use each REST response as
+a complete display snapshot, with one throttled trailing refresh for markers
+that arrive during hydration, but only a complete state payload actually
+delivered on that WebSocket connection may re-establish its delta baseline.
+Clients and servers that predate negotiation retain the existing full-frame
+path; a new client that locally drops such a legacy oversized frame must stay
+delta-free and use the same throttled REST recovery for that connection.
+
Docker and Podman app-container CPU payloads expose two API facts with
different meanings: canonical resource metrics and `/api/metrics-store/history`
CPU fallback points use host-capacity-normalized percent, while Docker metadata
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 798fb2c2bd..58b0cace6f 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -1145,6 +1145,11 @@ AI-only summary payloads, or page-local heuristics.
from websocket `state.resources` instead of layering confirmatory
route-local REST refetch loops over already-owned resource
updates.
+ Oversized WebSocket recovery is the transport exception: a complete
+ `/api/state` response may refresh display state while the connection remains
+ baseline-free, but resource deltas must not patch that independently built
+ REST snapshot. The store resumes delta application only after the same
+ connection delivers a complete WebSocket resource snapshot.
Browser WebSocket liveness tracking is part of that same store boundary:
valid inbound server messages, including heartbeat `ping`/`pong` traffic,
must refresh the browser-side activity timestamp so quiet periods between
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index 8fce7f1452..3b46c9be11 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,13 +1,20 @@
{
"version": 1,
- "base_sha": "7a0f410508822afed26c23cd3e715fbeaae3c420",
- "verified_at": "2026-08-08T00:21:37Z",
+ "base_sha": "98ecfb3f10143cdb7b317cb7ab410ae5b2852ab2",
+ "verified_at": "2026-08-08T00:30:24Z",
"result": "passed",
- "changed_paths": ["frontend-modern/src/App.tsx"],
+ "changed_paths": [
+ "frontend-modern/src/stores/websocket.ts",
+ "frontend-modern/src/types/api.ts"
+ ],
"content_sha256": {
- "frontend-modern/src/App.tsx": "689e80b118c2772f1ed8811897579f0677fb74cd19172640028f6f34b3b93112"
+ "frontend-modern/src/stores/websocket.ts": "2b6d4ae3c797c00e18bd4ec7ad3582c3878bf673345604efd65f8d030fd6de2d",
+ "frontend-modern/src/types/api.ts": "5ef74848b2fb1eb1a2f3a3e0d5b6d7832247755cd79cba14eb8a33f1facf7e59"
},
- "routes": ["/proxmox/overview", "/api/security/status", "/api/updates/status"],
+ "routes": [
+ "/docker/overview",
+ "/standalone/machines"
+ ],
"viewports": [
{
"width": 1280,
@@ -19,16 +26,15 @@
}
],
"states": [
- "An authenticated proxy viewer received requiresAuth=true and systemSettingsRead=false; the normal application shell rendered and no /api/updates/status request was emitted during an 11.5 second observation window.",
- "An authenticated proxy administrator received requiresAuth=true and systemSettingsRead=true; the normal application shell rendered and three /api/updates/status requests were emitted during an 11.5 second observation window.",
- "An auth-free backend returned requiresAuth=false without settings capabilities and continued to serve /api/updates/status with HTTP 200.",
- "The administrator shell rendered at 1280x800 and 375x812 with document scroll width equal to the viewport width."
+ "Authenticated Docker overview at 1280x800 on the final combined build, then stopped the backend: the amber reconnect status appeared while the previously received Tower host and pbs container rows remained coherent and readable.",
+ "At 375x812 the reconnecting Docker view retained its compact responsive tables, mobile navigation, and a document scroll width equal to the 375px viewport.",
+ "Mobile navigation reached /standalone/machines and returned to /docker/overview with the reconnect status intact; the newly mounted Machines REST projection failed closed while the retained Docker snapshot remained rendered on return.",
+ "The in-app browser console showed the expected reconnect diagnostics and REST fetch failures caused by deliberately stopping the backend, with no exception or rendering failure attributable to the changed WebSocket store."
],
"interactions": [
- "Built and launched an isolated backend with proxy authentication plus separate header-injecting viewer and administrator proxies.",
- "Loaded the authenticated viewer shell, observed two polling intervals, and confirmed the proxy logged no update-status requests while the direct route correctly returned HTTP 403.",
- "Loaded the authenticated administrator shell, observed two polling intervals, and confirmed the proxy logged three update-status requests while the direct route returned HTTP 200.",
- "Restarted the isolated backend without authentication and confirmed both the public security status and the still-open update-status route returned HTTP 200.",
- "Inspected the administrator shell at desktop and narrow viewports and confirmed there was no horizontal document overflow."
+ "Built and started the final backend plus frontend source on http://127.0.0.1:5174, signed in with the documented development account, and confirmed a connected Docker host/container snapshot at 1280x800.",
+ "Stopped the backend, captured and inspected the rendered desktop reconnect state, and confirmed the mounted Docker snapshot remained visible rather than accepting an unbased stream.",
+ "Resized to 375x812, verified the retained Docker tables and horizontal overflow metrics, then used mobile navigation to open Machines and return to Docker during reconnect.",
+ "Read the browser console after the interaction matrix and classified the reconnect and failed REST diagnostics against the deliberate backend shutdown."
]
}
diff --git a/frontend-modern/src/stores/__tests__/websocket-resilience.test.ts b/frontend-modern/src/stores/__tests__/websocket-resilience.test.ts
index bfb32c94d6..02bc5f5a19 100644
--- a/frontend-modern/src/stores/__tests__/websocket-resilience.test.ts
+++ b/frontend-modern/src/stores/__tests__/websocket-resilience.test.ts
@@ -1,16 +1,27 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createRoot } from 'solid-js';
+// Mirrors MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES in the store under test.
+const MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES = 8 * 1024 * 1024;
+
const notificationMocks = vi.hoisted(() => ({
success: vi.fn(),
error: vi.fn(),
info: vi.fn(),
warning: vi.fn(),
}));
+const apiFetchJSONMock = vi.hoisted(() => vi.fn());
vi.mock('@/stores/notifications', () => ({
notificationStore: notificationMocks,
}));
+vi.mock('@/utils/apiClient', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/utils/apiClient')>();
+ return {
+ ...actual,
+ apiFetchJSON: (...args: unknown[]) => apiFetchJSONMock(...args),
+ };
+});
interface MockWebSocketInstance {
url: string;
@@ -62,6 +73,12 @@ const installWebSocketMock = () => {
vi.stubGlobal('WebSocket', MockWebSocketClass);
};
+const flushMicrotasks = async (turns = 6) => {
+ for (let i = 0; i < turns; i += 1) {
+ await Promise.resolve();
+ }
+};
+
const createStoreHarness = async () => {
const { createWebSocketStore } = await import('@/stores/websocket');
let dispose = () => {};
@@ -81,6 +98,7 @@ describe('websocket store resilience', () => {
instances.length = 0;
vi.setSystemTime(new Date('2026-05-14T08:00:00.000Z'));
notificationMocks.success.mockClear();
+ apiFetchJSONMock.mockReset();
installWebSocketMock();
});
@@ -213,6 +231,206 @@ describe('websocket store resilience', () => {
}
});
+ it('waits for the reconnect snapshot before applying resource deltas', async () => {
+ vi.spyOn(Math, 'random').mockReturnValue(0.5);
+ let resolveRestSnapshot!: (snapshot: unknown) => void;
+ apiFetchJSONMock.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveRestSnapshot = resolve;
+ }),
+ );
+ apiFetchJSONMock.mockResolvedValueOnce({
+ resources: [{ id: 'new-host', type: 'agent', name: 'new-host', lastSeen: 400 }],
+ activeAlerts: [],
+ recentlyResolved: [],
+ lastUpdate: 400,
+ });
+
+ const { store, dispose } = await createStoreHarness();
+ try {
+ vi.advanceTimersByTime(1);
+ const firstConnection = currentInstance;
+ expect(firstConnection).not.toBeNull();
+
+ firstConnection!.onmessage?.({
+ data: JSON.stringify({
+ type: 'initialState',
+ data: {
+ resources: [{ id: 'old-host', type: 'agent', name: 'old-host', lastSeen: 100 }],
+ activeAlerts: [],
+ recentlyResolved: [],
+ lastUpdate: 100,
+ },
+ }),
+ } as MessageEvent);
+ expect(store.state.resources[0]?.lastSeen).toBe(100);
+
+ firstConnection!.onclose?.({ code: 1011, reason: 'network blip' } as CloseEvent);
+ expect(store.initialDataReceived()).toBe(false);
+ vi.advanceTimersByTime(1_000);
+ vi.advanceTimersByTime(1);
+ await flushMicrotasks();
+
+ const secondConnection = currentInstance;
+ expect(secondConnection).not.toBe(firstConnection);
+ secondConnection!.onmessage?.({
+ data: JSON.stringify({
+ type: 'stateTooLarge',
+ data: {
+ supersedes: 'initialState',
+ bytes: MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES + 1,
+ maxBytes: MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES,
+ resourceCount: 1,
+ hydrateFrom: '/api/state',
+ },
+ }),
+ } as MessageEvent);
+ expect(apiFetchJSONMock).toHaveBeenCalledTimes(1);
+
+ // The new connection's delta is based on its own dropped snapshot. It
+ // must not patch the previous connection's raw resource array while the
+ // replacement snapshot is still pending over REST.
+ secondConnection!.onmessage?.({
+ data: JSON.stringify({
+ type: 'rawData',
+ data: {
+ resourceDelta: { upserts: [{ id: 'old-host', lastSeen: 999 }] },
+ lastUpdate: 200,
+ },
+ }),
+ } as MessageEvent);
+ expect(store.state.resources[0]?.lastSeen).toBe(100);
+ expect(store.initialDataReceived()).toBe(false);
+
+ resolveRestSnapshot({
+ resources: [{ id: 'new-host', type: 'agent', name: 'new-host', lastSeen: 300 }],
+ activeAlerts: [],
+ recentlyResolved: [],
+ lastUpdate: 300,
+ });
+ await flushMicrotasks();
+
+ expect(store.state.resources.map((resource) => resource.id)).toEqual(['new-host']);
+ expect(store.initialDataReceived()).toBe(true);
+
+ // REST is a valid display snapshot, but it is not the exact state the
+ // server withheld earlier. Deltas remain disabled for this connection.
+ secondConnection!.onmessage?.({
+ data: JSON.stringify({
+ type: 'rawData',
+ data: {
+ resourceDelta: { upserts: [{ id: 'new-host', lastSeen: 400 }] },
+ lastUpdate: 400,
+ },
+ }),
+ } as MessageEvent);
+ expect(store.state.resources[0]?.lastSeen).toBe(300);
+
+ // The delta that arrived during/after hydration is coalesced into one
+ // trailing REST refresh once the shared throttle expires. It cannot be
+ // lost merely because the first request was still in flight.
+ vi.advanceTimersByTime(30_000);
+ await flushMicrotasks();
+ expect(apiFetchJSONMock).toHaveBeenCalledTimes(2);
+ expect(store.state.resources[0]?.lastSeen).toBe(400);
+
+ // If the estate later fits, a delivered socket snapshot establishes the
+ // connection's delta baseline and normal incremental updates resume.
+ secondConnection!.onmessage?.({
+ data: JSON.stringify({
+ type: 'rawData',
+ data: {
+ resources: [{ id: 'new-host', type: 'agent', name: 'new-host', lastSeen: 500 }],
+ lastUpdate: 500,
+ },
+ }),
+ } as MessageEvent);
+ secondConnection!.onmessage?.({
+ data: JSON.stringify({
+ type: 'rawData',
+ data: {
+ resourceDelta: { upserts: [{ id: 'new-host', lastSeen: 600 }] },
+ lastUpdate: 600,
+ },
+ }),
+ } as MessageEvent);
+ expect(store.state.resources[0]?.lastSeen).toBe(600);
+ } finally {
+ dispose();
+ }
+ });
+
+ it('keeps URL-switched sockets isolated until their own snapshot arrives', async () => {
+ const { store, dispose } = await createStoreHarness();
+ try {
+ vi.advanceTimersByTime(1);
+ const firstConnection = currentInstance;
+ firstConnection!.onmessage?.({
+ data: JSON.stringify({
+ type: 'initialState',
+ data: {
+ resources: [{ id: 'first-host', type: 'agent', name: 'first-host' }],
+ activeAlerts: [],
+ recentlyResolved: [],
+ },
+ }),
+ } as MessageEvent);
+
+ store.switchUrl('ws://other-backend/ws');
+ const secondConnection = currentInstance;
+ expect(secondConnection).not.toBe(firstConnection);
+ const switchedUrl = new URL(secondConnection!.url);
+ expect(`${switchedUrl.protocol}//${switchedUrl.host}${switchedUrl.pathname}`).toBe(
+ 'ws://other-backend/ws',
+ );
+ expect(switchedUrl.searchParams.get('max_message_bytes')).toBe(
+ String(MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES),
+ );
+ expect(store.state.resources).toEqual([]);
+ expect(store.initialDataReceived()).toBe(false);
+
+ // A late callback from the retired backend must not repopulate the reset
+ // store after URL switching.
+ firstConnection!.onmessage?.({
+ data: JSON.stringify({
+ type: 'rawData',
+ data: {
+ resources: [{ id: 'late-first-host', type: 'agent', name: 'late-first-host' }],
+ },
+ }),
+ } as MessageEvent);
+ expect(store.state.resources).toEqual([]);
+
+ secondConnection!.onmessage?.({
+ data: JSON.stringify({
+ type: 'rawData',
+ data: {
+ resourceDelta: { upserts: [{ id: 'second-host', lastSeen: 200 }] },
+ },
+ }),
+ } as MessageEvent);
+ expect(store.state.resources).toEqual([]);
+ expect(store.initialDataReceived()).toBe(false);
+ expect(secondConnection!.send).toHaveBeenCalledWith(JSON.stringify({ type: 'requestData' }));
+
+ secondConnection!.onmessage?.({
+ data: JSON.stringify({
+ type: 'initialState',
+ data: {
+ resources: [{ id: 'second-host', type: 'agent', name: 'second-host' }],
+ activeAlerts: [],
+ recentlyResolved: [],
+ },
+ }),
+ } as MessageEvent);
+ expect(store.state.resources.map((resource) => resource.id)).toEqual(['second-host']);
+ expect(store.initialDataReceived()).toBe(true);
+ } finally {
+ dispose();
+ }
+ });
+
it('manual reconnect avoids duplicate reconnect scheduling', async () => {
const { store, dispose } = await createStoreHarness();
try {
diff --git a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts b/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
index 9edb5a28fa..9ac2d240a9 100644
--- a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
+++ b/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
@@ -496,7 +496,7 @@ describe('websocket store unified resource contract', () => {
}
});
- it('establishes a delta baseline from the REST snapshot', async () => {
+ it('does not treat an independently built REST snapshot as a delta baseline', async () => {
apiFetchJSONMock.mockResolvedValue({
lastUpdate: 500,
resources: [{ id: 'agent-host-1', type: 'agent', name: 'host-1', lastSeen: 100 }],
@@ -510,8 +510,8 @@ describe('websocket store unified resource contract', () => {
await flushMicrotasks();
expect(store.state.resources).toHaveLength(1);
- // The REST payload must serve as the baseline the server's deltas are
- // patched onto — otherwise recovery hydrates once and then stalls again.
+ // The server's withheld snapshot and this later REST response are not
+ // guaranteed to be identical, so the delta must not patch the REST copy.
emitMessage({
type: 'rawData',
data: {
@@ -524,7 +524,7 @@ describe('websocket store unified resource contract', () => {
await flushMicrotasks();
expect(store.state.resources).toHaveLength(1);
- expect(store.state.resources[0]?.lastSeen).toBe(200);
+ expect(store.state.resources[0]?.lastSeen).toBe(100);
expect(store.state.resources[0]?.name).toBe('host-1');
expect(sentMessageTypes()).not.toContain('requestData');
} finally {
diff --git a/frontend-modern/src/stores/websocket.ts b/frontend-modern/src/stores/websocket.ts
index 04d223b31d..a713127aa9 100644
--- a/frontend-modern/src/stores/websocket.ts
+++ b/frontend-modern/src/stores/websocket.ts
@@ -49,6 +49,20 @@ const asMergePatchRecord = (value: unknown): Record<string, unknown> | undefined
const asString = (value: unknown): string | undefined =>
typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
+// The frame ceiling has to be negotiated on the upgrade request. A message
+// sent after open can race the server's initial-state build.
+const buildSocketUrl = (rawUrl: string): string => {
+ try {
+ const parsed = new URL(rawUrl, window.location.href);
+ if (parsed.protocol === 'http:') parsed.protocol = 'ws:';
+ if (parsed.protocol === 'https:') parsed.protocol = 'wss:';
+ parsed.searchParams.set('max_message_bytes', String(MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES));
+ return parsed.toString();
+ } catch {
+ return rawUrl;
+ }
+};
+
const isInboundPayloadWithinLimit = (payload: string): boolean => {
// JSON state is overwhelmingly ASCII. Avoid allocating a second multi-megabyte
// Blob for normal messages, while retaining an exact UTF-8 check for strings
@@ -316,7 +330,11 @@ export function createWebSocketStore(url: string) {
// guard. Asking for another one over the socket would only reproduce the same
// oversized frame, so recovery has to leave the WebSocket entirely.
let oversizedSnapshotObserved = false;
- let restHydrationInFlight = false;
+ let restHydrationConnectionId: number | null = null;
+ let pendingRestHydrationConnectionId: number | null = null;
+ let restHydrationTimeout = 0;
+ let nextConnectionId = 0;
+ let activeConnectionId: number | null = null;
let reconnectTimeout = 0;
let reconnectDelayTimeout = 0;
let lastServerActivityAt = Date.now();
@@ -370,6 +388,40 @@ export function createWebSocketStore(url: string) {
}
};
+ const resetConnectionBaseline = () => {
+ rawServerResources = null;
+ lastFullStateRecoveryAt = 0;
+ oversizedSnapshotObserved = false;
+ // A recovery request from a retired connection may still settle, but its
+ // connection id prevents it from mutating this connection. Clearing the
+ // owner here lets the replacement connection start its own recovery now.
+ restHydrationConnectionId = null;
+ pendingRestHydrationConnectionId = null;
+ if (restHydrationTimeout) {
+ window.clearTimeout(restHydrationTimeout);
+ restHydrationTimeout = 0;
+ }
+ };
+
+ const beginConnection = () => {
+ const connectionId = ++nextConnectionId;
+ activeConnectionId = connectionId;
+ resetConnectionBaseline();
+ setInitialDataReceived(false);
+ return connectionId;
+ };
+
+ const isCurrentConnection = (connectionId: number) =>
+ !isDisposed && activeConnectionId === connectionId;
+
+ const retireConnection = (connectionId: number) => {
+ if (activeConnectionId !== connectionId) return false;
+ activeConnectionId = null;
+ resetConnectionBaseline();
+ setInitialDataReceived(false);
+ return true;
+ };
+
const shutdown = () => {
if (isDisposed) return;
isDisposed = true;
@@ -381,6 +433,8 @@ export function createWebSocketStore(url: string) {
pendingAckTimeouts.forEach((timeout) => window.clearTimeout(timeout));
pendingAckTimeouts.clear();
pendingAckChanges.clear();
+ activeConnectionId = null;
+ resetConnectionBaseline();
if (typeof window !== 'undefined') {
window.removeEventListener(ALERTS_DETECTION_EVENT, handleAlertsDetectionEvent);
@@ -399,6 +453,7 @@ export function createWebSocketStore(url: string) {
const connect = () => {
if (isDisposed) return;
clearReconnectDelayTimeout();
+ const connectionId = beginConnection();
try {
// Close existing connection if any
@@ -409,9 +464,11 @@ export function createWebSocketStore(url: string) {
ws = null;
}
- ws = new WebSocket(wsUrl);
- setupWebSocket();
+ const socket = new WebSocket(buildSocketUrl(wsUrl));
+ ws = socket;
+ setupWebSocket(socket, connectionId);
} catch (err) {
+ retireConnection(connectionId);
logger.error('Failed to create WebSocket', err);
handleReconnect();
}
@@ -443,10 +500,14 @@ export function createWebSocketStore(url: string) {
}, delay);
};
- // Applies one decoded server message to the store. Shared by the socket
- // handler and the REST recovery path so a snapshot fetched over HTTP
- // establishes the same delta baseline a socket snapshot would.
- const processServerMessage = (data: unknown) => {
+ // Applies one decoded server message to the store. Socket snapshots may
+ // establish a delta baseline; REST snapshots update display state only.
+ const processServerMessage = (
+ data: unknown,
+ connectionId: number,
+ source: 'websocket' | 'rest' = 'websocket',
+ ) => {
+ if (!isCurrentConnection(connectionId)) return;
try {
const message = data as TimestampedWSMessage;
@@ -454,12 +515,18 @@ export function createWebSocketStore(url: string) {
message.type === WEBSOCKET.MESSAGE_TYPES.INITIAL_STATE ||
message.type === WEBSOCKET.MESSAGE_TYPES.RAW_DATA
) {
+ const resourceDeltaWithoutBaseline =
+ message.data !== undefined &&
+ message.data.resources === undefined &&
+ 'resourceDelta' in message.data &&
+ message.data.resourceDelta !== undefined &&
+ rawServerResources === null;
// Update state properties individually, but batch the whole payload to
// reduce reactive recomputations and UI thrash on large updates.
if (message.data)
batch(() => {
// Mark that we've received usable data (initial payload or raw update)
- if (!initialDataReceived()) {
+ if (!initialDataReceived() && !resourceDeltaWithoutBaseline) {
setInitialDataReceived(true);
}
@@ -491,13 +558,28 @@ export function createWebSocketStore(url: string) {
let nextResources: Resource[] | undefined;
if (message.data.resources !== undefined) {
if (Array.isArray(message.data.resources)) {
- rawServerResources = structuredClone(message.data.resources) as Resource[];
+ // Only a full payload actually delivered on this socket can
+ // establish its server-owned delta baseline. REST recovery is
+ // an independently built display snapshot and stays baseline-
+ // free until the server later delivers a socket snapshot.
+ rawServerResources =
+ source === 'websocket'
+ ? (structuredClone(message.data.resources) as Resource[])
+ : null;
+ if (source === 'websocket') {
+ oversizedSnapshotObserved = false;
+ pendingRestHydrationConnectionId = null;
+ if (restHydrationTimeout) {
+ window.clearTimeout(restHydrationTimeout);
+ restHydrationTimeout = 0;
+ }
+ }
nextResources = mergeCanonicalResourceSnapshot(
message.data.resources,
state.resources,
);
} else {
- rawServerResources = [];
+ rawServerResources = source === 'websocket' ? [] : null;
nextResources = [];
}
} else if (
@@ -518,7 +600,7 @@ export function createWebSocketStore(url: string) {
// payload was dropped as oversized). There is no baseline to
// patch, so re-acquire a full snapshot instead of applying the
// delta to nothing and rendering stubs.
- requestFullStateRecovery();
+ requestFullStateRecovery(connectionId);
}
}
if (nextResources !== undefined) {
@@ -603,6 +685,19 @@ export function createWebSocketStore(url: string) {
hasData: !!message.data,
resourceCount: message.data?.resources?.length || 0,
});
+ } else if (message.type === 'stateTooLarge') {
+ // The server deliberately did not adopt the withheld payload as this
+ // client's delta baseline. Invalidate any prior baseline before REST
+ // hydration and remain delta-free until a full socket snapshot lands.
+ rawServerResources = null;
+ oversizedSnapshotObserved = true;
+ logger.warn('Server withheld an oversized state payload; recovering over REST', {
+ supersedes: message.data.supersedes,
+ bytes: message.data.bytes,
+ maxBytes: message.data.maxBytes,
+ resourceCount: message.data.resourceCount,
+ });
+ requestFullStateRecovery(connectionId);
} else if (message.type === WEBSOCKET.MESSAGE_TYPES.ERROR) {
logger.debug('error', message.error);
} else if (message.type === 'ping') {
@@ -692,30 +787,60 @@ export function createWebSocketStore(url: string) {
}
};
- // Hydrate from the REST snapshot endpoint. `/api/state` serves the same
- // `BuildFrontendState()` value the socket sends as `initialState`, but over a
- // transport with no frame-size ceiling, so it is the only recovery path that
- // works once the snapshot has outgrown the inbound guard. The response is fed
- // through the normal message handler so it establishes the delta baseline
- // exactly as a socket snapshot would.
- const hydrateFullStateFromREST = async () => {
- if (isDisposed || restHydrationInFlight) return;
- restHydrationInFlight = true;
+ const schedulePendingRESTHydration = (connectionId: number, delay: number) => {
+ if (!isCurrentConnection(connectionId)) return;
+ pendingRestHydrationConnectionId = connectionId;
+ if (restHydrationTimeout) return;
+ restHydrationTimeout = window.setTimeout(
+ () => {
+ restHydrationTimeout = 0;
+ if (pendingRestHydrationConnectionId !== connectionId) return;
+ pendingRestHydrationConnectionId = null;
+ requestFullStateRecovery(connectionId);
+ },
+ Math.max(0, delay),
+ );
+ };
+
+ // Hydrate display state from `/api/state`, which has no frame-size ceiling.
+ // It deliberately does not establish a socket delta baseline: the endpoint
+ // builds independently from the snapshot the hub withheld.
+ const hydrateFullStateFromREST = async (connectionId: number) => {
+ if (!isCurrentConnection(connectionId) || restHydrationConnectionId === connectionId) return;
+ restHydrationConnectionId = connectionId;
try {
const snapshot = await apiFetchJSON<State>('/api/state');
- if (isDisposed) return;
+ if (!isCurrentConnection(connectionId)) return;
+ if (rawServerResources !== null) {
+ // A deliverable socket snapshot won the race while REST was pending.
+ // Keep that connection-native baseline instead of replacing it with an
+ // older HTTP response captured before the socket snapshot arrived.
+ return;
+ }
if (!snapshot || typeof snapshot !== 'object') {
logger.error('REST state recovery returned an unusable payload');
return;
}
logger.info('Hydrated full state over REST after an oversized WebSocket snapshot');
- processServerMessage({ type: WEBSOCKET.MESSAGE_TYPES.RAW_DATA, data: snapshot });
+ processServerMessage(
+ { type: WEBSOCKET.MESSAGE_TYPES.RAW_DATA, data: snapshot },
+ connectionId,
+ 'rest',
+ );
} catch (error) {
- // Leave the throttle stamp in place; the next delta without a baseline
- // retries. Failing here is not fatal — the UI stays in its current state.
+ if (!isCurrentConnection(connectionId)) return;
+ // Leave the throttle stamp in place; the next marker or baseline-less
+ // delta retries after the shared recovery window. Failing here is not
+ // fatal — the UI stays in its current state without hammering REST.
logger.error('REST state recovery failed', error);
} finally {
- restHydrationInFlight = false;
+ if (restHydrationConnectionId === connectionId) {
+ restHydrationConnectionId = null;
+ }
+ if (isCurrentConnection(connectionId) && pendingRestHydrationConnectionId === connectionId) {
+ const remaining = Math.max(0, 30000 - (Date.now() - lastFullStateRecoveryAt));
+ schedulePendingRESTHydration(connectionId, remaining);
+ }
}
};
@@ -723,31 +848,46 @@ export function createWebSocketStore(url: string) {
// trigger noticed the gap: a frame dropped as oversized, or a delta arriving
// with no baseline to patch. Sharing one budget keeps a server that repeatedly
// emits an undeliverable snapshot from turning into a REST hammer.
- const requestFullStateRecovery = () => {
+ const requestFullStateRecovery = (connectionId: number) => {
+ if (!isCurrentConnection(connectionId)) return;
const now = Date.now();
- if (now - lastFullStateRecoveryAt < 30000) return;
- lastFullStateRecoveryAt = now;
if (oversizedSnapshotObserved) {
+ if (restHydrationConnectionId === connectionId) {
+ // A marker received after this request started may describe a newer
+ // state than its response. Coalesce one trailing refresh rather than
+ // losing the update or starting concurrent full-state builds.
+ pendingRestHydrationConnectionId = connectionId;
+ return;
+ }
+ const remaining = 30000 - (now - lastFullStateRecoveryAt);
+ if (remaining > 0) {
+ schedulePendingRESTHydration(connectionId, remaining);
+ return;
+ }
+ lastFullStateRecoveryAt = now;
// The socket has already proven it cannot deliver this estate's snapshot.
// `requestData` would just queue another frame the guard drops, which is
// what left large estates stuck on an empty UI, retrying every 30s.
logger.warn('Recovering full state over REST; socket snapshot exceeds the inbound limit');
- void hydrateFullStateFromREST();
+ void hydrateFullStateFromREST(connectionId);
return;
}
+ if (now - lastFullStateRecoveryAt < 30000) return;
+ lastFullStateRecoveryAt = now;
+
logger.warn('Received resource delta without a full snapshot baseline; requesting full state');
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'requestData' }));
}
};
- const setupWebSocket = () => {
- if (!ws || isDisposed) return;
+ const setupWebSocket = (socket: WebSocket, connectionId: number) => {
+ if (!isCurrentConnection(connectionId)) return;
- ws.onopen = () => {
- if (isDisposed) return;
+ socket.onopen = () => {
+ if (!isCurrentConnection(connectionId)) return;
logger.debug('connect');
const wasReconnecting = reconnectAttempt > 0;
setConnected(true);
@@ -760,16 +900,16 @@ export function createWebSocketStore(url: string) {
// Start heartbeat to keep connection alive
clearHeartbeatTimer();
heartbeatInterval = window.setInterval(() => {
- if (ws && ws.readyState === WebSocket.OPEN) {
+ if (isCurrentConnection(connectionId) && socket.readyState === WebSocket.OPEN) {
const silenceDuration = Date.now() - lastServerActivityAt;
if (silenceDuration >= heartbeatTimeoutMs) {
logger.warn('WebSocket heartbeat timeout, forcing reconnect', {
silenceMs: silenceDuration,
});
- ws.close(4000, 'Heartbeat timeout');
+ socket.close(4000, 'Heartbeat timeout');
return;
}
- ws.send(JSON.stringify({ type: 'ping', data: { timestamp: Date.now() } }));
+ socket.send(JSON.stringify({ type: 'ping', data: { timestamp: Date.now() } }));
}
}, heartbeatIntervalMs);
@@ -783,7 +923,8 @@ export function createWebSocketStore(url: string) {
// Alerts will come with the initial state broadcast
};
- ws.onmessage = (event) => {
+ socket.onmessage = (event) => {
+ if (!isCurrentConnection(connectionId)) return;
if (typeof event.data !== 'string') {
logger.warn('Ignoring non-text WebSocket payload');
return;
@@ -801,7 +942,7 @@ export function createWebSocketStore(url: string) {
// paint on a large estate is an empty UI.
oversizedSnapshotObserved = true;
lastServerActivityAt = Date.now();
- requestFullStateRecovery();
+ requestFullStateRecovery(connectionId);
return;
}
@@ -814,19 +955,13 @@ export function createWebSocketStore(url: string) {
}
lastServerActivityAt = Date.now();
- processServerMessage(data);
+ processServerMessage(data, connectionId);
};
- ws.onclose = (event) => {
- if (isDisposed) return;
+ socket.onclose = (event) => {
+ if (isDisposed || !retireConnection(connectionId)) return;
logger.debug('disconnect', { code: event.code, reason: event.reason });
setConnected(false);
- setInitialDataReceived(false);
- // The next connection re-sends the snapshot, so let its recovery fire
- // immediately instead of inheriting this connection's throttle window —
- // otherwise a reconnect on an estate whose snapshot the guard drops can
- // sit unhydrated for up to 30s.
- lastFullStateRecoveryAt = 0;
// Clear heartbeat interval
clearHeartbeatTimer();
@@ -858,8 +993,8 @@ export function createWebSocketStore(url: string) {
handleReconnect();
};
- ws.onerror = (error) => {
- if (isDisposed) return;
+ socket.onerror = (error) => {
+ if (!isCurrentConnection(connectionId)) return;
// Don't log connection errors if we're already connected
// Browser may show errors for initial connection attempts even after success
if (!connected()) {
@@ -875,6 +1010,8 @@ export function createWebSocketStore(url: string) {
onCleanup(() => {
isDisposed = true;
isReconnecting = false;
+ activeConnectionId = null;
+ resetConnectionBaseline();
window.clearTimeout(reconnectDelayTimeout);
window.clearTimeout(reconnectTimeout);
window.clearInterval(heartbeatInterval);
@@ -988,10 +1125,6 @@ export function createWebSocketStore(url: string) {
setRecentlyResolved(reconcile({}));
});
- rawServerResources = null;
- lastFullStateRecoveryAt = 0;
- // A different backend may have an estate that fits the socket guard.
- oversizedSnapshotObserved = false;
clearReconnectTimeout();
clearReconnectDelayTimeout();
reconnectAttempt = 0;
diff --git a/frontend-modern/src/types/api.ts b/frontend-modern/src/types/api.ts
index 21b91051d2..b360850c0d 100644
--- a/frontend-modern/src/types/api.ts
+++ b/frontend-modern/src/types/api.ts
@@ -1344,6 +1344,16 @@ export interface Incident {
export type WSMessage =
| { type: 'initialState'; data: State }
| { type: 'rawData'; data: StateUpdate }
+ | {
+ type: 'stateTooLarge';
+ data: {
+ supersedes: 'initialState' | 'rawData';
+ bytes?: number;
+ maxBytes: number;
+ resourceCount: number;
+ hydrateFrom: '/api/state';
+ };
+ }
| { type: 'error'; error: string }
| { type: 'ping'; data?: unknown }
| { type: 'pong'; data?: unknown }
diff --git a/internal/websocket/hub.go b/internal/websocket/hub.go
index a7f2b6bebb..84b9c59250 100644
--- a/internal/websocket/hub.go
+++ b/internal/websocket/hub.go
@@ -8,6 +8,7 @@ import (
"math"
"net"
"net/http"
+ "strconv"
"strings"
"sync"
"sync/atomic"
@@ -26,10 +27,17 @@ const (
// maxWebSocketInboundMessageSize bounds client->server websocket message size.
maxWebSocketInboundMessageSize = 64 * 1024
// maxWebSocketOrgIDLength keeps org IDs bounded to prevent oversized header/query abuse.
- maxWebSocketOrgIDLength = 64
- websocketHubComponent = "websocket_hub"
- initialWelcomeDelay = 500 * time.Millisecond
- initialStateMessageDelay = 100 * time.Millisecond
+ maxWebSocketOrgIDLength = 64
+ // inboundLimitQueryParam lets a browser declare the largest state frame it
+ // can safely accept before the hub builds that connection's initial state.
+ inboundLimitQueryParam = "max_message_bytes"
+ // minAdvertisedInboundBytes keeps tiny or malicious values from turning
+ // ordinary control messages into an unusable connection.
+ minAdvertisedInboundBytes = 64 * 1024
+ stateTooLargeMessageType = "stateTooLarge"
+ websocketHubComponent = "websocket_hub"
+ initialWelcomeDelay = 500 * time.Millisecond
+ initialStateMessageDelay = 100 * time.Millisecond
// clientReadDeadline is how long a client may stay silent before the server
// drops it. Liveness is proven by ANY inbound frame (data, JSON heartbeat,
// or protocol pong) — proxies and middleboxes (Cloudflare, AV products)
@@ -44,6 +52,14 @@ const (
clientPingPeriod = 30 * time.Second
)
+type stateTooLargePayload struct {
+ Supersedes string `json:"supersedes"`
+ Bytes int `json:"bytes,omitempty"`
+ MaxBytes int64 `json:"maxBytes"`
+ ResourceCount int `json:"resourceCount"`
+ HydrateFrom string `json:"hydrateFrom"`
+}
+
// extractPeerIP extracts just the IP part from a RemoteAddr (host:port format)
func extractPeerIP(remoteAddr string) string {
host, _, err := net.SplitHostPort(remoteAddr)
@@ -275,6 +291,27 @@ type Client struct {
lifecycleOnce sync.Once
stateMu sync.Mutex
stateSnapshot *clientStateSnapshot
+ // restRecovery is protected by stateMu. While set, REST supplies complete
+ // display snapshots and the socket deliberately has no delta baseline.
+ restRecovery bool
+ maxInboundBytes atomic.Int64
+}
+
+func (c *Client) inboundLimitBytes() int64 {
+ return c.maxInboundBytes.Load()
+}
+
+func (c *Client) applyAdvertisedInboundLimit(raw string) {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return
+ }
+ limit, err := strconv.ParseInt(raw, 10, 64)
+ if err != nil || limit < minAdvertisedInboundBytes {
+ log.Debug().Str("client", c.id).Str("value", raw).Msg("ignoring invalid client inbound frame limit")
+ return
+ }
+ c.maxInboundBytes.Store(limit)
}
func (c *Client) lifecycleSignal() chan struct{} {
@@ -334,13 +371,51 @@ func (c *Client) queueFullState(messageType string, state interface{}) (int, boo
c.stateMu.Lock()
defer c.stateMu.Unlock()
+ if limit := c.inboundLimitBytes(); limit > 0 && int64(len(data)) > limit {
+ return c.queueStateTooLargeLocked(messageType, snapshot, len(data), limit)
+ }
if !c.safeSend(data) {
return len(data), false, nil
}
c.stateSnapshot = snapshot
+ c.restRecovery = false
return len(data), true, nil
}
+// queueStateTooLargeLocked sends a compact REST-hydration marker without
+// adopting the state as a delta baseline. REST builds its snapshot later and
+// independently, so treating the withheld state as accepted would let a delta
+// race onto a different baseline. The caller must hold stateMu.
+func (c *Client) queueStateTooLargeLocked(
+ supersedes string,
+ snapshot *clientStateSnapshot,
+ payloadBytes int,
+ limit int64,
+) (int, bool, error) {
+ marker, err := json.Marshal(Message{
+ Type: stateTooLargeMessageType,
+ Data: stateTooLargePayload{
+ Supersedes: supersedes,
+ Bytes: payloadBytes,
+ MaxBytes: limit,
+ ResourceCount: len(snapshot.resourceOrder),
+ HydrateFrom: "/api/state",
+ },
+ })
+ if err != nil {
+ return payloadBytes, false, err
+ }
+
+ // Invalidate first. Even if the marker cannot queue, no later delta may be
+ // based on the payload the client did not receive.
+ c.stateSnapshot = nil
+ c.restRecovery = true
+ if !c.safeSend(marker) {
+ return payloadBytes, false, nil
+ }
+ return payloadBytes, true, nil
+}
+
func (c *Client) queueStateDelta(current *clientStateSnapshot) (int, bool, bool, error) {
if current == nil {
return 0, false, false, fmt.Errorf("current state snapshot is nil")
@@ -348,6 +423,15 @@ func (c *Client) queueStateDelta(current *clientStateSnapshot) (int, bool, bool,
c.stateMu.Lock()
defer c.stateMu.Unlock()
+ if c.restRecovery {
+ dataLen, sent, markerErr := c.queueStateTooLargeLocked(
+ "rawData",
+ current,
+ 0,
+ c.inboundLimitBytes(),
+ )
+ return dataLen, true, sent, markerErr
+ }
if c.stateSnapshot == nil {
// Initial hydration owns the baseline. A client still waiting for that
// payload must not receive a delta based on state it has never seen.
@@ -366,6 +450,10 @@ func (c *Client) queueStateDelta(current *clientStateSnapshot) (int, bool, bool,
if err != nil {
return 0, true, false, err
}
+ if limit := c.inboundLimitBytes(); limit > 0 && int64(len(data)) > limit {
+ dataLen, sent, markerErr := c.queueStateTooLargeLocked("rawData", current, len(data), limit)
+ return dataLen, true, sent, markerErr
+ }
if !c.safeSend(data) {
return len(data), true, false, nil
}
@@ -1022,6 +1110,9 @@ func (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
id: clientID,
lastPing: time.Now(),
}
+ // This must be captured from the upgrade URL before registration: initial
+ // state construction begins as soon as the hub accepts the client.
+ client.applyAdvertisedInboundLimit(r.URL.Query().Get(inboundLimitQueryParam))
log.Info().Str("client", clientID).Str("org_id", orgID).Msg("webSocket client created")
diff --git a/internal/websocket/hub_client_frame_limit_test.go b/internal/websocket/hub_client_frame_limit_test.go
new file mode 100644
index 0000000000..f6637f544d
--- /dev/null
+++ b/internal/websocket/hub_client_frame_limit_test.go
@@ -0,0 +1,217 @@
+package websocket
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/gorilla/websocket"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+func paddedFrontendState(count, padBytes int) models.StateFrontend {
+ state := models.EmptyStateFrontend()
+ state.LastUpdate = 100
+ state.Resources = make([]models.ResourceFrontend, 0, count)
+ for i := range count {
+ id := fmt.Sprintf("agent:host-%d", i)
+ state.Resources = append(state.Resources, models.ResourceFrontend{
+ ID: id,
+ Type: "agent",
+ Name: id,
+ DisplayName: id,
+ PlatformData: json.RawMessage(`{"pad":"` + strings.Repeat("x", padBytes) + `"}`),
+ })
+ }
+ return state
+}
+
+func decodeStateTooLargeMarker(t *testing.T, raw []byte) stateTooLargePayload {
+ t.Helper()
+ var message struct {
+ Type string `json:"type"`
+ Data stateTooLargePayload `json:"data"`
+ }
+ if err := json.Unmarshal(raw, &message); err != nil {
+ t.Fatalf("decode marker: %v", err)
+ }
+ if message.Type != stateTooLargeMessageType {
+ t.Fatalf("message type = %q, want %q", message.Type, stateTooLargeMessageType)
+ }
+ return message.Data
+}
+
+func TestOversizedFullStateEntersBaselineFreeRESTRecovery(t *testing.T) {
+ state := paddedFrontendState(20, 4*1024)
+ client := &Client{send: make(chan []byte, 1)}
+ client.maxInboundBytes.Store(minAdvertisedInboundBytes)
+
+ dataLen, sent, err := client.queueFullState("initialState", state)
+ if err != nil || !sent {
+ t.Fatalf("queueFullState() bytes=%d sent=%v error=%v", dataLen, sent, err)
+ }
+ marker := decodeStateTooLargeMarker(t, <-client.send)
+ if marker.Supersedes != "initialState" || marker.Bytes != dataLen {
+ t.Fatalf("marker = %+v, want initialState and %d bytes", marker, dataLen)
+ }
+ if marker.MaxBytes != minAdvertisedInboundBytes || marker.HydrateFrom != "/api/state" {
+ t.Fatalf("marker negotiation = %+v", marker)
+ }
+ if client.stateSnapshot != nil || !client.restRecovery {
+ t.Fatal("withheld snapshot became a delta baseline")
+ }
+}
+
+func TestRESTRecoverySendsMarkersWithoutAdvancingDeltaBaseline(t *testing.T) {
+ initial := paddedFrontendState(20, 4*1024)
+ client := &Client{send: make(chan []byte, 2)}
+ client.maxInboundBytes.Store(minAdvertisedInboundBytes)
+ if _, sent, err := client.queueFullState("initialState", initial); err != nil || !sent {
+ t.Fatalf("queueFullState() sent=%v error=%v", sent, err)
+ }
+ <-client.send
+
+ current := paddedFrontendState(20, 4*1024)
+ current.LastUpdate = 200
+ currentSnapshot, err := buildClientStateSnapshot(current)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, attempted, sent, err := client.queueStateDelta(currentSnapshot)
+ if err != nil || !attempted || !sent {
+ t.Fatalf("queueStateDelta() attempted=%v sent=%v error=%v", attempted, sent, err)
+ }
+ marker := decodeStateTooLargeMarker(t, <-client.send)
+ if marker.Supersedes != "rawData" {
+ t.Fatalf("marker supersedes = %q, want rawData", marker.Supersedes)
+ }
+ if client.stateSnapshot != nil || !client.restRecovery {
+ t.Fatal("REST recovery marker advanced the delta baseline")
+ }
+}
+
+func TestOversizedDeltaInvalidatesPreviouslyDeliveredBaseline(t *testing.T) {
+ initial := paddedFrontendState(20, 4*1024)
+ client := &Client{send: make(chan []byte, 2)}
+ if _, sent, err := client.queueFullState("initialState", initial); err != nil || !sent {
+ t.Fatalf("queueFullState() sent=%v error=%v", sent, err)
+ }
+ <-client.send
+ client.maxInboundBytes.Store(minAdvertisedInboundBytes)
+
+ current := paddedFrontendState(20, 4*1024)
+ current.LastUpdate = 200
+ for i := range current.Resources {
+ current.Resources[i].PlatformData = json.RawMessage(
+ `{"pad":"` + strings.Repeat("y", 4*1024) + `"}`,
+ )
+ }
+ currentSnapshot, err := buildClientStateSnapshot(current)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dataLen, attempted, sent, err := client.queueStateDelta(currentSnapshot)
+ if err != nil || !attempted || !sent {
+ t.Fatalf("queueStateDelta() bytes=%d attempted=%v sent=%v error=%v", dataLen, attempted, sent, err)
+ }
+ marker := decodeStateTooLargeMarker(t, <-client.send)
+ if marker.Bytes != dataLen || marker.Supersedes != "rawData" {
+ t.Fatalf("marker = %+v, want oversized rawData of %d bytes", marker, dataLen)
+ }
+ if client.stateSnapshot != nil || !client.restRecovery {
+ t.Fatal("oversized delta left an accepted baseline behind")
+ }
+}
+
+func TestDeliverableFullStateExitsRESTRecovery(t *testing.T) {
+ client := &Client{send: make(chan []byte, 2)}
+ client.maxInboundBytes.Store(minAdvertisedInboundBytes)
+ if _, sent, err := client.queueFullState("initialState", paddedFrontendState(20, 4*1024)); err != nil || !sent {
+ t.Fatalf("oversized queueFullState() sent=%v error=%v", sent, err)
+ }
+ <-client.send
+
+ small := paddedFrontendState(1, 32)
+ if _, sent, err := client.queueFullState("rawData", small); err != nil || !sent {
+ t.Fatalf("deliverable queueFullState() sent=%v error=%v", sent, err)
+ }
+ var message Message
+ if err := json.Unmarshal(<-client.send, &message); err != nil {
+ t.Fatal(err)
+ }
+ if message.Type != "rawData" {
+ t.Fatalf("message type = %q, want rawData", message.Type)
+ }
+ if client.stateSnapshot == nil || client.restRecovery {
+ t.Fatal("delivered full state did not establish the new delta baseline")
+ }
+}
+
+func TestApplyAdvertisedInboundLimit(t *testing.T) {
+ tests := []struct {
+ raw string
+ want int64
+ }{
+ {raw: "8388608", want: 8 * 1024 * 1024},
+ {raw: " 8388608 ", want: 8 * 1024 * 1024},
+ {raw: ""},
+ {raw: "1024"},
+ {raw: "not-a-number"},
+ }
+ for _, test := range tests {
+ client := &Client{}
+ client.applyAdvertisedInboundLimit(test.raw)
+ if got := client.inboundLimitBytes(); got != test.want {
+ t.Fatalf("applyAdvertisedInboundLimit(%q) = %d, want %d", test.raw, got, test.want)
+ }
+ }
+}
+
+func TestWebSocketUpgradeNegotiatesLimitBeforeInitialState(t *testing.T) {
+ hub := NewHub(func(string) interface{} {
+ return paddedFrontendState(20, 4*1024)
+ })
+ go hub.Run()
+ t.Cleanup(hub.Stop)
+
+ server := httptest.NewServer(http.HandlerFunc(hub.HandleWebSocket))
+ defer server.Close()
+ wsURL := "ws" + strings.TrimPrefix(server.URL, "http") +
+ "?org_id=default&max_message_bytes=65536"
+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, wsHeadersForHTTP(t, server.URL))
+ if err != nil {
+ t.Fatalf("dial websocket: %v", err)
+ }
+ defer conn.Close()
+ if err := conn.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+
+ for {
+ _, raw, readErr := conn.ReadMessage()
+ if readErr != nil {
+ t.Fatalf("read negotiated initial state: %v", readErr)
+ }
+ var envelope struct {
+ Type string `json:"type"`
+ }
+ if err := json.Unmarshal(raw, &envelope); err != nil {
+ t.Fatal(err)
+ }
+ if envelope.Type == "welcome" {
+ continue
+ }
+ if envelope.Type != stateTooLargeMessageType {
+ t.Fatalf("initial state message type = %q, want %q", envelope.Type, stateTooLargeMessageType)
+ }
+ marker := decodeStateTooLargeMarker(t, raw)
+ if marker.MaxBytes != minAdvertisedInboundBytes {
+ t.Fatalf("negotiated maxBytes = %d, want %d", marker.MaxBytes, minAdvertisedInboundBytes)
+ }
+ return
+ }
+}