fix: WS keepalive-пинги против обрыва простаивающих сессий (#646)#925
Open
f4rceful wants to merge 1 commit into
Open
fix: WS keepalive-пинги против обрыва простаивающих сессий (#646)#925f4rceful wants to merge 1 commit into
f4rceful wants to merge 1 commit into
Conversation
…eal#646) Idle sessions could be silently torn down by NAT/firewall timeouts on the upstream WS connection: with no traffic and no keepalive, the bridge only noticed the dead connection on the next client packet, by which point Telegram had already dropped the session. Add an optional WS keepalive: RawWebSocket.send_ping() emits a masked PING frame, and _ws_keepalive() runs alongside the bridge pumps, pinging every ws_keepalive_interval seconds (--ws-keepalive, default 30, 0 to disable). The loop exits on send failure so a dead upstream is detected promptly.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Что сделано
RawWebSocket.send_ping()— отправка WS-фрейма OP_PING (маскированного, как требует протокол для клиента)._ws_keepalive()вbridge_ws_reencrypt, который шлёт PING на upstream каждые--ws-keepaliveсекунд (по умолчанию 30,0— отключить).--ws-keepalive SECв CLI и полеws_keepalive_intervalвProxyConfig(дефолт 30с — фикс активен и для GUI/трея).Зачем (разбор #646)
Долгие сессии рвались через случайный интервал простоя: Telegram показывал «прокси использует некорректные настройки», хотя сам прокси оставался жив, а мгновенное переподключение всё чинило.
Причина — тихий обрыв простаивающего соединения. Прокси отвечал на входящие PING, но сам не слал keepalive, и
SO_KEEPALIVEне выставлялся. Stateful-устройство на пути (NAT-таблица домашнего роутера / мобильный CGNAT, либо idle-таймаут CF edge) выкидывает простаивающий поток; следующий пакет упирается в мёртвое соединение → RST. Тот же симптом в независимой go-реализации указывает на причину в транспорте/NAT, а не в Python-коде.Периодический PING держит NAT-маппинги «тёплыми». Дополнительно: при сбое отправки пинга сессия теперь закрывается сразу, а не висит до следующего пакета клиента.
Поведение по умолчанию
Keepalive включён (30с). Отключить:
--ws-keepalive 0.Как проверить
py_compileдляproxy/bridge.py,proxy/raw_websocket.py,proxy/config.py,proxy/tg_ws_proxy.py— без ошибок.