57 lines
1.7 KiB
JavaScript
57 lines
1.7 KiB
JavaScript
import { ensureEarthSession, getCachedEarthWsToken } from "./earth-session.js";
|
|
|
|
const WS_BACKOFF_BASE_MS = 5_000;
|
|
const WS_BACKOFF_MAX_MS = 60_000;
|
|
|
|
const wsBackoffState = {
|
|
failures: 0,
|
|
nextAttemptAt: 0,
|
|
};
|
|
|
|
export function getEarthRealtimeUrl() {
|
|
const configuredWsUrl = globalThis.__PLANET_RUNTIME_CONFIG__?.wsUrl;
|
|
if (typeof configuredWsUrl === "string" && configuredWsUrl.trim()) {
|
|
return configuredWsUrl.trim();
|
|
}
|
|
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 async function resolveEarthRealtimeUrl() {
|
|
const baseUrl = getEarthRealtimeUrl();
|
|
const token = getCachedEarthWsToken() || (await ensureEarthSession());
|
|
if (!token) {
|
|
return baseUrl;
|
|
}
|
|
const separator = baseUrl.includes("?") ? "&" : "?";
|
|
return `${baseUrl}${separator}earth_token=${encodeURIComponent(token)}`;
|
|
}
|
|
|
|
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;
|
|
}
|