mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-03 01:42:50 +08:00
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:
1 parent
23e61c86b3
commit
12e482b223
8 files changed
+81
-4
No files matched your search
+21
-1
@@ -293,6 +293,12 @@ enum Event {
|
|||||||
Talkers { clients: Vec<u16> },
|
Talkers { clients: Vec<u16> },
|
||||||
#[serde(rename = "disconnected")]
|
#[serde(rename = "disconnected")]
|
||||||
Disconnected { reason: String },
|
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")]
|
#[serde(rename = "error")]
|
||||||
Error { message: String },
|
Error { message: String },
|
||||||
/// A "switch" to a password-protected channel was rejected because no (or
|
/// 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
|
// TeaSpeak may reveal hidden channels after a group/permission change. Debounce
|
||||||
// a channelsubscribeall so we pick up any channels the server only exposes then.
|
// a channelsubscribeall so we pick up any channels the server only exposes then.
|
||||||
let mut resubscribe_at: Option<tokio::time::Instant> = None;
|
let mut resubscribe_at: Option<tokio::time::Instant> = None;
|
||||||
|
let mut ts_reconnecting = false;
|
||||||
|
|
||||||
enum LoopOutcome {
|
enum LoopOutcome {
|
||||||
StdinLine(std::io::Result<Option<String>>),
|
StdinLine(std::io::Result<Option<String>>),
|
||||||
@@ -2437,6 +2444,13 @@ async fn run(args: Args) -> Result<()> {
|
|||||||
},
|
},
|
||||||
LoopOutcome::ConEvent(ev) => match ev {
|
LoopOutcome::ConEvent(ev) => match ev {
|
||||||
Some(Ok(StreamItem::BookEvents(events))) => {
|
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;
|
let own_id = con.get_state()?.own_client;
|
||||||
for event in &events {
|
for event in &events {
|
||||||
if let BookEvent::Message { target, invoker, message } = event {
|
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}") });
|
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(Ok(_)) => {}
|
||||||
Some(Err(e)) => {
|
Some(Err(e)) => {
|
||||||
emit(&Event::Disconnected { reason: e.to_string() });
|
emit(&Event::Disconnected { reason: e.to_string() });
|
||||||
@@ -3029,7 +3047,9 @@ async fn run(args: Args) -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
LoopOutcome::ServerVarsRefresh => {
|
LoopOutcome::ServerVarsRefresh => {
|
||||||
send_server_get_variables(&mut con);
|
if !ts_reconnecting {
|
||||||
|
send_server_get_variables(&mut con);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
LoopOutcome::AudioTick => {
|
LoopOutcome::AudioTick => {
|
||||||
if !audio_handler.get_queues().is_empty() {
|
if !audio_handler.get_queues().is_empty() {
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ const WEB_DIST = process.env.WEB_DIST ?? path.resolve(__dirname, "../../web/dist
|
|||||||
const SERVE_STATIC = process.env.WEB_STATIC !== "0";
|
const SERVE_STATIC = process.env.WEB_STATIC !== "0";
|
||||||
|
|
||||||
// Sent to every browser in the "hello" message on socket open; see there.
|
// 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
|
// 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,
|
// TURN_SECRET (coturn's use-auth-secret) every socket gets its own credential,
|
||||||
@@ -585,6 +585,9 @@ const heartbeatTimer = setInterval(() => {
|
|||||||
}
|
}
|
||||||
state.isAlive = false;
|
state.isAlive = false;
|
||||||
socket.ping();
|
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);
|
}, HEARTBEAT_INTERVAL_MS);
|
||||||
|
|
||||||
|
|||||||
@@ -154,6 +154,8 @@ export type Ts3ConnectionEvent =
|
|||||||
| { type: "audioOut"; pcm: string }
|
| { type: "audioOut"; pcm: string }
|
||||||
| { type: "talkers"; clients: number[] }
|
| { type: "talkers"; clients: number[] }
|
||||||
| { type: "disconnected"; reason: string }
|
| { type: "disconnected"; reason: string }
|
||||||
|
| { type: "reconnecting"; reason: string }
|
||||||
|
| { type: "reconnected" }
|
||||||
| { type: "error"; message: string }
|
| { type: "error"; message: string }
|
||||||
| { type: "channelPasswordRequired"; channelId: number }
|
| { type: "channelPasswordRequired"; channelId: number }
|
||||||
| ({ type: "serverLog" } & ServerLogEntry)
|
| ({ type: "serverLog" } & ServerLogEntry)
|
||||||
@@ -362,6 +364,8 @@ export class Ts3Connection {
|
|||||||
| { type: "audioOut"; pcm: string }
|
| { type: "audioOut"; pcm: string }
|
||||||
| { type: "talkers"; clients: number[] }
|
| { type: "talkers"; clients: number[] }
|
||||||
| { type: "disconnected"; reason: string }
|
| { type: "disconnected"; reason: string }
|
||||||
|
| { type: "reconnecting"; reason: string }
|
||||||
|
| { type: "reconnected" }
|
||||||
| { type: "error"; message: string }
|
| { type: "error"; message: string }
|
||||||
| { type: "channelPasswordRequired"; channel_id: number }
|
| { type: "channelPasswordRequired"; channel_id: number }
|
||||||
| ({ type: "serverLog" } & ServerLogEntry)
|
| ({ type: "serverLog" } & ServerLogEntry)
|
||||||
|
|||||||
+44
-2
@@ -7449,6 +7449,17 @@ function AppInner() {
|
|||||||
case "talkers":
|
case "talkers":
|
||||||
setTalkers(new Set<number>(data.clients));
|
setTalkers(new Set<number>(data.clients));
|
||||||
break;
|
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": {
|
case "streamEvent": {
|
||||||
const streamEvent = data as StreamEvent;
|
const streamEvent = data as StreamEvent;
|
||||||
if (streamEvent.name === "notifystreaminfo" || streamEvent.name === "notifystreamstarted") {
|
if (streamEvent.name === "notifystreaminfo" || streamEvent.name === "notifystreamstarted") {
|
||||||
@@ -7744,10 +7755,28 @@ function AppInner() {
|
|||||||
|
|
||||||
const wireSocket = (sessionId: string, socket: WebSocket | DemoSocket, params: ConnectParams) => {
|
const wireSocket = (sessionId: string, socket: WebSocket | DemoSocket, params: ConnectParams) => {
|
||||||
const current = () => socketHandlersRef.current(sessionId, socket, params);
|
const current = () => socketHandlersRef.current(sessionId, socket, params);
|
||||||
|
let watchdog: ReturnType<typeof setTimeout> | undefined;
|
||||||
socket.onopen = () => current().onopen();
|
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.onerror = () => current().onerror();
|
||||||
socket.onclose = () => current().onclose();
|
socket.onclose = () => {
|
||||||
|
clearTimeout(watchdog);
|
||||||
|
current().onclose();
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleConnect = (overrides?: {
|
const handleConnect = (overrides?: {
|
||||||
@@ -7878,6 +7907,11 @@ function AppInner() {
|
|||||||
// instantly, which without a delay would tight-loop). Reset to 0 once a
|
// instantly, which without a delay would tight-loop). Reset to 0 once a
|
||||||
// session actually reaches "connected" again (see the two spots below).
|
// session actually reaches "connected" again (see the two spots below).
|
||||||
const reconnectAttemptsRef = useRef<Map<string, number>>(new Map());
|
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 reconnectTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
|
||||||
const scheduleReconnect = (sessionId: string) => {
|
const scheduleReconnect = (sessionId: string) => {
|
||||||
if (reconnectTimersRef.current.has(sessionId)) return; // already scheduled
|
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);
|
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||||
|
window.addEventListener("online", onOnline);
|
||||||
requestWakeLock();
|
requestWakeLock();
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||||
|
window.removeEventListener("online", onOnline);
|
||||||
releaseWakeLock();
|
releaseWakeLock();
|
||||||
};
|
};
|
||||||
}, [sessionTabs.length]);
|
}, [sessionTabs.length]);
|
||||||
|
|||||||
@@ -659,6 +659,8 @@
|
|||||||
"tabs.closeTab": "Tab schließen: {label}",
|
"tabs.closeTab": "Tab schließen: {label}",
|
||||||
"identity.importInvalid": "„{file}“ ist keine gültige Identitätsdatei.",
|
"identity.importInvalid": "„{file}“ ist keine gültige Identitätsdatei.",
|
||||||
"log.fileTransferFailed": "Dateiübertragung fehlgeschlagen:",
|
"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)",
|
"log.fileTransferInvalidAddress": "Dateiübertragung fehlgeschlagen (ungültige Adresse)",
|
||||||
"sounds.importFailed": "Das Soundpack konnte nicht gelesen werden – ist es eine gültige .ts3soundpack-/ZIP-Datei?",
|
"sounds.importFailed": "Das Soundpack konnte nicht gelesen werden – ist es eine gültige .ts3soundpack-/ZIP-Datei?",
|
||||||
"tabs.connections": "Server-Verbindungen",
|
"tabs.connections": "Server-Verbindungen",
|
||||||
|
|||||||
@@ -659,6 +659,8 @@
|
|||||||
"tabs.closeTab": "Close tab: {label}",
|
"tabs.closeTab": "Close tab: {label}",
|
||||||
"identity.importInvalid": "\"{file}\" is not a valid identity file.",
|
"identity.importInvalid": "\"{file}\" is not a valid identity file.",
|
||||||
"log.fileTransferFailed": "File transfer failed:",
|
"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)",
|
"log.fileTransferInvalidAddress": "File transfer failed (invalid address)",
|
||||||
"sounds.importFailed": "Could not read this soundpack - is it a valid .ts3soundpack/ZIP file?",
|
"sounds.importFailed": "Could not read this soundpack - is it a valid .ts3soundpack/ZIP file?",
|
||||||
"tabs.connections": "Server connections",
|
"tabs.connections": "Server connections",
|
||||||
|
|||||||
@@ -658,6 +658,8 @@
|
|||||||
"tabs.closeTab": "بستن زبانه: {label}",
|
"tabs.closeTab": "بستن زبانه: {label}",
|
||||||
"identity.importInvalid": "«{file}» یک فایل هویت معتبر نیست.",
|
"identity.importInvalid": "«{file}» یک فایل هویت معتبر نیست.",
|
||||||
"log.fileTransferFailed": "انتقال فایل ناموفق بود:",
|
"log.fileTransferFailed": "انتقال فایل ناموفق بود:",
|
||||||
|
"log.serverReconnecting": "اتصال به سرور قطع شد، در حال اتصال دوباره…",
|
||||||
|
"log.serverReconnected": "دوباره به سرور متصل شد",
|
||||||
"log.fileTransferInvalidAddress": "انتقال فایل ناموفق بود (نشانی نامعتبر)",
|
"log.fileTransferInvalidAddress": "انتقال فایل ناموفق بود (نشانی نامعتبر)",
|
||||||
"sounds.importFailed": "این بسته صدا خوانده نشد - آیا یک فایل .ts3soundpack/ZIP معتبر است؟",
|
"sounds.importFailed": "این بسته صدا خوانده نشد - آیا یک فایل .ts3soundpack/ZIP معتبر است؟",
|
||||||
"tabs.connections": "اتصالهای سرور",
|
"tabs.connections": "اتصالهای سرور",
|
||||||
|
|||||||
@@ -658,6 +658,8 @@
|
|||||||
"tabs.closeTab": "关闭标签页:{label}",
|
"tabs.closeTab": "关闭标签页:{label}",
|
||||||
"identity.importInvalid": "“{file}”不是有效的身份文件。",
|
"identity.importInvalid": "“{file}”不是有效的身份文件。",
|
||||||
"log.fileTransferFailed": "文件传输失败:",
|
"log.fileTransferFailed": "文件传输失败:",
|
||||||
|
"log.serverReconnecting": "与服务器的连接已断开,正在重新连接…",
|
||||||
|
"log.serverReconnected": "已重新连接到服务器",
|
||||||
"log.fileTransferInvalidAddress": "文件传输失败(地址无效)",
|
"log.fileTransferInvalidAddress": "文件传输失败(地址无效)",
|
||||||
"sounds.importFailed": "无法读取此音效包——它是有效的 .ts3soundpack/ZIP 文件吗?",
|
"sounds.importFailed": "无法读取此音效包——它是有效的 .ts3soundpack/ZIP 文件吗?",
|
||||||
"tabs.connections": "服务器连接",
|
"tabs.connections": "服务器连接",
|
||||||
|
|||||||
Reference in new issue
Block a user