41 lines
1.1 KiB
JavaScript
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;
|
|
}
|