Files
planet/frontend/public/earth/js/realtime.js
T
linkong b3d2d9e9f1
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release: bump version to 0.81.0
2026-11-30 19:39:29 +08:00

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;
}