| 39 | |
| 40 | |
| 41 | class TConn: |
| 42 | |
| 43 | def __init__(self, cfg, sock, client, server): |
| 44 | self.cfg = cfg |
| 45 | self.sock = sock |
| 46 | self.client = client |
| 47 | self.server = server |
| 48 | |
| 49 | self.timeout = None |
| 50 | self.parser = None |
| 51 | self.initialized = False |
| 52 | self.is_http2 = False |
| 53 | # Track if we've already waited for data (to avoid waiting again after defer) |
| 54 | self.data_ready = False |
| 55 | |
| 56 | # set the socket to non blocking |
| 57 | self.sock.setblocking(False) |
| 58 | |
| 59 | def init(self): |
| 60 | # Guard against double initialization |
| 61 | if self.initialized: |
| 62 | return |
| 63 | self.initialized = True |
| 64 | self.sock.setblocking(True) |
| 65 | |
| 66 | if self.parser is None: |
| 67 | # wrap the socket if needed |
| 68 | if self.cfg.is_ssl: |
| 69 | self.sock = sock.ssl_wrap_socket(self.sock, self.cfg) |
| 70 | |
| 71 | # Complete the handshake to ensure ALPN negotiation is done |
| 72 | # (needed if do_handshake_on_connect is False) |
| 73 | if not self.cfg.do_handshake_on_connect: |
| 74 | self.sock.do_handshake() |
| 75 | |
| 76 | # Check if HTTP/2 was negotiated via ALPN |
| 77 | if sock.is_http2_negotiated(self.sock): |
| 78 | self.is_http2 = True |
| 79 | self.parser = http.get_parser( |
| 80 | self.cfg, self.sock, self.client, http2_connection=True |
| 81 | ) |
| 82 | self.parser.initiate_connection() |
| 83 | return |
| 84 | |
| 85 | # initialize the HTTP/1.x parser |
| 86 | self.parser = http.get_parser(self.cfg, self.sock, self.client) |
| 87 | |
| 88 | def set_timeout(self): |
| 89 | # Use monotonic clock for reliability (time.time() can jump due to NTP) |
| 90 | self.timeout = time.monotonic() + self.cfg.keepalive |
| 91 | |
| 92 | def wait_for_data(self, timeout): |
| 93 | """Wait for data to be available on the socket. |
| 94 | |
| 95 | Uses selectors to wait for the socket to become readable within |
| 96 | the given timeout. This prevents slow clients from blocking |
| 97 | thread pool slots indefinitely. |
| 98 | |