Socket occupation fix

This commit is contained in:
Flowseal
2026-11-23 06:28:14 +03:00
parent 0970820f1f
commit 13d764f809
9 changed files with 295 additions and 41 deletions
+42 -1
View File
@@ -4,12 +4,53 @@ import signal
import socket
import sys
import threading
from contextlib import suppress
from contextlib import contextmanager, suppress
log = logging.getLogger('tg-mtproto-proxy')
class ClientStreamProtocol(asyncio.StreamReaderProtocol):
def __init__(self, client_cb):
super().__init__(asyncio.StreamReader(), client_cb)
self.cancel_setup = None
def eof_received(self):
keep_open = super().eof_received()
if self.cancel_setup is not None:
self.cancel_setup(False)
return keep_open
def connection_lost(self, exc):
super().connection_lost(exc)
if self.cancel_setup is not None:
self.cancel_setup(True)
@contextmanager
def client_setup(reader, writer):
"""Cancel an upstream dial when its client leaves, without reading client bytes."""
if reader.at_eof() or writer.is_closing():
raise asyncio.CancelledError()
protocol = writer.transport.get_protocol()
if not isinstance(protocol, ClientStreamProtocol):
yield
return
task = asyncio.current_task()
def cancel(lost):
if lost or reader.at_eof():
protocol.cancel_setup = None
task.cancel()
protocol.cancel_setup = cancel
try:
yield
finally:
protocol.cancel_setup = None
def _close_proactor_socket(transport, exc):
sock = transport._sock
if sock is None: