Files
worldwideview/src/core/data/WsClient.ts
SilvertakanaandCopilot Autofix powered by AI 16c82c9184 refactor(lint): address React 19 hook purity and immutability violations (#136)
* chore(merge): resolve conflicts, fix mockWs error, and apply refactor standards

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* fix(ci): Stabilize github actions and resolve test failures

- fix(tests): update WsClient mock to use standard function for Vitest constructor compatibility

- fix(db): correct PrismaClient import path to use generated output directory

- fix(e2e): add predev database boot step to playwright CI workflow

- chore: sync pnpm-lock.yaml after merge conflict resolution

* refactor(plugins): decouple GeoJSON plugin and implement data bus lifecycle

- feat(sdk): [Minor] Added dynamicPluginCreate, dynamicPluginRemove, and pluginUnregistered to DataBusEvents.

- feat(core): [Minor] Implemented unregisterPlugin in PluginManager.ts for automated IndexedDB caching cleanup and polling teardown.

- feat(core): [Minor] Added removeLayer to layersSlice.ts to support safe removal of plugin states.

- refactor(plugins): [Patch] Refactored useGeoJsonImport.ts and ImportedLayerList.tsx to decouple from direct manager imports, utilizing DataBus for lifecycle events.

- refactor(core): [Patch] Added pluginUnregistered listener to DataBusSubscriber.tsx to handle state and cache cleanup synchronously via event.

* fix(types): resolve PluginManager type errors

* refactor(core): decouple PluginManager and fix rendering invariants

- refactor(core): Replace Zustand mutations in PluginManager with DataBus events (Patch)
- refactor(sdk): Add layerLoadingChanged, pluginError, pluginUnregistered to DataBusEvents (Patch)
- refactor(ui): Subscribe to new DataBus events in DataBusSubscriber (Patch)
- fix(plugins): Remove size from BaseAviationPlugin to fix model rendering clipping (Patch)
- fix(plugins): Migrate BaseIncidentPlugin from size to iconScale to fix billboard clipping (Patch)

* chore: resolve lockfile conflict

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-05-16 13:03:05 +12:00

173 lines
5.9 KiB
TypeScript

import type { WsStreamPayload, GeoEntity } from "@worldwideview/wwv-plugin-sdk";
import { dataBus } from "./DataBus";
import { pluginManager } from "../plugins/PluginManager";
import { useStore } from "../state/store";
interface EngineConnection {
ws: WebSocket | null;
reconnectTimer: NodeJS.Timeout | null;
subscriptions: Set<string>;
/** Grace period timer — closes the connection if no plugins remain subscribed */
cleanupTimer: NodeJS.Timeout | null;
}
const RECONNECT_DELAY_MS = 5000;
const CLEANUP_GRACE_MS = 30000;
class WebSocketClient {
private engines = new Map<string, EngineConnection>();
private getOrCreateEngine(engineUrl: string): EngineConnection {
let engine = this.engines.get(engineUrl);
if (!engine) {
engine = {
ws: null,
reconnectTimer: null,
subscriptions: new Set(),
cleanupTimer: null,
};
this.engines.set(engineUrl, engine);
}
return engine;
}
private connectEngine(engineUrl: string) {
const engine = this.getOrCreateEngine(engineUrl);
if (engine.ws && (engine.ws.readyState === WebSocket.CONNECTING || engine.ws.readyState === WebSocket.OPEN)) {
return;
}
const wsStart = performance.now();
engine.ws = new WebSocket(engineUrl);
engine.ws.onopen = () => {
console.debug(`[WSClient] 🟢 Connected to ${engineUrl}. WS Handshake took ${(performance.now() - wsStart).toFixed(2)}ms`);
// Resubscribe to all active plugins on this engine
for (const pluginId of engine.subscriptions) {
this.send(engine, { action: "subscribe", pluginId });
}
};
engine.ws.onmessage = (event) => {
try {
const msgTime = performance.now();
console.debug(`[WSClient] 📥 Received raw message at +${(msgTime - wsStart).toFixed(2)}ms from start:`, event.data.substring(0, 150) + (event.data.length > 150 ? '...' : ''));
const data = JSON.parse(event.data);
// Handle welcome message (informational, no action needed)
if (data.type === "welcome") {
console.debug(`[WSClient] 👋 Engine ${engineUrl} serves: ${data.plugins?.join(", ")}`);
return;
}
if (data.type === "data" && data.pluginId && data.payload) {
this.handleDataMessage(data as WsStreamPayload);
}
} catch (err) {
console.error("[WSClient] Error parsing message:", err);
}
};
engine.ws.onerror = () => {
console.warn(`[WSClient] Connection to ${engineUrl} failed. Retrying in background...`);
};
engine.ws.onclose = () => {
console.warn(`[WSClient] Disconnected from ${engineUrl}. Reconnecting in 5s...`);
engine.ws = null;
if (engine.reconnectTimer) clearTimeout(engine.reconnectTimer);
// Only reconnect if there are still active subscriptions
if (engine.subscriptions.size > 0) {
engine.reconnectTimer = setTimeout(() => this.connectEngine(engineUrl), RECONNECT_DELAY_MS);
}
};
}
private handleDataMessage(data: WsStreamPayload) {
const plugin = pluginManager.getPlugin(data.pluginId!)?.plugin;
let finalEntities = data.payload as GeoEntity[];
const existingEntities = useStore.getState().entitiesByPlugin[data.pluginId!] || [];
if (plugin && typeof (plugin as any).mapWebsocketPayload === "function") {
finalEntities = (plugin as any).mapWebsocketPayload(data.payload, existingEntities);
} else if (!Array.isArray(data.payload)) {
console.warn(`[WsClient] Payload for ${data.pluginId} is an object but no mapWebsocketPayload exists. Ignoring.`);
return;
} else {
finalEntities = finalEntities.map((e) => ({
...e,
timestamp: new Date(e.timestamp || Date.now()),
}));
}
console.debug(`[WSClient] 🔄 Dispatching ${finalEntities.length} entities for ${data.pluginId} to DataBus`);
dataBus.emit("dataUpdated", {
pluginId: data.pluginId!,
entities: finalEntities,
});
}
private send(engine: EngineConnection, msg: any) {
if (engine.ws && engine.ws.readyState === WebSocket.OPEN) {
engine.ws.send(JSON.stringify(msg));
}
}
public subscribe(pluginId: string, engineUrl: string) {
console.debug(`[WSClient] 📡 Subscribing to ${pluginId} at ${engineUrl}`);
const engine = this.getOrCreateEngine(engineUrl);
// Cancel any pending cleanup
if (engine.cleanupTimer) {
clearTimeout(engine.cleanupTimer);
engine.cleanupTimer = null;
}
engine.subscriptions.add(pluginId);
this.connectEngine(engineUrl);
this.send(engine, { action: "subscribe", pluginId });
}
public unsubscribe(pluginId: string, engineUrl: string) {
const engine = this.engines.get(engineUrl);
if (!engine) return;
engine.subscriptions.delete(pluginId);
this.send(engine, { action: "unsubscribe", pluginId });
// If no more subscriptions for this engine, schedule cleanup
if (engine.subscriptions.size === 0) {
engine.cleanupTimer = setTimeout(() => {
if (engine.subscriptions.size === 0) {
console.log(`[WSClient] No subscriptions remain for ${engineUrl}. Closing connection.`);
if (engine.reconnectTimer) clearTimeout(engine.reconnectTimer);
engine.ws?.close();
this.engines.delete(engineUrl);
}
}, CLEANUP_GRACE_MS);
}
}
public printConnections() {
const table: any[] = [];
this.engines.forEach((engine, url) => {
table.push({
'Engine URL': url,
Status: engine.ws ? ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'][engine.ws.readyState] || 'UNKNOWN' : 'DISCONNECTED',
'Plugins Subscribed': Array.from(engine.subscriptions).join(", ") || "(None)",
});
});
console.groupCollapsed("[WSClient] Active Engine Connections Matrix");
console.table(table);
console.groupEnd();
}
}
export const wsClient = new WebSocketClient();
if (typeof window !== "undefined") {
(window as any).wwvDebugConnections = () => wsClient.printConnections();
}