Skip to content

Commit ee6da6d

Browse files
feat: enable tcp keep-alive
1 parent 4d820a2 commit ee6da6d

1 file changed

Lines changed: 22 additions & 2 deletions

File tree

  • pyrogram/connection/transport/tcp

pyrogram/connection/transport/tcp/tcp.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424
from typing import Optional, Tuple, TypedDict, Union
2525
from urllib.parse import parse_qs
2626

27-
from python_socks import ProxyType
2827
from python_socks.async_.asyncio import Proxy
2928

3029
from pyrogram import utils
@@ -46,7 +45,7 @@ class TCP:
4645
def __init__(
4746
self,
4847
ipv6: bool = False,
49-
proxy: Union[str, ProxyDict, None] = None,
48+
proxy: Optional[Union[str, ProxyDict]] = None,
5049
crypto_executor_workers: int = 1,
5150
loop: Optional[asyncio.AbstractEventLoop] = None,
5251
) -> None:
@@ -110,6 +109,20 @@ async def _build_proxy(self) -> Proxy:
110109

111110
return Proxy.from_url(url)
112111

112+
@staticmethod
113+
def _enable_keepalive(sock: socket.socket) -> None:
114+
try:
115+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
116+
117+
if hasattr(socket, "TCP_KEEPIDLE"):
118+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10)
119+
if hasattr(socket, "TCP_KEEPINTVL"):
120+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5)
121+
if hasattr(socket, "TCP_KEEPCNT"):
122+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3)
123+
except Exception as e:
124+
log.debug("Could not configure TCP Keep-Alive: %s %s", type(e).__name__, e)
125+
113126
async def _connect_via_proxy(self, destination: Tuple[str, int]) -> None:
114127
dest_host, dest_port = destination
115128
proxy = await self._build_proxy()
@@ -131,6 +144,8 @@ async def _connect_via_proxy(self, destination: Tuple[str, int]) -> None:
131144
log.error("Proxy connection failed: %s %s", type(e).__name__, e)
132145
raise
133146

147+
self._enable_keepalive(sock)
148+
134149
log.info("Proxy connection established")
135150

136151
self.reader, self.writer = await asyncio.open_connection(sock=sock)
@@ -147,6 +162,11 @@ async def _connect_via_direct(self, destination: Tuple[str, int]) -> None:
147162
port=port,
148163
family=family,
149164
)
165+
166+
raw_socket = self.writer.get_extra_info("socket")
167+
168+
if raw_socket:
169+
self._enable_keepalive(raw_socket)
150170
except Exception as e:
151171
log.error("Connection failed: %s %s", type(e).__name__, e)
152172
raise

0 commit comments

Comments
 (0)