59 lines
1.6 KiB
JavaScript
59 lines
1.6 KiB
JavaScript
import { applyRuntimeUpdate } from "./segments.js";
|
|
|
|
const RECONNECT_INITIAL_MS = 1_000;
|
|
const RECONNECT_MAX_MS = 30_000;
|
|
let socket = null;
|
|
let reconnectDelay = RECONNECT_INITIAL_MS;
|
|
|
|
function setWsStatus(connected) {
|
|
const dot = document.getElementById("wsDot");
|
|
const label = document.getElementById("wsLabel");
|
|
if (dot) {
|
|
dot.classList.toggle("connected", connected);
|
|
dot.classList.toggle("disconnected", !connected);
|
|
}
|
|
if (label) {
|
|
label.textContent = connected ? "已连接" : "连接断开,重连中…";
|
|
}
|
|
}
|
|
|
|
function handleMessage(payload) {
|
|
if (!payload || typeof payload !== "object") return;
|
|
if (payload.type !== "app_event") return;
|
|
const event = payload.data;
|
|
if (!event || event.app !== "operation-system") return;
|
|
if (event.event_type === "segment_runtime_changed") {
|
|
applyRuntimeUpdate(event.data);
|
|
}
|
|
}
|
|
|
|
export function startOpsSocket() {
|
|
const protocol = location.protocol === "https:" ? "wss" : "ws";
|
|
const ws = new WebSocket(`${protocol}://${location.host}/ws/public`);
|
|
socket = ws;
|
|
|
|
ws.onopen = () => {
|
|
setWsStatus(true);
|
|
reconnectDelay = RECONNECT_INITIAL_MS;
|
|
};
|
|
|
|
ws.onmessage = (event) => {
|
|
try {
|
|
const payload = JSON.parse(event.data);
|
|
handleMessage(payload);
|
|
} catch (err) {
|
|
// Tolerate non-JSON pings.
|
|
console.debug("ops ws non-json message", err);
|
|
}
|
|
};
|
|
|
|
ws.onclose = () => {
|
|
setWsStatus(false);
|
|
socket = null;
|
|
window.setTimeout(startOpsSocket, reconnectDelay);
|
|
reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
|
|
};
|
|
|
|
ws.onerror = () => setWsStatus(false);
|
|
}
|