fix: recover from silent network drops on both sides of the gateway

Measured with relays that blackhole traffic:

- Gateway to TS server: tsclientlib reconnects on its own after a timeout or
  server restart, but the connector ignored that, so the browser got no notice
  and the new session stayed unsubscribed - everyone but us vanished from the
  tree. The connector now emits "reconnecting"/"reconnected", resubscribes,
  and pauses the server-variable poll meanwhile; the page logs both.
- Browser to gateway: a network that dies silently never closed the socket on
  the page, which kept showing "connected" indefinitely. The gateway now sends
  an app-level keepalive every 20 s (announced as "keepalive" in hello), and
  a socket quiet for 50 s is handled as dropped and reconnected.
- Coming back online skips any remaining reconnect backoff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
MoepchiandClaude Opus 5.5 committed 2026-10-03 01:37:13 +00:00
1 parent 23e61c86b3
commit 12e482b223
8 files changed
+81 -4

No files matched your search

+21 -1
View File
@@ -293,6 +293,12 @@ enum Event {
Talkers { clients: Vec<u16> },
#[serde(rename = "disconnected")]
Disconnected { reason: String },
/// Lost the server (timeout, server restart); tsclientlib is reconnecting
/// on its own. Followed by "reconnected" once it is back.
#[serde(rename = "reconnecting")]
Reconnecting { reason: String },
#[serde(rename = "reconnected")]
Reconnected,
#[serde(rename = "error")]
Error { message: String },
/// A "switch" to a password-protected channel was rejected because no (or
@@ -1060,6 +1066,7 @@ async fn run(args: Args) -> Result<()> {
// TeaSpeak may reveal hidden channels after a group/permission change. Debounce
// a channelsubscribeall so we pick up any channels the server only exposes then.
let mut resubscribe_at: Option<tokio::time::Instant> = None;
let mut ts_reconnecting = false;
enum LoopOutcome {
StdinLine(std::io::Result<Option<String>>),
@@ -2437,6 +2444,13 @@ async fn run(args: Args) -> Result<()> {
},
LoopOutcome::ConEvent(ev) => match ev {
Some(Ok(StreamItem::BookEvents(events))) => {
if ts_reconnecting {
// The new session starts unsubscribed, which would leave
// everyone but us invisible.
ts_reconnecting = false;
resubscribe_at = Some(tokio::time::Instant::now());
emit(&Event::Reconnected);
}
let own_id = con.get_state()?.own_client;
for event in &events {
if let BookEvent::Message { target, invoker, message } = event {
@@ -3008,6 +3022,10 @@ async fn run(args: Args) -> Result<()> {
emit(&Event::Error { message: format!("File transfer failed: {e}") });
}
}
Some(Ok(StreamItem::DisconnectedTemporarily(reason))) => {
ts_reconnecting = true;
emit(&Event::Reconnecting { reason: format!("{reason:?}") });
}
Some(Ok(_)) => {}
Some(Err(e)) => {
emit(&Event::Disconnected { reason: e.to_string() });
@@ -3029,7 +3047,9 @@ async fn run(args: Args) -> Result<()> {
}
}
LoopOutcome::ServerVarsRefresh => {
send_server_get_variables(&mut con);
if !ts_reconnecting {
send_server_get_variables(&mut con);
}
}
LoopOutcome::AudioTick => {
if !audio_handler.get_queues().is_empty() {
+4 -1
View File
@@ -112,7 +112,7 @@ const WEB_DIST = process.env.WEB_DIST ?? path.resolve(__dirname, "../../web/dist
const SERVE_STATIC = process.env.WEB_STATIC !== "0";
// Sent to every browser in the "hello" message on socket open; see there.
const GATEWAY_FEATURES = ["clientVolume"];
const GATEWAY_FEATURES = ["clientVolume", "keepalive"];
// Optional TURN relay for screen streams, also handed out in "hello". With
// TURN_SECRET (coturn's use-auth-secret) every socket gets its own credential,
@@ -585,6 +585,9 @@ const heartbeatTimer = setInterval(() => {
}
state.isAlive = false;
socket.ping();
// Protocol pings are invisible to browser JS; this lets the page notice
// a dead network on its side too (KEEPALIVE_MESSAGE in web/src/App.tsx).
socket.send('{"type":"keepalive"}');
}
}, HEARTBEAT_INTERVAL_MS);
+4
View File
@@ -154,6 +154,8 @@ export type Ts3ConnectionEvent =
| { type: "audioOut"; pcm: string }
| { type: "talkers"; clients: number[] }
| { type: "disconnected"; reason: string }
| { type: "reconnecting"; reason: string }
| { type: "reconnected" }
| { type: "error"; message: string }
| { type: "channelPasswordRequired"; channelId: number }
| ({ type: "serverLog" } & ServerLogEntry)
@@ -362,6 +364,8 @@ export class Ts3Connection {
| { type: "audioOut"; pcm: string }
| { type: "talkers"; clients: number[] }
| { type: "disconnected"; reason: string }
| { type: "reconnecting"; reason: string }
| { type: "reconnected" }
| { type: "error"; message: string }
| { type: "channelPasswordRequired"; channel_id: number }
| ({ type: "serverLog" } & ServerLogEntry)
+44 -2
View File
@@ -7449,6 +7449,17 @@ function AppInner() {
case "talkers":
setTalkers(new Set<number>(data.clients));
break;
case "reconnecting":
// The gateway lost the TS server and is reconnecting by itself.
appendLog({ text: t("log.serverReconnecting"), kind: "error" });
logClient("warning", "Connection", `Lost the server, reconnecting: ${data.reason}`);
updateTabMeta(sessionId, { connecting: true });
break;
case "reconnected":
appendLog({ text: t("log.serverReconnected"), kind: "info" });
logClient("info", "Connection", "Reconnected to the server");
updateTabMeta(sessionId, { connecting: false });
break;
case "streamEvent": {
const streamEvent = data as StreamEvent;
if (streamEvent.name === "notifystreaminfo" || streamEvent.name === "notifystreamstarted") {
@@ -7744,10 +7755,28 @@ function AppInner() {
const wireSocket = (sessionId: string, socket: WebSocket | DemoSocket, params: ConnectParams) => {
const current = () => socketHandlersRef.current(sessionId, socket, params);
let watchdog: ReturnType<typeof setTimeout> | undefined;
socket.onopen = () => current().onopen();
socket.onmessage = (event) => current().onmessage(event);
socket.onmessage = (event) => {
// Armed by the "hello" announcing "keepalive", or by the first keepalive.
// The quoted word cannot come from user text, where JSON escapes quotes.
if (watchdog !== undefined || String(event.data).includes('"keepalive"')) {
clearTimeout(watchdog);
watchdog = setTimeout(() => {
// close() on a dead link may take a minute to fire onclose, so
// detach and run the drop handling right away.
socket.onmessage = socket.onerror = socket.onclose = null;
socket.close();
current().onclose();
}, KEEPALIVE_TIMEOUT_MS);
}
if (event.data !== KEEPALIVE_MESSAGE) current().onmessage(event);
};
socket.onerror = () => current().onerror();
socket.onclose = () => current().onclose();
socket.onclose = () => {
clearTimeout(watchdog);
current().onclose();
};
};
const handleConnect = (overrides?: {
@@ -7878,6 +7907,11 @@ function AppInner() {
// instantly, which without a delay would tight-loop). Reset to 0 once a
// session actually reaches "connected" again (see the two spots below).
const reconnectAttemptsRef = useRef<Map<string, number>>(new Map());
// The gateway sends this every 20 s (heartbeat in gateway/src/index.ts). A
// network that dies silently never closes the socket on this side, so a
// socket that stays quiet this long counts as dropped.
const KEEPALIVE_MESSAGE = '{"type":"keepalive"}';
const KEEPALIVE_TIMEOUT_MS = 50_000;
const reconnectTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
const scheduleReconnect = (sessionId: string) => {
if (reconnectTimersRef.current.has(sessionId)) return; // already scheduled
@@ -7939,11 +7973,19 @@ function AppInner() {
}
};
// Back online: retry now instead of waiting out a backoff of up to 30 s.
const onOnline = () => {
reconnectAttemptsRef.current.clear();
for (const id of sessionsRef.current.keys()) reconnectSessionRef.current(id);
};
document.addEventListener("visibilitychange", onVisibilityChange);
window.addEventListener("online", onOnline);
requestWakeLock();
return () => {
document.removeEventListener("visibilitychange", onVisibilityChange);
window.removeEventListener("online", onOnline);
releaseWakeLock();
};
}, [sessionTabs.length]);
+2
View File
@@ -659,6 +659,8 @@
"tabs.closeTab": "Tab schließen: {label}",
"identity.importInvalid": "„{file}“ ist keine gültige Identitätsdatei.",
"log.fileTransferFailed": "Dateiübertragung fehlgeschlagen:",
"log.serverReconnecting": "Verbindung zum Server verloren, verbinde neu…",
"log.serverReconnected": "Wieder mit dem Server verbunden",
"log.fileTransferInvalidAddress": "Dateiübertragung fehlgeschlagen (ungültige Adresse)",
"sounds.importFailed": "Das Soundpack konnte nicht gelesen werden – ist es eine gültige .ts3soundpack-/ZIP-Datei?",
"tabs.connections": "Server-Verbindungen",
+2
View File
@@ -659,6 +659,8 @@
"tabs.closeTab": "Close tab: {label}",
"identity.importInvalid": "\"{file}\" is not a valid identity file.",
"log.fileTransferFailed": "File transfer failed:",
"log.serverReconnecting": "Connection to the server lost, reconnecting…",
"log.serverReconnected": "Reconnected to the server",
"log.fileTransferInvalidAddress": "File transfer failed (invalid address)",
"sounds.importFailed": "Could not read this soundpack - is it a valid .ts3soundpack/ZIP file?",
"tabs.connections": "Server connections",
+2
View File
@@ -658,6 +658,8 @@
"tabs.closeTab": "بستن زبانه: {label}",
"identity.importInvalid": "«{file}» یک فایل هویت معتبر نیست.",
"log.fileTransferFailed": "انتقال فایل ناموفق بود:",
"log.serverReconnecting": "اتصال به سرور قطع شد، در حال اتصال دوباره…",
"log.serverReconnected": "دوباره به سرور متصل شد",
"log.fileTransferInvalidAddress": "انتقال فایل ناموفق بود (نشانی نامعتبر)",
"sounds.importFailed": "این بسته صدا خوانده نشد - آیا یک فایل ‎.ts3soundpack/ZIP معتبر است؟",
"tabs.connections": "اتصال‌های سرور",
+2
View File
@@ -658,6 +658,8 @@
"tabs.closeTab": "关闭标签页:{label}",
"identity.importInvalid": "“{file}”不是有效的身份文件。",
"log.fileTransferFailed": "文件传输失败:",
"log.serverReconnecting": "与服务器的连接已断开,正在重新连接…",
"log.serverReconnected": "已重新连接到服务器",
"log.fileTransferInvalidAddress": "文件传输失败(地址无效)",
"sounds.importFailed": "无法读取此音效包——它是有效的 .ts3soundpack/ZIP 文件吗?",
"tabs.connections": "服务器连接",