Files
planet/frontend/public/earth/js/realtime.js
linkong acbbfdf9e2
Some checks failed
ci / backend (push) Has been cancelled
ci / frontend (push) Has been cancelled
ci / delivery (push) Has been cancelled
release / images (push) Has been cancelled
release: bump version to 0.69.0
2026-06-03 17:27:00 +08:00

41 lines
1.1 KiB
JavaScript

const WS_BACKOFF_BASE_MS = 5_000;
const WS_BACKOFF_MAX_MS = 60_000;
const wsBackoffState = {
failures: 0,
nextAttemptAt: 0,
};
export function getEarthRealtimeUrl() {
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const host = window.location.hostname;
const port = window.location.port;
if ((host === "localhost" || host === "127.0.0.1") && port === "3000") {
return `${protocol}//${host}:8000/ws`;
}
return `${protocol}//${window.location.host}/ws`;
}
export function getEarthRealtimeCooldownMs() {
return Math.max(0, wsBackoffState.nextAttemptAt - Date.now());
}
export function canAttemptEarthRealtime() {
return typeof WebSocket !== "undefined" && getEarthRealtimeCooldownMs() <= 0;
}
export function recordEarthRealtimeOpen() {
wsBackoffState.failures = 0;
wsBackoffState.nextAttemptAt = 0;
}
export function recordEarthRealtimeFailure() {
wsBackoffState.failures += 1;
const delay = Math.min(
WS_BACKOFF_MAX_MS,
WS_BACKOFF_BASE_MS * 2 ** Math.min(wsBackoffState.failures - 1, 5),
);
wsBackoffState.nextAttemptAt = Date.now() + delay;
return delay;
}