mirror of
https://github.com/stablyai/orca.git
synced 2026-10-01 08:01:56 +00:00
76 lines
2.4 KiB
TypeScript
76 lines
2.4 KiB
TypeScript
// Why: a half-open tunnel (devtunnel/NAT drop) never delivers a ws `close`,
|
|
// so edge-triggered reconnect logic on the client side never fires while the
|
|
// server has long since reaped its end (#7718/#7489). This monitor gives
|
|
// client sockets a level-based liveness check: ping on a cadence and declare
|
|
// the socket dead when no inbound traffic (frames, pings, or pongs) arrives
|
|
// within the window, so the existing close/reconnect path can run.
|
|
|
|
// Why: pings ride the RFC 6455 control-frame layer, which every supported
|
|
// server (and the `ws` package it embeds) answers automatically — this stays
|
|
// backward compatible with old servers that predate client-side liveness.
|
|
export const REMOTE_RUNTIME_SOCKET_PING_INTERVAL_MS = 10_000
|
|
// Why: just under two server heartbeat periods (15s), so a dead link is
|
|
// detected on a similar horizon to the server's own ping/terminate reaper.
|
|
export const REMOTE_RUNTIME_SOCKET_LIVENESS_TIMEOUT_MS = 25_000
|
|
|
|
export type RemoteRuntimeSocketLivenessOptions = {
|
|
pingIntervalMs?: number
|
|
livenessTimeoutMs?: number
|
|
}
|
|
|
|
export type RemoteRuntimeSocketLivenessMonitor = {
|
|
noteActivity: () => void
|
|
stop: () => void
|
|
}
|
|
|
|
export function startRemoteRuntimeSocketLiveness(args: {
|
|
ping: () => void
|
|
onDead: () => void
|
|
options?: RemoteRuntimeSocketLivenessOptions
|
|
now?: () => number
|
|
}): RemoteRuntimeSocketLivenessMonitor {
|
|
const now = args.now ?? Date.now
|
|
const pingIntervalMs = args.options?.pingIntervalMs ?? REMOTE_RUNTIME_SOCKET_PING_INTERVAL_MS
|
|
const livenessTimeoutMs =
|
|
args.options?.livenessTimeoutMs ?? REMOTE_RUNTIME_SOCKET_LIVENESS_TIMEOUT_MS
|
|
let lastActivityAt = now()
|
|
let stopped = false
|
|
|
|
const timer = setInterval(() => {
|
|
if (stopped) {
|
|
return
|
|
}
|
|
if (now() - lastActivityAt > livenessTimeoutMs) {
|
|
stop()
|
|
args.onDead()
|
|
return
|
|
}
|
|
try {
|
|
args.ping()
|
|
} catch {
|
|
// Why: ping() can throw while a socket is mid-teardown; the liveness
|
|
// window (or the close handler) settles the socket's fate either way.
|
|
}
|
|
}, pingIntervalMs)
|
|
// Why: mobile typechecks shared code with DOM timer types where unref is absent.
|
|
const unrefable = timer as unknown as { unref?: () => void }
|
|
if (typeof unrefable.unref === 'function') {
|
|
unrefable.unref()
|
|
}
|
|
|
|
function stop(): void {
|
|
if (stopped) {
|
|
return
|
|
}
|
|
stopped = true
|
|
clearInterval(timer)
|
|
}
|
|
|
|
return {
|
|
noteActivity: () => {
|
|
lastActivityAt = now()
|
|
},
|
|
stop
|
|
}
|
|
}
|