From 12e482b223b05e246862b60c487266b9d4b2d3e3 Mon Sep 17 00:00:00 2001 From: Moepchi Date: Sat, 3 Oct 2026 01:37:13 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- connector/src/main.rs | 22 ++++++++++++++++- gateway/src/index.ts | 5 +++- gateway/src/ts3/connection.ts | 4 +++ web/src/App.tsx | 46 +++++++++++++++++++++++++++++++++-- web/src/locales/de.json | 2 ++ web/src/locales/en.json | 2 ++ web/src/locales/fa.json | 2 ++ web/src/locales/zh-CN.json | 2 ++ 8 files changed, 81 insertions(+), 4 deletions(-) diff --git a/connector/src/main.rs b/connector/src/main.rs index 30baeaa..d59c7ea 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -293,6 +293,12 @@ enum Event { Talkers { clients: Vec }, #[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 = None; + let mut ts_reconnecting = false; enum LoopOutcome { StdinLine(std::io::Result>), @@ -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() { diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 43a7d8c..79872eb 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -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); diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index 6a7cbfa..0f8728d 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -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) diff --git a/web/src/App.tsx b/web/src/App.tsx index d6e9a6f..d6ca071 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -7449,6 +7449,17 @@ function AppInner() { case "talkers": setTalkers(new Set(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 | 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>(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>>(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]); diff --git a/web/src/locales/de.json b/web/src/locales/de.json index a8cf614..039ef58 100644 --- a/web/src/locales/de.json +++ b/web/src/locales/de.json @@ -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", diff --git a/web/src/locales/en.json b/web/src/locales/en.json index f128823..ed9ba26 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -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", diff --git a/web/src/locales/fa.json b/web/src/locales/fa.json index 40373fa..0342b23 100644 --- a/web/src/locales/fa.json +++ b/web/src/locales/fa.json @@ -658,6 +658,8 @@ "tabs.closeTab": "بستن زبانه: {label}", "identity.importInvalid": "«{file}» یک فایل هویت معتبر نیست.", "log.fileTransferFailed": "انتقال فایل ناموفق بود:", + "log.serverReconnecting": "اتصال به سرور قطع شد، در حال اتصال دوباره…", + "log.serverReconnected": "دوباره به سرور متصل شد", "log.fileTransferInvalidAddress": "انتقال فایل ناموفق بود (نشانی نامعتبر)", "sounds.importFailed": "این بسته صدا خوانده نشد - آیا یک فایل ‎.ts3soundpack/ZIP معتبر است؟", "tabs.connections": "اتصال‌های سرور", diff --git a/web/src/locales/zh-CN.json b/web/src/locales/zh-CN.json index 27d8d1d..00e2ba3 100644 --- a/web/src/locales/zh-CN.json +++ b/web/src/locales/zh-CN.json @@ -658,6 +658,8 @@ "tabs.closeTab": "关闭标签页:{label}", "identity.importInvalid": "“{file}”不是有效的身份文件。", "log.fileTransferFailed": "文件传输失败:", + "log.serverReconnecting": "与服务器的连接已断开,正在重新连接…", + "log.serverReconnected": "已重新连接到服务器", "log.fileTransferInvalidAddress": "文件传输失败(地址无效)", "sounds.importFailed": "无法读取此音效包——它是有效的 .ts3soundpack/ZIP 文件吗?", "tabs.connections": "服务器连接",