{
    "file_diffs": [
        {
            "old_file_content": "import asyncio\nimport functools\nimport random\nimport socket\nimport sys\nimport traceback\nimport warnings\nfrom collections import OrderedDict, defaultdict, deque\nfrom contextlib import suppress\nfrom http import HTTPStatus\nfrom itertools import chain, cycle, islice\nfrom time import monotonic\nfrom types import TracebackType\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Awaitable,\n    Callable,\n    DefaultDict,\n    Deque,\n    Dict,\n    Iterator,\n    List,\n    Literal,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Type,\n    Union,\n    cast,\n)\n\nimport aiohappyeyeballs\n\nfrom . import hdrs, helpers\nfrom .abc import AbstractResolver, ResolveResult\nfrom .client_exceptions import (\n    ClientConnectionError,\n    ClientConnectorCertificateError,\n    ClientConnectorDNSError,\n    ClientConnectorError,\n    ClientConnectorSSLError,\n    ClientHttpProxyError,\n    ClientProxyConnectionError,\n    ServerFingerprintMismatch,\n    UnixClientConnectorError,\n    cert_errors,\n    ssl_errors,\n)\nfrom .client_proto import ResponseHandler\nfrom .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params\nfrom .helpers import (\n    ceil_timeout,\n    is_ip_address,\n    noop,\n    sentinel,\n    set_exception,\n    set_result,\n)\nfrom .resolver import DefaultResolver\n\ntry:\n    import ssl\n\n    SSLContext = ssl.SSLContext\nexcept ImportError:  # pragma: no cover\n    ssl = None  # type: ignore[assignment]\n    SSLContext = object  # type: ignore[misc,assignment]\n\n\nEMPTY_SCHEMA_SET = frozenset({\"\"})\nHTTP_SCHEMA_SET = frozenset({\"http\", \"https\"})\nWS_SCHEMA_SET = frozenset({\"ws\", \"wss\"})\n\nHTTP_AND_EMPTY_SCHEMA_SET = HTTP_SCHEMA_SET | EMPTY_SCHEMA_SET\nHIGH_LEVEL_SCHEMA_SET = HTTP_AND_EMPTY_SCHEMA_SET | WS_SCHEMA_SET\n\n\n__all__ = (\"BaseConnector\", \"TCPConnector\", \"UnixConnector\", \"NamedPipeConnector\")\n\n\nif TYPE_CHECKING:\n    from .client import ClientTimeout\n    from .client_reqrep import ConnectionKey\n    from .tracing import Trace\n\n\nclass _DeprecationWaiter:\n    __slots__ = (\"_awaitable\", \"_awaited\")\n\n    def __init__(self, awaitable: Awaitable[Any]) -> None:\n        self._awaitable = awaitable\n        self._awaited = False\n\n    def __await__(self) -> Any:\n        self._awaited = True\n        return self._awaitable.__await__()\n\n    def __del__(self) -> None:\n        if not self._awaited:\n            warnings.warn(\n                \"Connector.close() is a coroutine, \"\n                \"please use await connector.close()\",\n                DeprecationWarning,\n            )\n\n\nclass Connection:\n\n    _source_traceback = None\n\n    def __init__(\n        self,\n        connector: \"BaseConnector\",\n        key: \"ConnectionKey\",\n        protocol: ResponseHandler,\n        loop: asyncio.AbstractEventLoop,\n    ) -> None:\n        self._key = key\n        self._connector = connector\n        self._loop = loop\n        self._protocol: Optional[ResponseHandler] = protocol\n        self._callbacks: List[Callable[[], None]] = []\n\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n    def __repr__(self) -> str:\n        return f\"Connection<{self._key}>\"\n\n    def __del__(self, _warnings: Any = warnings) -> None:\n        if self._protocol is not None:\n            kwargs = {\"source\": self}\n            _warnings.warn(f\"Unclosed connection {self!r}\", ResourceWarning, **kwargs)\n            if self._loop.is_closed():\n                return\n\n            self._connector._release(self._key, self._protocol, should_close=True)\n\n            context = {\"client_connection\": self, \"message\": \"Unclosed connection\"}\n            if self._source_traceback is not None:\n                context[\"source_traceback\"] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def __bool__(self) -> Literal[True]:\n        \"\"\"Force subclasses to not be falsy, to make checks simpler.\"\"\"\n        return True\n\n    @property\n    def loop(self) -> asyncio.AbstractEventLoop:\n        warnings.warn(\n            \"connector.loop property is deprecated\", DeprecationWarning, stacklevel=2\n        )\n        return self._loop\n\n    @property\n    def transport(self) -> Optional[asyncio.Transport]:\n        if self._protocol is None:\n            return None\n        return self._protocol.transport\n\n    @property\n    def protocol(self) -> Optional[ResponseHandler]:\n        return self._protocol\n\n    def add_callback(self, callback: Callable[[], None]) -> None:\n        if callback is not None:\n            self._callbacks.append(callback)\n\n    def _notify_release(self) -> None:\n        callbacks, self._callbacks = self._callbacks[:], []\n\n        for cb in callbacks:\n            with suppress(Exception):\n                cb()\n\n    def close(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(self._key, self._protocol, should_close=True)\n            self._protocol = None\n\n    def release(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(\n                self._key, self._protocol, should_close=self._protocol.should_close\n            )\n            self._protocol = None\n\n    @property\n    def closed(self) -> bool:\n        return self._protocol is None or not self._protocol.is_connected()\n\n\nclass _TransportPlaceholder:\n    \"\"\"placeholder for BaseConnector.connect function\"\"\"\n\n    __slots__ = ()\n\n    def close(self) -> None:\n        \"\"\"Close the placeholder transport.\"\"\"\n\n\nclass BaseConnector:\n    \"\"\"Base connector class.\n\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    enable_cleanup_closed - Enables clean-up closed ssl transports.\n                            Disabled by default.\n    timeout_ceil_threshold - Trigger ceiling of timeout values when\n                             it's above timeout_ceil_threshold.\n    loop - Optional event loop.\n    \"\"\"\n\n    _closed = True  # prevent AttributeError in __del__ if ctor was failed\n    _source_traceback = None\n\n    # abort transport after 2 seconds (cleanup broken connections)\n    _cleanup_closed_period = 2.0\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET\n\n    def __init__(\n        self,\n        *,\n        keepalive_timeout: Union[object, None, float] = sentinel,\n        force_close: bool = False,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        enable_cleanup_closed: bool = False,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n        timeout_ceil_threshold: float = 5,\n    ) -> None:\n\n        if force_close:\n            if keepalive_timeout is not None and keepalive_timeout is not sentinel:\n                raise ValueError(\n                    \"keepalive_timeout cannot be set if force_close is True\"\n                )\n        else:\n            if keepalive_timeout is sentinel:\n                keepalive_timeout = 15.0\n\n        loop = loop or asyncio.get_running_loop()\n        self._timeout_ceil_threshold = timeout_ceil_threshold\n\n        self._closed = False\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        # Connection pool of reusable connections.\n        # We use a deque to store connections because it has O(1) popleft()\n        # and O(1) append() operations to implement a FIFO queue.\n        self._conns: DefaultDict[\n            ConnectionKey, Deque[Tuple[ResponseHandler, float]]\n        ] = defaultdict(deque)\n        self._limit = limit\n        self._limit_per_host = limit_per_host\n        self._acquired: Set[ResponseHandler] = set()\n        self._acquired_per_host: DefaultDict[ConnectionKey, Set[ResponseHandler]] = (\n            defaultdict(set)\n        )\n        self._keepalive_timeout = cast(float, keepalive_timeout)\n        self._force_close = force_close\n\n        # {host_key: FIFO list of waiters}\n        # The FIFO is implemented with an OrderedDict with None keys because\n        # python does not have an ordered set.\n        self._waiters: DefaultDict[\n            ConnectionKey, OrderedDict[asyncio.Future[None], None]\n        ] = defaultdict(OrderedDict)\n\n        self._loop = loop\n        self._factory = functools.partial(ResponseHandler, loop=loop)\n\n        # start keep-alive connection cleanup task\n        self._cleanup_handle: Optional[asyncio.TimerHandle] = None\n\n        # start cleanup closed transports task\n        self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None\n        self._cleanup_closed_disabled = not enable_cleanup_closed\n        self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = []\n        self._cleanup_closed()\n\n    def __del__(self, _warnings: Any = warnings) -> None:\n        if self._closed:\n            return\n        if not self._conns:\n            return\n\n        conns = [repr(c) for c in self._conns.values()]\n\n        self._close()\n\n        kwargs = {\"source\": self}\n        _warnings.warn(f\"Unclosed connector {self!r}\", ResourceWarning, **kwargs)\n        context = {\n            \"connector\": self,\n            \"connections\": conns,\n            \"message\": \"Unclosed connector\",\n        }\n        if self._source_traceback is not None:\n            context[\"source_traceback\"] = self._source_traceback\n        self._loop.call_exception_handler(context)\n\n    def __enter__(self) -> \"BaseConnector\":\n        warnings.warn(\n            '\"with Connector():\" is deprecated, '\n            'use \"async with Connector():\" instead',\n            DeprecationWarning,\n        )\n        return self\n\n    def __exit__(self, *exc: Any) -> None:\n        self._close()\n\n    async def __aenter__(self) -> \"BaseConnector\":\n        return self\n\n    async def __aexit__(\n        self,\n        exc_type: Optional[Type[BaseException]] = None,\n        exc_value: Optional[BaseException] = None,\n        exc_traceback: Optional[TracebackType] = None,\n    ) -> None:\n        await self.close()\n\n    @property\n    def force_close(self) -> bool:\n        \"\"\"Ultimately close connection on releasing if True.\"\"\"\n        return self._force_close\n\n    @property\n    def limit(self) -> int:\n        \"\"\"The total number for simultaneous connections.\n\n        If limit is 0 the connector has no limit.\n        The default limit size is 100.\n        \"\"\"\n        return self._limit\n\n    @property\n    def limit_per_host(self) -> int:\n        \"\"\"The limit for simultaneous connections to the same endpoint.\n\n        Endpoints are the same if they are have equal\n        (host, port, is_ssl) triple.\n        \"\"\"\n        return self._limit_per_host\n\n    def _cleanup(self) -> None:\n        \"\"\"Cleanup unused transports.\"\"\"\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            # _cleanup_handle should be unset, otherwise _release() will not\n            # recreate it ever!\n            self._cleanup_handle = None\n\n        now = monotonic()\n        timeout = self._keepalive_timeout\n\n        if self._conns:\n            connections = defaultdict(deque)\n            deadline = now - timeout\n            for key, conns in self._conns.items():\n                alive: Deque[Tuple[ResponseHandler, float]] = deque()\n                for proto, use_time in conns:\n                    if proto.is_connected() and use_time - deadline >= 0:\n                        alive.append((proto, use_time))\n                        continue\n                    transport = proto.transport\n                    proto.close()\n                    if not self._cleanup_closed_disabled and key.is_ssl:\n                        self._cleanup_closed_transports.append(transport)\n\n                if alive:\n                    connections[key] = alive\n\n            self._conns = connections\n\n        if self._conns:\n            self._cleanup_handle = helpers.weakref_handle(\n                self,\n                \"_cleanup\",\n                timeout,\n                self._loop,\n                timeout_ceil_threshold=self._timeout_ceil_threshold,\n            )\n\n    def _cleanup_closed(self) -> None:\n        \"\"\"Double confirmation for transport close.\n\n        Some broken ssl servers may leave socket open without proper close.\n        \"\"\"\n        if self._cleanup_closed_handle:\n            self._cleanup_closed_handle.cancel()\n\n        for transport in self._cleanup_closed_transports:\n            if transport is not None:\n                transport.abort()\n\n        self._cleanup_closed_transports = []\n\n        if not self._cleanup_closed_disabled:\n            self._cleanup_closed_handle = helpers.weakref_handle(\n                self,\n                \"_cleanup_closed\",\n                self._cleanup_closed_period,\n                self._loop,\n                timeout_ceil_threshold=self._timeout_ceil_threshold,\n            )\n\n    def close(self) -> Awaitable[None]:\n        \"\"\"Close all opened transports.\"\"\"\n        self._close()\n        return _DeprecationWaiter(noop())\n\n    def _close(self) -> None:\n        if self._closed:\n            return\n\n        self._closed = True\n\n        try:\n            if self._loop.is_closed():\n                return\n\n            # cancel cleanup task\n            if self._cleanup_handle:\n                self._cleanup_handle.cancel()\n\n            # cancel cleanup close task\n            if self._cleanup_closed_handle:\n                self._cleanup_closed_handle.cancel()\n\n            for data in self._conns.values():\n                for proto, t0 in data:\n                    proto.close()\n\n            for proto in self._acquired:\n                proto.close()\n\n            for transport in self._cleanup_closed_transports:\n                if transport is not None:\n                    transport.abort()\n\n        finally:\n            self._conns.clear()\n            self._acquired.clear()\n            for keyed_waiters in self._waiters.values():\n                for keyed_waiter in keyed_waiters:\n                    keyed_waiter.cancel()\n            self._waiters.clear()\n            self._cleanup_handle = None\n            self._cleanup_closed_transports.clear()\n            self._cleanup_closed_handle = None\n\n    @property\n    def closed(self) -> bool:\n        \"\"\"Is connector closed.\n\n        A readonly property.\n        \"\"\"\n        return self._closed\n\n    def _available_connections(self, key: \"ConnectionKey\") -> int:\n        \"\"\"\n        Return number of available connections.\n\n        The limit, limit_per_host and the connection key are taken into account.\n\n        If it returns less than 1 means that there are no connections\n        available.\n        \"\"\"\n        # check total available connections\n        # If there are no limits, this will always return 1\n        total_remain = 1\n\n        if self._limit and (total_remain := self._limit - len(self._acquired)) <= 0:\n            return total_remain\n\n        # check limit per host\n        if host_remain := self._limit_per_host:\n            if acquired := self._acquired_per_host.get(key):\n                host_remain -= len(acquired)\n            if total_remain > host_remain:\n                return host_remain\n\n        return total_remain\n\n    async def connect(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> Connection:\n        \"\"\"Get from pool or create new connection.\"\"\"\n        key = req.connection_key\n        if (conn := await self._get(key, traces)) is not None:\n            # If we do not have to wait and we can get a connection from the pool\n            # we can avoid the timeout ceil logic and directly return the connection\n            return conn\n\n        async with ceil_timeout(timeout.connect, timeout.ceil_threshold):\n            if self._available_connections(key) <= 0:\n                await self._wait_for_available_connection(key, traces)\n                if (conn := await self._get(key, traces)) is not None:\n                    return conn\n\n            placeholder = cast(ResponseHandler, _TransportPlaceholder())\n            self._acquired.add(placeholder)\n            self._acquired_per_host[key].add(placeholder)\n\n            try:\n                # Traces are done inside the try block to ensure that the\n                # that the placeholder is still cleaned up if an exception\n                # is raised.\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_create_start()\n                proto = await self._create_connection(req, traces, timeout)\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_create_end()\n            except BaseException:\n                self._release_acquired(key, placeholder)\n                raise\n            else:\n                if self._closed:\n                    proto.close()\n                    raise ClientConnectionError(\"Connector is closed.\")\n\n        # The connection was successfully created, drop the placeholder\n        # and add the real connection to the acquired set. There should\n        # be no awaits after the proto is added to the acquired set\n        # to ensure that the connection is not left in the acquired set\n        # on cancellation.\n        acquired_per_host = self._acquired_per_host[key]\n        self._acquired.remove(placeholder)\n        acquired_per_host.remove(placeholder)\n        self._acquired.add(proto)\n        acquired_per_host.add(proto)\n        return Connection(self, key, proto, self._loop)\n\n    async def _wait_for_available_connection(\n        self, key: \"ConnectionKey\", traces: List[\"Trace\"]\n    ) -> None:\n        \"\"\"Wait for an available connection slot.\"\"\"\n        # We loop here because there is a race between\n        # the connection limit check and the connection\n        # being acquired. If the connection is acquired\n        # between the check and the await statement, we\n        # need to loop again to check if the connection\n        # slot is still available.\n        attempts = 0\n        while True:\n            fut: asyncio.Future[None] = self._loop.create_future()\n            keyed_waiters = self._waiters[key]\n            keyed_waiters[fut] = None\n            if attempts:\n                # If we have waited before, we need to move the waiter\n                # to the front of the queue as otherwise we might get\n                # starved and hit the timeout.\n                keyed_waiters.move_to_end(fut, last=False)\n\n            try:\n                # Traces happen in the try block to ensure that the\n                # the waiter is still cleaned up if an exception is raised.\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_queued_start()\n                await fut\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_queued_end()\n            finally:\n                # pop the waiter from the queue if its still\n                # there and not already removed by _release_waiter\n                keyed_waiters.pop(fut, None)\n                if not self._waiters.get(key, True):\n                    del self._waiters[key]\n\n            if self._available_connections(key) > 0:\n                break\n            attempts += 1\n\n    async def _get(\n        self, key: \"ConnectionKey\", traces: List[\"Trace\"]\n    ) -> Optional[Connection]:\n        \"\"\"Get next reusable connection for the key or None.\n\n        The connection will be marked as acquired.\n        \"\"\"\n        if (conns := self._conns.get(key)) is None:\n            return None\n\n        t1 = monotonic()\n        while conns:\n            proto, t0 = conns.popleft()\n            # We will we reuse the connection if its connected and\n            # the keepalive timeout has not been exceeded\n            if proto.is_connected() and t1 - t0 <= self._keepalive_timeout:\n                if not conns:\n                    # The very last connection was reclaimed: drop the key\n                    del self._conns[key]\n                self._acquired.add(proto)\n                self._acquired_per_host[key].add(proto)\n                if traces:\n                    for trace in traces:\n                        try:\n                            await trace.send_connection_reuseconn()\n                        except BaseException:\n                            self._release_acquired(key, proto)\n                            raise\n                return Connection(self, key, proto, self._loop)\n\n            # Connection cannot be reused, close it\n            transport = proto.transport\n            proto.close()\n            # only for SSL transports\n            if not self._cleanup_closed_disabled and key.is_ssl:\n                self._cleanup_closed_transports.append(transport)\n\n        # No more connections: drop the key\n        del self._conns[key]\n        return None\n\n    def _release_waiter(self) -> None:\n        \"\"\"\n        Iterates over all waiters until one to be released is found.\n\n        The one to be released is not finished and\n        belongs to a host that has available connections.\n        \"\"\"\n        if not self._waiters:\n            return\n\n        # Having the dict keys ordered this avoids to iterate\n        # at the same order at each call.\n        queues = list(self._waiters)\n        random.shuffle(queues)\n\n        for key in queues:\n            if self._available_connections(key) < 1:\n                continue\n\n            waiters = self._waiters[key]\n            while waiters:\n                waiter, _ = waiters.popitem(last=False)\n                if not waiter.done():\n                    waiter.set_result(None)\n                    return\n\n    def _release_acquired(self, key: \"ConnectionKey\", proto: ResponseHandler) -> None:\n        \"\"\"Release acquired connection.\"\"\"\n        if self._closed:\n            # acquired connection is already released on connector closing\n            return\n\n        self._acquired.discard(proto)\n        if conns := self._acquired_per_host.get(key):\n            conns.discard(proto)\n            if not conns:\n                del self._acquired_per_host[key]\n        self._release_waiter()\n\n    def _release(\n        self,\n        key: \"ConnectionKey\",\n        protocol: ResponseHandler,\n        *,\n        should_close: bool = False,\n    ) -> None:\n        if self._closed:\n            # acquired connection is already released on connector closing\n            return\n\n        self._release_acquired(key, protocol)\n\n        if self._force_close:\n            should_close = True\n\n        if should_close or protocol.should_close:\n            transport = protocol.transport\n            protocol.close()\n\n            if key.is_ssl and not self._cleanup_closed_disabled:\n                self._cleanup_closed_transports.append(transport)\n            return\n\n        self._conns[key].append((protocol, monotonic()))\n\n        if self._cleanup_handle is None:\n            self._cleanup_handle = helpers.weakref_handle(\n                self,\n                \"_cleanup\",\n                self._keepalive_timeout,\n                self._loop,\n                timeout_ceil_threshold=self._timeout_ceil_threshold,\n            )\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        raise NotImplementedError()\n\n\nclass _DNSCacheTable:\n    def __init__(self, ttl: Optional[float] = None) -> None:\n        self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[ResolveResult], int]] = {}\n        self._timestamps: Dict[Tuple[str, int], float] = {}\n        self._ttl = ttl\n\n    def __contains__(self, host: object) -> bool:\n        return host in self._addrs_rr\n\n    def add(self, key: Tuple[str, int], addrs: List[ResolveResult]) -> None:\n        self._addrs_rr[key] = (cycle(addrs), len(addrs))\n\n        if self._ttl is not None:\n            self._timestamps[key] = monotonic()\n\n    def remove(self, key: Tuple[str, int]) -> None:\n        self._addrs_rr.pop(key, None)\n\n        if self._ttl is not None:\n            self._timestamps.pop(key, None)\n\n    def clear(self) -> None:\n        self._addrs_rr.clear()\n        self._timestamps.clear()\n\n    def next_addrs(self, key: Tuple[str, int]) -> List[ResolveResult]:\n        loop, length = self._addrs_rr[key]\n        addrs = list(islice(loop, length))\n        # Consume one more element to shift internal state of `cycle`\n        next(loop)\n        return addrs\n\n    def expired(self, key: Tuple[str, int]) -> bool:\n        if self._ttl is None:\n            return False\n\n        return self._timestamps[key] + self._ttl < monotonic()\n\n\ndef _make_ssl_context(verified: bool) -> SSLContext:\n    \"\"\"Create SSL context.\n\n    This method is not async-friendly and should be called from a thread\n    because it will load certificates from disk and do other blocking I/O.\n    \"\"\"\n    if ssl is None:\n        # No ssl support\n        return None\n    if verified:\n        return ssl.create_default_context()\n    sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n    sslcontext.options |= ssl.OP_NO_SSLv2\n    sslcontext.options |= ssl.OP_NO_SSLv3\n    sslcontext.check_hostname = False\n    sslcontext.verify_mode = ssl.CERT_NONE\n    sslcontext.options |= ssl.OP_NO_COMPRESSION\n    sslcontext.set_default_verify_paths()\n    return sslcontext\n\n\n# The default SSLContext objects are created at import time\n# since they do blocking I/O to load certificates from disk,\n# and imports should always be done before the event loop starts\n# or in a thread.\n_SSL_CONTEXT_VERIFIED = _make_ssl_context(True)\n_SSL_CONTEXT_UNVERIFIED = _make_ssl_context(False)\n\n\nclass TCPConnector(BaseConnector):\n    \"\"\"TCP connector.\n\n    verify_ssl - Set to True to check ssl certifications.\n    fingerprint - Pass the binary sha256\n        digest of the expected certificate in DER format to verify\n        that the certificate the server presents matches. See also\n        https://en.wikipedia.org/wiki/HTTP_Public_Key_Pinning\n    resolver - Enable DNS lookups and use this\n        resolver\n    use_dns_cache - Use memory cache for DNS lookups.\n    ttl_dns_cache - Max seconds having cached a DNS entry, None forever.\n    family - socket address family\n    local_addr - local tuple of (host, port) to bind socket to\n\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    enable_cleanup_closed - Enables clean-up closed ssl transports.\n                            Disabled by default.\n    happy_eyeballs_delay - This is the “Connection Attempt Delay”\n                           as defined in RFC 8305. To disable\n                           the happy eyeballs algorithm, set to None.\n    interleave - “First Address Family Count” as defined in RFC 8305\n    loop - Optional event loop.\n    \"\"\"\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({\"tcp\"})\n\n    def __init__(\n        self,\n        *,\n        verify_ssl: bool = True,\n        fingerprint: Optional[bytes] = None,\n        use_dns_cache: bool = True,\n        ttl_dns_cache: Optional[int] = 10,\n        family: socket.AddressFamily = socket.AddressFamily.AF_UNSPEC,\n        ssl_context: Optional[SSLContext] = None,\n        ssl: Union[bool, Fingerprint, SSLContext] = True,\n        local_addr: Optional[Tuple[str, int]] = None,\n        resolver: Optional[AbstractResolver] = None,\n        keepalive_timeout: Union[None, float, object] = sentinel,\n        force_close: bool = False,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        enable_cleanup_closed: bool = False,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n        timeout_ceil_threshold: float = 5,\n        happy_eyeballs_delay: Optional[float] = 0.25,\n        interleave: Optional[int] = None,\n    ):\n        super().__init__(\n            keepalive_timeout=keepalive_timeout,\n            force_close=force_close,\n            limit=limit,\n            limit_per_host=limit_per_host,\n            enable_cleanup_closed=enable_cleanup_closed,\n            loop=loop,\n            timeout_ceil_threshold=timeout_ceil_threshold,\n        )\n\n        self._ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)\n        if resolver is None:\n            resolver = DefaultResolver(loop=self._loop)\n        self._resolver = resolver\n\n        self._use_dns_cache = use_dns_cache\n        self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache)\n        self._throttle_dns_futures: Dict[\n            Tuple[str, int], Set[\"asyncio.Future[None]\"]\n        ] = {}\n        self._family = family\n        self._local_addr_infos = aiohappyeyeballs.addr_to_addr_infos(local_addr)\n        self._happy_eyeballs_delay = happy_eyeballs_delay\n        self._interleave = interleave\n        self._resolve_host_tasks: Set[\"asyncio.Task[List[ResolveResult]]\"] = set()\n\n    def close(self) -> Awaitable[None]:\n        \"\"\"Close all ongoing DNS calls.\"\"\"\n        for fut in chain.from_iterable(self._throttle_dns_futures.values()):\n            fut.cancel()\n\n        for t in self._resolve_host_tasks:\n            t.cancel()\n\n        return super().close()\n\n    @property\n    def family(self) -> int:\n        \"\"\"Socket family like AF_INET.\"\"\"\n        return self._family\n\n    @property\n    def use_dns_cache(self) -> bool:\n        \"\"\"True if local DNS caching is enabled.\"\"\"\n        return self._use_dns_cache\n\n    def clear_dns_cache(\n        self, host: Optional[str] = None, port: Optional[int] = None\n    ) -> None:\n        \"\"\"Remove specified host/port or clear all dns local cache.\"\"\"\n        if host is not None and port is not None:\n            self._cached_hosts.remove((host, port))\n        elif host is not None or port is not None:\n            raise ValueError(\"either both host and port or none of them are allowed\")\n        else:\n            self._cached_hosts.clear()\n\n    async def _resolve_host(\n        self, host: str, port: int, traces: Optional[Sequence[\"Trace\"]] = None\n    ) -> List[ResolveResult]:\n        \"\"\"Resolve host and return list of addresses.\"\"\"\n        if is_ip_address(host):\n            return [\n                {\n                    \"hostname\": host,\n                    \"host\": host,\n                    \"port\": port,\n                    \"family\": self._family,\n                    \"proto\": 0,\n                    \"flags\": 0,\n                }\n            ]\n\n        if not self._use_dns_cache:\n\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_start(host)\n\n            res = await self._resolver.resolve(host, port, family=self._family)\n\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_end(host)\n\n            return res\n\n        key = (host, port)\n        if key in self._cached_hosts and not self._cached_hosts.expired(key):\n            # get result early, before any await (#4014)\n            result = self._cached_hosts.next_addrs(key)\n\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_cache_hit(host)\n            return result\n\n        futures: Set[\"asyncio.Future[None]\"]\n        #\n        # If multiple connectors are resolving the same host, we wait\n        # for the first one to resolve and then use the result for all of them.\n        # We use a throttle to ensure that we only resolve the host once\n        # and then use the result for all the waiters.\n        #\n        if key in self._throttle_dns_futures:\n            # get futures early, before any await (#4014)\n            futures = self._throttle_dns_futures[key]\n            future: asyncio.Future[None] = self._loop.create_future()\n            futures.add(future)\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_cache_hit(host)\n            try:\n                await future\n            finally:\n                futures.discard(future)\n            return self._cached_hosts.next_addrs(key)\n\n        # update dict early, before any await (#4014)\n        self._throttle_dns_futures[key] = futures = set()\n        # In this case we need to create a task to ensure that we can shield\n        # the task from cancellation as cancelling this lookup should not cancel\n        # the underlying lookup or else the cancel event will get broadcast to\n        # all the waiters across all connections.\n        #\n        coro = self._resolve_host_with_throttle(key, host, port, futures, traces)\n        loop = asyncio.get_running_loop()\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send immediately\n            resolved_host_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            resolved_host_task = loop.create_task(coro)\n\n        if not resolved_host_task.done():\n            self._resolve_host_tasks.add(resolved_host_task)\n            resolved_host_task.add_done_callback(self._resolve_host_tasks.discard)\n\n        try:\n            return await asyncio.shield(resolved_host_task)\n        except asyncio.CancelledError:\n\n            def drop_exception(fut: \"asyncio.Future[List[ResolveResult]]\") -> None:\n                with suppress(Exception, asyncio.CancelledError):\n                    fut.result()\n\n            resolved_host_task.add_done_callback(drop_exception)\n            raise\n\n    async def _resolve_host_with_throttle(\n        self,\n        key: Tuple[str, int],\n        host: str,\n        port: int,\n        futures: Set[\"asyncio.Future[None]\"],\n        traces: Optional[Sequence[\"Trace\"]],\n    ) -> List[ResolveResult]:\n        \"\"\"Resolve host and set result for all waiters.\n\n        This method must be run in a task and shielded from cancellation\n        to avoid cancelling the underlying lookup.\n        \"\"\"\n        if traces:\n            for trace in traces:\n                await trace.send_dns_cache_miss(host)\n        try:\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_start(host)\n\n            addrs = await self._resolver.resolve(host, port, family=self._family)\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_end(host)\n\n            self._cached_hosts.add(key, addrs)\n            for fut in futures:\n                set_result(fut, None)\n        except BaseException as e:\n            # any DNS exception is set for the waiters to raise the same exception.\n            # This coro is always run in task that is shielded from cancellation so\n            # we should never be propagating cancellation here.\n            for fut in futures:\n                set_exception(fut, e)\n            raise\n        finally:\n            self._throttle_dns_futures.pop(key)\n\n        return self._cached_hosts.next_addrs(key)\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        \"\"\"Create connection.\n\n        Has same keyword arguments as BaseEventLoop.create_connection.\n        \"\"\"\n        if req.proxy:\n            _, proto = await self._create_proxy_connection(req, traces, timeout)\n        else:\n            _, proto = await self._create_direct_connection(req, traces, timeout)\n\n        return proto\n\n    def _get_ssl_context(self, req: ClientRequest) -> Optional[SSLContext]:\n        \"\"\"Logic to get the correct SSL context\n\n        0. if req.ssl is false, return None\n\n        1. if ssl_context is specified in req, use it\n        2. if _ssl_context is specified in self, use it\n        3. otherwise:\n            1. if verify_ssl is not specified in req, use self.ssl_context\n               (will generate a default context according to self.verify_ssl)\n            2. if verify_ssl is True in req, generate a default SSL context\n            3. if verify_ssl is False in req, generate a SSL context that\n               won't verify\n        \"\"\"\n        if not req.is_ssl():\n            return None\n\n        if ssl is None:  # pragma: no cover\n            raise RuntimeError(\"SSL is not supported.\")\n        sslcontext = req.ssl\n        if isinstance(sslcontext, ssl.SSLContext):\n            return sslcontext\n        if sslcontext is not True:\n            # not verified or fingerprinted\n            return _SSL_CONTEXT_UNVERIFIED\n        sslcontext = self._ssl\n        if isinstance(sslcontext, ssl.SSLContext):\n            return sslcontext\n        if sslcontext is not True:\n            # not verified or fingerprinted\n            return _SSL_CONTEXT_UNVERIFIED\n        return _SSL_CONTEXT_VERIFIED\n\n    def _get_fingerprint(self, req: ClientRequest) -> Optional[\"Fingerprint\"]:\n        ret = req.ssl\n        if isinstance(ret, Fingerprint):\n            return ret\n        ret = self._ssl\n        if isinstance(ret, Fingerprint):\n            return ret\n        return None\n\n    async def _wrap_create_connection(\n        self,\n        *args: Any,\n        addr_infos: List[aiohappyeyeballs.AddrInfoType],\n        req: ClientRequest,\n        timeout: \"ClientTimeout\",\n        client_error: Type[Exception] = ClientConnectorError,\n        **kwargs: Any,\n    ) -> Tuple[asyncio.Transport, ResponseHandler]:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                sock = await aiohappyeyeballs.start_connection(\n                    addr_infos=addr_infos,\n                    local_addr_infos=self._local_addr_infos,\n                    happy_eyeballs_delay=self._happy_eyeballs_delay,\n                    interleave=self._interleave,\n                    loop=self._loop,\n                )\n                return await self._loop.create_connection(*args, **kwargs, sock=sock)\n        except cert_errors as exc:\n            raise ClientConnectorCertificateError(req.connection_key, exc) from exc\n        except ssl_errors as exc:\n            raise ClientConnectorSSLError(req.connection_key, exc) from exc\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise client_error(req.connection_key, exc) from exc\n\n    async def _wrap_existing_connection(\n        self,\n        *args: Any,\n        req: ClientRequest,\n        timeout: \"ClientTimeout\",\n        client_error: Type[Exception] = ClientConnectorError,\n        **kwargs: Any,\n    ) -> Tuple[asyncio.Transport, ResponseHandler]:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                return await self._loop.create_connection(*args, **kwargs)\n        except cert_errors as exc:\n            raise ClientConnectorCertificateError(req.connection_key, exc) from exc\n        except ssl_errors as exc:\n            raise ClientConnectorSSLError(req.connection_key, exc) from exc\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise client_error(req.connection_key, exc) from exc\n\n    def _fail_on_no_start_tls(self, req: \"ClientRequest\") -> None:\n        \"\"\"Raise a :py:exc:`RuntimeError` on missing ``start_tls()``.\n\n        It is necessary for TLS-in-TLS so that it is possible to\n        send HTTPS queries through HTTPS proxies.\n\n        This doesn't affect regular HTTP requests, though.\n        \"\"\"\n        if not req.is_ssl():\n            return\n\n        proxy_url = req.proxy\n        assert proxy_url is not None\n        if proxy_url.scheme != \"https\":\n            return\n\n        self._check_loop_for_start_tls()\n\n    def _check_loop_for_start_tls(self) -> None:\n        try:\n            self._loop.start_tls\n        except AttributeError as attr_exc:\n            raise RuntimeError(\n                \"An HTTPS request is being sent through an HTTPS proxy. \"\n                \"This needs support for TLS in TLS but it is not implemented \"\n                \"in your runtime for the stdlib asyncio.\\n\\n\"\n                \"Please upgrade to Python 3.11 or higher. For more details, \"\n                \"please see:\\n\"\n                \"* https://bugs.python.org/issue37179\\n\"\n                \"* https://github.com/python/cpython/pull/28073\\n\"\n                \"* https://docs.aiohttp.org/en/stable/\"\n                \"client_advanced.html#proxy-support\\n\"\n                \"* https://github.com/aio-libs/aiohttp/discussions/6044\\n\",\n            ) from attr_exc\n\n    def _loop_supports_start_tls(self) -> bool:\n        try:\n            self._check_loop_for_start_tls()\n        except RuntimeError:\n            return False\n        else:\n            return True\n\n    def _warn_about_tls_in_tls(\n        self,\n        underlying_transport: asyncio.Transport,\n        req: ClientRequest,\n    ) -> None:\n        \"\"\"Issue a warning if the requested URL has HTTPS scheme.\"\"\"\n        if req.request_info.url.scheme != \"https\":\n            return\n\n        asyncio_supports_tls_in_tls = getattr(\n            underlying_transport,\n            \"_start_tls_compatible\",\n            False,\n        )\n\n        if asyncio_supports_tls_in_tls:\n            return\n\n        warnings.warn(\n            \"An HTTPS request is being sent through an HTTPS proxy. \"\n            \"This support for TLS in TLS is known to be disabled \"\n            \"in the stdlib asyncio (Python <3.11). This is why you'll probably see \"\n            \"an error in the log below.\\n\\n\"\n            \"It is possible to enable it via monkeypatching. \"\n            \"For more details, see:\\n\"\n            \"* https://bugs.python.org/issue37179\\n\"\n            \"* https://github.com/python/cpython/pull/28073\\n\\n\"\n            \"You can temporarily patch this as follows:\\n\"\n            \"* https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support\\n\"\n            \"* https://github.com/aio-libs/aiohttp/discussions/6044\\n\",\n            RuntimeWarning,\n            source=self,\n            # Why `4`? At least 3 of the calls in the stack originate\n            # from the methods in this class.\n            stacklevel=3,\n        )\n\n    async def _start_tls_connection(\n        self,\n        underlying_transport: asyncio.Transport,\n        req: ClientRequest,\n        timeout: \"ClientTimeout\",\n        client_error: Type[Exception] = ClientConnectorError,\n    ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:\n        \"\"\"Wrap the raw TCP transport with TLS.\"\"\"\n        tls_proto = self._factory()  # Create a brand new proto for TLS\n        sslcontext = self._get_ssl_context(req)\n        if TYPE_CHECKING:\n            # _start_tls_connection is unreachable in the current code path\n            # if sslcontext is None.\n            assert sslcontext is not None\n\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                try:\n                    tls_transport = await self._loop.start_tls(\n                        underlying_transport,\n                        tls_proto,\n                        sslcontext,\n                        server_hostname=req.server_hostname or req.host,\n                        ssl_handshake_timeout=timeout.total,\n                    )\n                except BaseException:\n                    # We need to close the underlying transport since\n                    # `start_tls()` probably failed before it had a\n                    # chance to do this:\n                    underlying_transport.close()\n                    raise\n                if isinstance(tls_transport, asyncio.Transport):\n                    fingerprint = self._get_fingerprint(req)\n                    if fingerprint:\n                        try:\n                            fingerprint.check(tls_transport)\n                        except ServerFingerprintMismatch:\n                            tls_transport.close()\n                            if not self._cleanup_closed_disabled:\n                                self._cleanup_closed_transports.append(tls_transport)\n                            raise\n        except cert_errors as exc:\n            raise ClientConnectorCertificateError(req.connection_key, exc) from exc\n        except ssl_errors as exc:\n            raise ClientConnectorSSLError(req.connection_key, exc) from exc\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise client_error(req.connection_key, exc) from exc\n        except TypeError as type_err:\n            # Example cause looks like this:\n            # TypeError: transport <asyncio.sslproto._SSLProtocolTransport\n            # object at 0x7f760615e460> is not supported by start_tls()\n\n            raise ClientConnectionError(\n                \"Cannot initialize a TLS-in-TLS connection to host \"\n                f\"{req.host!s}:{req.port:d} through an underlying connection \"\n                f\"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} \"\n                f\"[{type_err!s}]\"\n            ) from type_err\n        else:\n            if tls_transport is None:\n                msg = \"Failed to start TLS (possibly caused by closing transport)\"\n                raise client_error(req.connection_key, OSError(msg))\n            tls_proto.connection_made(\n                tls_transport\n            )  # Kick the state machine of the new TLS protocol\n\n        return tls_transport, tls_proto\n\n    def _convert_hosts_to_addr_infos(\n        self, hosts: List[ResolveResult]\n    ) -> List[aiohappyeyeballs.AddrInfoType]:\n        \"\"\"Converts the list of hosts to a list of addr_infos.\n\n        The list of hosts is the result of a DNS lookup. The list of\n        addr_infos is the result of a call to `socket.getaddrinfo()`.\n        \"\"\"\n        addr_infos: List[aiohappyeyeballs.AddrInfoType] = []\n        for hinfo in hosts:\n            host = hinfo[\"host\"]\n            is_ipv6 = \":\" in host\n            family = socket.AF_INET6 if is_ipv6 else socket.AF_INET\n            if self._family and self._family != family:\n                continue\n            addr = (host, hinfo[\"port\"], 0, 0) if is_ipv6 else (host, hinfo[\"port\"])\n            addr_infos.append(\n                (family, socket.SOCK_STREAM, socket.IPPROTO_TCP, \"\", addr)\n            )\n        return addr_infos\n\n    async def _create_direct_connection(\n        self,\n        req: ClientRequest,\n        traces: List[\"Trace\"],\n        timeout: \"ClientTimeout\",\n        *,\n        client_error: Type[Exception] = ClientConnectorError,\n    ) -> Tuple[asyncio.Transport, ResponseHandler]:\n        sslcontext = self._get_ssl_context(req)\n        fingerprint = self._get_fingerprint(req)\n\n        host = req.url.raw_host\n        assert host is not None\n        # Replace multiple trailing dots with a single one.\n        # A trailing dot is only present for fully-qualified domain names.\n        # See https://github.com/aio-libs/aiohttp/pull/7364.\n        if host.endswith(\"..\"):\n            host = host.rstrip(\".\") + \".\"\n        port = req.port\n        assert port is not None\n        try:\n            # Cancelling this lookup should not cancel the underlying lookup\n            #  or else the cancel event will get broadcast to all the waiters\n            #  across all connections.\n            hosts = await self._resolve_host(host, port, traces=traces)\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            # in case of proxy it is not ClientProxyConnectionError\n            # it is problem of resolving proxy ip itself\n            raise ClientConnectorDNSError(req.connection_key, exc) from exc\n\n        last_exc: Optional[Exception] = None\n        addr_infos = self._convert_hosts_to_addr_infos(hosts)\n        while addr_infos:\n            # Strip trailing dots, certificates contain FQDN without dots.\n            # See https://github.com/aio-libs/aiohttp/issues/3636\n            server_hostname = (\n                (req.server_hostname or host).rstrip(\".\") if sslcontext else None\n            )\n\n            try:\n                transp, proto = await self._wrap_create_connection(\n                    self._factory,\n                    timeout=timeout,\n                    ssl=sslcontext,\n                    addr_infos=addr_infos,\n                    server_hostname=server_hostname,\n                    req=req,\n                    client_error=client_error,\n                )\n            except (ClientConnectorError, asyncio.TimeoutError) as exc:\n                last_exc = exc\n                aiohappyeyeballs.pop_addr_infos_interleave(addr_infos, self._interleave)\n                continue\n\n            if req.is_ssl() and fingerprint:\n                try:\n                    fingerprint.check(transp)\n                except ServerFingerprintMismatch as exc:\n                    transp.close()\n                    if not self._cleanup_closed_disabled:\n                        self._cleanup_closed_transports.append(transp)\n                    last_exc = exc\n                    # Remove the bad peer from the list of addr_infos\n                    sock: socket.socket = transp.get_extra_info(\"socket\")\n                    bad_peer = sock.getpeername()\n                    aiohappyeyeballs.remove_addr_infos(addr_infos, bad_peer)\n                    continue\n\n            return transp, proto\n        else:\n            assert last_exc is not None\n            raise last_exc\n\n    async def _create_proxy_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:\n        self._fail_on_no_start_tls(req)\n        runtime_has_start_tls = self._loop_supports_start_tls()\n\n        headers: Dict[str, str] = {}\n        if req.proxy_headers is not None:\n            headers = req.proxy_headers  # type: ignore[assignment]\n        headers[hdrs.HOST] = req.headers[hdrs.HOST]\n\n        url = req.proxy\n        assert url is not None\n        proxy_req = ClientRequest(\n            hdrs.METH_GET,\n            url,\n            headers=headers,\n            auth=req.proxy_auth,\n            loop=self._loop,\n            ssl=req.ssl,\n        )\n\n        # create connection to proxy server\n        transport, proto = await self._create_direct_connection(\n            proxy_req, [], timeout, client_error=ClientProxyConnectionError\n        )\n\n        auth = proxy_req.headers.pop(hdrs.AUTHORIZATION, None)\n        if auth is not None:\n            if not req.is_ssl():\n                req.headers[hdrs.PROXY_AUTHORIZATION] = auth\n            else:\n                proxy_req.headers[hdrs.PROXY_AUTHORIZATION] = auth\n\n        if req.is_ssl():\n            if runtime_has_start_tls:\n                self._warn_about_tls_in_tls(transport, req)\n\n            # For HTTPS requests over HTTP proxy\n            # we must notify proxy to tunnel connection\n            # so we send CONNECT command:\n            #   CONNECT www.python.org:443 HTTP/1.1\n            #   Host: www.python.org\n            #\n            # next we must do TLS handshake and so on\n            # to do this we must wrap raw socket into secure one\n            # asyncio handles this perfectly\n            proxy_req.method = hdrs.METH_CONNECT\n            proxy_req.url = req.url\n            key = req.connection_key._replace(\n                proxy=None, proxy_auth=None, proxy_headers_hash=None\n            )\n            conn = Connection(self, key, proto, self._loop)\n            proxy_resp = await proxy_req.send(conn)\n            try:\n                protocol = conn._protocol\n                assert protocol is not None\n\n                # read_until_eof=True will ensure the connection isn't closed\n                # once the response is received and processed allowing\n                # START_TLS to work on the connection below.\n                protocol.set_response_params(\n                    read_until_eof=runtime_has_start_tls,\n                    timeout_ceil_threshold=self._timeout_ceil_threshold,\n                )\n                resp = await proxy_resp.start(conn)\n            except BaseException:\n                proxy_resp.close()\n                conn.close()\n                raise\n            else:\n                conn._protocol = None\n                try:\n                    if resp.status != 200:\n                        message = resp.reason\n                        if message is None:\n                            message = HTTPStatus(resp.status).phrase\n                        raise ClientHttpProxyError(\n                            proxy_resp.request_info,\n                            resp.history,\n                            status=resp.status,\n                            message=message,\n                            headers=resp.headers,\n                        )\n                    if not runtime_has_start_tls:\n                        rawsock = transport.get_extra_info(\"socket\", default=None)\n                        if rawsock is None:\n                            raise RuntimeError(\n                                \"Transport does not expose socket instance\"\n                            )\n                        # Duplicate the socket, so now we can close proxy transport\n                        rawsock = rawsock.dup()\n                except BaseException:\n                    # It shouldn't be closed in `finally` because it's fed to\n                    # `loop.start_tls()` and the docs say not to touch it after\n                    # passing there.\n                    transport.close()\n                    raise\n                finally:\n                    if not runtime_has_start_tls:\n                        transport.close()\n\n                if not runtime_has_start_tls:\n                    # HTTP proxy with support for upgrade to HTTPS\n                    sslcontext = self._get_ssl_context(req)\n                    return await self._wrap_existing_connection(\n                        self._factory,\n                        timeout=timeout,\n                        ssl=sslcontext,\n                        sock=rawsock,\n                        server_hostname=req.host,\n                        req=req,\n                    )\n\n                return await self._start_tls_connection(\n                    # Access the old transport for the last time before it's\n                    # closed and forgotten forever:\n                    transport,\n                    req=req,\n                    timeout=timeout,\n                )\n            finally:\n                proxy_resp.close()\n\n        return transport, proto\n\n\nclass UnixConnector(BaseConnector):\n    \"\"\"Unix socket connector.\n\n    path - Unix socket path.\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    loop - Optional event loop.\n    \"\"\"\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({\"unix\"})\n\n    def __init__(\n        self,\n        path: str,\n        force_close: bool = False,\n        keepalive_timeout: Union[object, float, None] = sentinel,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n    ) -> None:\n        super().__init__(\n            force_close=force_close,\n            keepalive_timeout=keepalive_timeout,\n            limit=limit,\n            limit_per_host=limit_per_host,\n            loop=loop,\n        )\n        self._path = path\n\n    @property\n    def path(self) -> str:\n        \"\"\"Path to unix socket.\"\"\"\n        return self._path\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                _, proto = await self._loop.create_unix_connection(\n                    self._factory, self._path\n                )\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc\n\n        return proto\n\n\nclass NamedPipeConnector(BaseConnector):\n    \"\"\"Named pipe connector.\n\n    Only supported by the proactor event loop.\n    See also: https://docs.python.org/3/library/asyncio-eventloop.html\n\n    path - Windows named pipe path.\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    loop - Optional event loop.\n    \"\"\"\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({\"npipe\"})\n\n    def __init__(\n        self,\n        path: str,\n        force_close: bool = False,\n        keepalive_timeout: Union[object, float, None] = sentinel,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n    ) -> None:\n        super().__init__(\n            force_close=force_close,\n            keepalive_timeout=keepalive_timeout,\n            limit=limit,\n            limit_per_host=limit_per_host,\n            loop=loop,\n        )\n        if not isinstance(\n            self._loop, asyncio.ProactorEventLoop  # type: ignore[attr-defined]\n        ):\n            raise RuntimeError(\n                \"Named Pipes only available in proactor loop under windows\"\n            )\n        self._path = path\n\n    @property\n    def path(self) -> str:\n        \"\"\"Path to the named pipe.\"\"\"\n        return self._path\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                _, proto = await self._loop.create_pipe_connection(  # type: ignore[attr-defined]\n                    self._factory, self._path\n                )\n                # the drain is required so that the connection_made is called\n                # and transport is set otherwise it is not set before the\n                # `assert conn.transport is not None`\n                # in client.py's _request method\n                await asyncio.sleep(0)\n                # other option is to manually set transport like\n                # `proto.transport = trans`\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise ClientConnectorError(req.connection_key, exc) from exc\n\n        return cast(ResponseHandler, proto)\n",
            "new_file_content": "import asyncio\nimport functools\nimport random\nimport socket\nimport sys\nimport traceback\nimport warnings\nfrom collections import OrderedDict, defaultdict, deque\nfrom contextlib import suppress\nfrom http import HTTPStatus\nfrom itertools import chain, cycle, islice\nfrom time import monotonic\nfrom types import TracebackType\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Awaitable,\n    Callable,\n    DefaultDict,\n    Deque,\n    Dict,\n    Iterator,\n    List,\n    Literal,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Type,\n    Union,\n    cast,\n)\n\nimport aiohappyeyeballs\n\nfrom . import hdrs, helpers\nfrom .abc import AbstractResolver, ResolveResult\nfrom .client_exceptions import (\n    ClientConnectionError,\n    ClientConnectorCertificateError,\n    ClientConnectorDNSError,\n    ClientConnectorError,\n    ClientConnectorSSLError,\n    ClientHttpProxyError,\n    ClientProxyConnectionError,\n    ServerFingerprintMismatch,\n    UnixClientConnectorError,\n    cert_errors,\n    ssl_errors,\n)\nfrom .client_proto import ResponseHandler\nfrom .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params\nfrom .helpers import (\n    ceil_timeout,\n    is_ip_address,\n    noop,\n    sentinel,\n    set_exception,\n    set_result,\n)\nfrom .resolver import DefaultResolver\n\ntry:\n    import ssl\n\n    SSLContext = ssl.SSLContext\nexcept ImportError:  # pragma: no cover\n    ssl = None  # type: ignore[assignment]\n    SSLContext = object  # type: ignore[misc,assignment]\n\n\nEMPTY_SCHEMA_SET = frozenset({\"\"})\nHTTP_SCHEMA_SET = frozenset({\"http\", \"https\"})\nWS_SCHEMA_SET = frozenset({\"ws\", \"wss\"})\n\nHTTP_AND_EMPTY_SCHEMA_SET = HTTP_SCHEMA_SET | EMPTY_SCHEMA_SET\nHIGH_LEVEL_SCHEMA_SET = HTTP_AND_EMPTY_SCHEMA_SET | WS_SCHEMA_SET\n\n\n__all__ = (\"BaseConnector\", \"TCPConnector\", \"UnixConnector\", \"NamedPipeConnector\")\n\n\nif TYPE_CHECKING:\n    from .client import ClientTimeout\n    from .client_reqrep import ConnectionKey\n    from .tracing import Trace\n\n\nclass _DeprecationWaiter:\n    __slots__ = (\"_awaitable\", \"_awaited\")\n\n    def __init__(self, awaitable: Awaitable[Any]) -> None:\n        self._awaitable = awaitable\n        self._awaited = False\n\n    def __await__(self) -> Any:\n        self._awaited = True\n        return self._awaitable.__await__()\n\n    def __del__(self) -> None:\n        if not self._awaited:\n            warnings.warn(\n                \"Connector.close() is a coroutine, \"\n                \"please use await connector.close()\",\n                DeprecationWarning,\n            )\n\n\nclass Connection:\n\n    _source_traceback = None\n\n    def __init__(\n        self,\n        connector: \"BaseConnector\",\n        key: \"ConnectionKey\",\n        protocol: ResponseHandler,\n        loop: asyncio.AbstractEventLoop,\n    ) -> None:\n        self._key = key\n        self._connector = connector\n        self._loop = loop\n        self._protocol: Optional[ResponseHandler] = protocol\n        self._callbacks: List[Callable[[], None]] = []\n\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n    def __repr__(self) -> str:\n        return f\"Connection<{self._key}>\"\n\n    def __del__(self, _warnings: Any = warnings) -> None:\n        if self._protocol is not None:\n            kwargs = {\"source\": self}\n            _warnings.warn(f\"Unclosed connection {self!r}\", ResourceWarning, **kwargs)\n            if self._loop.is_closed():\n                return\n\n            self._connector._release(self._key, self._protocol, should_close=True)\n\n            context = {\"client_connection\": self, \"message\": \"Unclosed connection\"}\n            if self._source_traceback is not None:\n                context[\"source_traceback\"] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def __bool__(self) -> Literal[True]:\n        \"\"\"Force subclasses to not be falsy, to make checks simpler.\"\"\"\n        return True\n\n    @property\n    def loop(self) -> asyncio.AbstractEventLoop:\n        warnings.warn(\n            \"connector.loop property is deprecated\", DeprecationWarning, stacklevel=2\n        )\n        return self._loop\n\n    @property\n    def transport(self) -> Optional[asyncio.Transport]:\n        if self._protocol is None:\n            return None\n        return self._protocol.transport\n\n    @property\n    def protocol(self) -> Optional[ResponseHandler]:\n        return self._protocol\n\n    def add_callback(self, callback: Callable[[], None]) -> None:\n        if callback is not None:\n            self._callbacks.append(callback)\n\n    def _notify_release(self) -> None:\n        callbacks, self._callbacks = self._callbacks[:], []\n\n        for cb in callbacks:\n            with suppress(Exception):\n                cb()\n\n    def close(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(self._key, self._protocol, should_close=True)\n            self._protocol = None\n\n    def release(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(self._key, self._protocol)\n            self._protocol = None\n\n    @property\n    def closed(self) -> bool:\n        return self._protocol is None or not self._protocol.is_connected()\n\n\nclass _TransportPlaceholder:\n    \"\"\"placeholder for BaseConnector.connect function\"\"\"\n\n    __slots__ = ()\n\n    def close(self) -> None:\n        \"\"\"Close the placeholder transport.\"\"\"\n\n\nclass BaseConnector:\n    \"\"\"Base connector class.\n\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    enable_cleanup_closed - Enables clean-up closed ssl transports.\n                            Disabled by default.\n    timeout_ceil_threshold - Trigger ceiling of timeout values when\n                             it's above timeout_ceil_threshold.\n    loop - Optional event loop.\n    \"\"\"\n\n    _closed = True  # prevent AttributeError in __del__ if ctor was failed\n    _source_traceback = None\n\n    # abort transport after 2 seconds (cleanup broken connections)\n    _cleanup_closed_period = 2.0\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET\n\n    def __init__(\n        self,\n        *,\n        keepalive_timeout: Union[object, None, float] = sentinel,\n        force_close: bool = False,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        enable_cleanup_closed: bool = False,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n        timeout_ceil_threshold: float = 5,\n    ) -> None:\n\n        if force_close:\n            if keepalive_timeout is not None and keepalive_timeout is not sentinel:\n                raise ValueError(\n                    \"keepalive_timeout cannot be set if force_close is True\"\n                )\n        else:\n            if keepalive_timeout is sentinel:\n                keepalive_timeout = 15.0\n\n        loop = loop or asyncio.get_running_loop()\n        self._timeout_ceil_threshold = timeout_ceil_threshold\n\n        self._closed = False\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        # Connection pool of reusable connections.\n        # We use a deque to store connections because it has O(1) popleft()\n        # and O(1) append() operations to implement a FIFO queue.\n        self._conns: DefaultDict[\n            ConnectionKey, Deque[Tuple[ResponseHandler, float]]\n        ] = defaultdict(deque)\n        self._limit = limit\n        self._limit_per_host = limit_per_host\n        self._acquired: Set[ResponseHandler] = set()\n        self._acquired_per_host: DefaultDict[ConnectionKey, Set[ResponseHandler]] = (\n            defaultdict(set)\n        )\n        self._keepalive_timeout = cast(float, keepalive_timeout)\n        self._force_close = force_close\n\n        # {host_key: FIFO list of waiters}\n        # The FIFO is implemented with an OrderedDict with None keys because\n        # python does not have an ordered set.\n        self._waiters: DefaultDict[\n            ConnectionKey, OrderedDict[asyncio.Future[None], None]\n        ] = defaultdict(OrderedDict)\n\n        self._loop = loop\n        self._factory = functools.partial(ResponseHandler, loop=loop)\n\n        # start keep-alive connection cleanup task\n        self._cleanup_handle: Optional[asyncio.TimerHandle] = None\n\n        # start cleanup closed transports task\n        self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None\n        self._cleanup_closed_disabled = not enable_cleanup_closed\n        self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = []\n        self._cleanup_closed()\n\n    def __del__(self, _warnings: Any = warnings) -> None:\n        if self._closed:\n            return\n        if not self._conns:\n            return\n\n        conns = [repr(c) for c in self._conns.values()]\n\n        self._close()\n\n        kwargs = {\"source\": self}\n        _warnings.warn(f\"Unclosed connector {self!r}\", ResourceWarning, **kwargs)\n        context = {\n            \"connector\": self,\n            \"connections\": conns,\n            \"message\": \"Unclosed connector\",\n        }\n        if self._source_traceback is not None:\n            context[\"source_traceback\"] = self._source_traceback\n        self._loop.call_exception_handler(context)\n\n    def __enter__(self) -> \"BaseConnector\":\n        warnings.warn(\n            '\"with Connector():\" is deprecated, '\n            'use \"async with Connector():\" instead',\n            DeprecationWarning,\n        )\n        return self\n\n    def __exit__(self, *exc: Any) -> None:\n        self._close()\n\n    async def __aenter__(self) -> \"BaseConnector\":\n        return self\n\n    async def __aexit__(\n        self,\n        exc_type: Optional[Type[BaseException]] = None,\n        exc_value: Optional[BaseException] = None,\n        exc_traceback: Optional[TracebackType] = None,\n    ) -> None:\n        await self.close()\n\n    @property\n    def force_close(self) -> bool:\n        \"\"\"Ultimately close connection on releasing if True.\"\"\"\n        return self._force_close\n\n    @property\n    def limit(self) -> int:\n        \"\"\"The total number for simultaneous connections.\n\n        If limit is 0 the connector has no limit.\n        The default limit size is 100.\n        \"\"\"\n        return self._limit\n\n    @property\n    def limit_per_host(self) -> int:\n        \"\"\"The limit for simultaneous connections to the same endpoint.\n\n        Endpoints are the same if they are have equal\n        (host, port, is_ssl) triple.\n        \"\"\"\n        return self._limit_per_host\n\n    def _cleanup(self) -> None:\n        \"\"\"Cleanup unused transports.\"\"\"\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            # _cleanup_handle should be unset, otherwise _release() will not\n            # recreate it ever!\n            self._cleanup_handle = None\n\n        now = monotonic()\n        timeout = self._keepalive_timeout\n\n        if self._conns:\n            connections = defaultdict(deque)\n            deadline = now - timeout\n            for key, conns in self._conns.items():\n                alive: Deque[Tuple[ResponseHandler, float]] = deque()\n                for proto, use_time in conns:\n                    if proto.is_connected() and use_time - deadline >= 0:\n                        alive.append((proto, use_time))\n                        continue\n                    transport = proto.transport\n                    proto.close()\n                    if not self._cleanup_closed_disabled and key.is_ssl:\n                        self._cleanup_closed_transports.append(transport)\n\n                if alive:\n                    connections[key] = alive\n\n            self._conns = connections\n\n        if self._conns:\n            self._cleanup_handle = helpers.weakref_handle(\n                self,\n                \"_cleanup\",\n                timeout,\n                self._loop,\n                timeout_ceil_threshold=self._timeout_ceil_threshold,\n            )\n\n    def _cleanup_closed(self) -> None:\n        \"\"\"Double confirmation for transport close.\n\n        Some broken ssl servers may leave socket open without proper close.\n        \"\"\"\n        if self._cleanup_closed_handle:\n            self._cleanup_closed_handle.cancel()\n\n        for transport in self._cleanup_closed_transports:\n            if transport is not None:\n                transport.abort()\n\n        self._cleanup_closed_transports = []\n\n        if not self._cleanup_closed_disabled:\n            self._cleanup_closed_handle = helpers.weakref_handle(\n                self,\n                \"_cleanup_closed\",\n                self._cleanup_closed_period,\n                self._loop,\n                timeout_ceil_threshold=self._timeout_ceil_threshold,\n            )\n\n    def close(self) -> Awaitable[None]:\n        \"\"\"Close all opened transports.\"\"\"\n        self._close()\n        return _DeprecationWaiter(noop())\n\n    def _close(self) -> None:\n        if self._closed:\n            return\n\n        self._closed = True\n\n        try:\n            if self._loop.is_closed():\n                return\n\n            # cancel cleanup task\n            if self._cleanup_handle:\n                self._cleanup_handle.cancel()\n\n            # cancel cleanup close task\n            if self._cleanup_closed_handle:\n                self._cleanup_closed_handle.cancel()\n\n            for data in self._conns.values():\n                for proto, t0 in data:\n                    proto.close()\n\n            for proto in self._acquired:\n                proto.close()\n\n            for transport in self._cleanup_closed_transports:\n                if transport is not None:\n                    transport.abort()\n\n        finally:\n            self._conns.clear()\n            self._acquired.clear()\n            for keyed_waiters in self._waiters.values():\n                for keyed_waiter in keyed_waiters:\n                    keyed_waiter.cancel()\n            self._waiters.clear()\n            self._cleanup_handle = None\n            self._cleanup_closed_transports.clear()\n            self._cleanup_closed_handle = None\n\n    @property\n    def closed(self) -> bool:\n        \"\"\"Is connector closed.\n\n        A readonly property.\n        \"\"\"\n        return self._closed\n\n    def _available_connections(self, key: \"ConnectionKey\") -> int:\n        \"\"\"\n        Return number of available connections.\n\n        The limit, limit_per_host and the connection key are taken into account.\n\n        If it returns less than 1 means that there are no connections\n        available.\n        \"\"\"\n        # check total available connections\n        # If there are no limits, this will always return 1\n        total_remain = 1\n\n        if self._limit and (total_remain := self._limit - len(self._acquired)) <= 0:\n            return total_remain\n\n        # check limit per host\n        if host_remain := self._limit_per_host:\n            if acquired := self._acquired_per_host.get(key):\n                host_remain -= len(acquired)\n            if total_remain > host_remain:\n                return host_remain\n\n        return total_remain\n\n    async def connect(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> Connection:\n        \"\"\"Get from pool or create new connection.\"\"\"\n        key = req.connection_key\n        if (conn := await self._get(key, traces)) is not None:\n            # If we do not have to wait and we can get a connection from the pool\n            # we can avoid the timeout ceil logic and directly return the connection\n            return conn\n\n        async with ceil_timeout(timeout.connect, timeout.ceil_threshold):\n            if self._available_connections(key) <= 0:\n                await self._wait_for_available_connection(key, traces)\n                if (conn := await self._get(key, traces)) is not None:\n                    return conn\n\n            placeholder = cast(ResponseHandler, _TransportPlaceholder())\n            self._acquired.add(placeholder)\n            self._acquired_per_host[key].add(placeholder)\n\n            try:\n                # Traces are done inside the try block to ensure that the\n                # that the placeholder is still cleaned up if an exception\n                # is raised.\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_create_start()\n                proto = await self._create_connection(req, traces, timeout)\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_create_end()\n            except BaseException:\n                self._release_acquired(key, placeholder)\n                raise\n            else:\n                if self._closed:\n                    proto.close()\n                    raise ClientConnectionError(\"Connector is closed.\")\n\n        # The connection was successfully created, drop the placeholder\n        # and add the real connection to the acquired set. There should\n        # be no awaits after the proto is added to the acquired set\n        # to ensure that the connection is not left in the acquired set\n        # on cancellation.\n        acquired_per_host = self._acquired_per_host[key]\n        self._acquired.remove(placeholder)\n        acquired_per_host.remove(placeholder)\n        self._acquired.add(proto)\n        acquired_per_host.add(proto)\n        return Connection(self, key, proto, self._loop)\n\n    async def _wait_for_available_connection(\n        self, key: \"ConnectionKey\", traces: List[\"Trace\"]\n    ) -> None:\n        \"\"\"Wait for an available connection slot.\"\"\"\n        # We loop here because there is a race between\n        # the connection limit check and the connection\n        # being acquired. If the connection is acquired\n        # between the check and the await statement, we\n        # need to loop again to check if the connection\n        # slot is still available.\n        attempts = 0\n        while True:\n            fut: asyncio.Future[None] = self._loop.create_future()\n            keyed_waiters = self._waiters[key]\n            keyed_waiters[fut] = None\n            if attempts:\n                # If we have waited before, we need to move the waiter\n                # to the front of the queue as otherwise we might get\n                # starved and hit the timeout.\n                keyed_waiters.move_to_end(fut, last=False)\n\n            try:\n                # Traces happen in the try block to ensure that the\n                # the waiter is still cleaned up if an exception is raised.\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_queued_start()\n                await fut\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_queued_end()\n            finally:\n                # pop the waiter from the queue if its still\n                # there and not already removed by _release_waiter\n                keyed_waiters.pop(fut, None)\n                if not self._waiters.get(key, True):\n                    del self._waiters[key]\n\n            if self._available_connections(key) > 0:\n                break\n            attempts += 1\n\n    async def _get(\n        self, key: \"ConnectionKey\", traces: List[\"Trace\"]\n    ) -> Optional[Connection]:\n        \"\"\"Get next reusable connection for the key or None.\n\n        The connection will be marked as acquired.\n        \"\"\"\n        if (conns := self._conns.get(key)) is None:\n            return None\n\n        t1 = monotonic()\n        while conns:\n            proto, t0 = conns.popleft()\n            # We will we reuse the connection if its connected and\n            # the keepalive timeout has not been exceeded\n            if proto.is_connected() and t1 - t0 <= self._keepalive_timeout:\n                if not conns:\n                    # The very last connection was reclaimed: drop the key\n                    del self._conns[key]\n                self._acquired.add(proto)\n                self._acquired_per_host[key].add(proto)\n                if traces:\n                    for trace in traces:\n                        try:\n                            await trace.send_connection_reuseconn()\n                        except BaseException:\n                            self._release_acquired(key, proto)\n                            raise\n                return Connection(self, key, proto, self._loop)\n\n            # Connection cannot be reused, close it\n            transport = proto.transport\n            proto.close()\n            # only for SSL transports\n            if not self._cleanup_closed_disabled and key.is_ssl:\n                self._cleanup_closed_transports.append(transport)\n\n        # No more connections: drop the key\n        del self._conns[key]\n        return None\n\n    def _release_waiter(self) -> None:\n        \"\"\"\n        Iterates over all waiters until one to be released is found.\n\n        The one to be released is not finished and\n        belongs to a host that has available connections.\n        \"\"\"\n        if not self._waiters:\n            return\n\n        # Having the dict keys ordered this avoids to iterate\n        # at the same order at each call.\n        queues = list(self._waiters)\n        random.shuffle(queues)\n\n        for key in queues:\n            if self._available_connections(key) < 1:\n                continue\n\n            waiters = self._waiters[key]\n            while waiters:\n                waiter, _ = waiters.popitem(last=False)\n                if not waiter.done():\n                    waiter.set_result(None)\n                    return\n\n    def _release_acquired(self, key: \"ConnectionKey\", proto: ResponseHandler) -> None:\n        \"\"\"Release acquired connection.\"\"\"\n        if self._closed:\n            # acquired connection is already released on connector closing\n            return\n\n        self._acquired.discard(proto)\n        if conns := self._acquired_per_host.get(key):\n            conns.discard(proto)\n            if not conns:\n                del self._acquired_per_host[key]\n        self._release_waiter()\n\n    def _release(\n        self,\n        key: \"ConnectionKey\",\n        protocol: ResponseHandler,\n        *,\n        should_close: bool = False,\n    ) -> None:\n        if self._closed:\n            # acquired connection is already released on connector closing\n            return\n\n        self._release_acquired(key, protocol)\n\n        if self._force_close:\n            should_close = True\n\n        if should_close or protocol.should_close:\n            transport = protocol.transport\n            protocol.close()\n\n            if key.is_ssl and not self._cleanup_closed_disabled:\n                self._cleanup_closed_transports.append(transport)\n            return\n\n        self._conns[key].append((protocol, monotonic()))\n\n        if self._cleanup_handle is None:\n            self._cleanup_handle = helpers.weakref_handle(\n                self,\n                \"_cleanup\",\n                self._keepalive_timeout,\n                self._loop,\n                timeout_ceil_threshold=self._timeout_ceil_threshold,\n            )\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        raise NotImplementedError()\n\n\nclass _DNSCacheTable:\n    def __init__(self, ttl: Optional[float] = None) -> None:\n        self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[ResolveResult], int]] = {}\n        self._timestamps: Dict[Tuple[str, int], float] = {}\n        self._ttl = ttl\n\n    def __contains__(self, host: object) -> bool:\n        return host in self._addrs_rr\n\n    def add(self, key: Tuple[str, int], addrs: List[ResolveResult]) -> None:\n        self._addrs_rr[key] = (cycle(addrs), len(addrs))\n\n        if self._ttl is not None:\n            self._timestamps[key] = monotonic()\n\n    def remove(self, key: Tuple[str, int]) -> None:\n        self._addrs_rr.pop(key, None)\n\n        if self._ttl is not None:\n            self._timestamps.pop(key, None)\n\n    def clear(self) -> None:\n        self._addrs_rr.clear()\n        self._timestamps.clear()\n\n    def next_addrs(self, key: Tuple[str, int]) -> List[ResolveResult]:\n        loop, length = self._addrs_rr[key]\n        addrs = list(islice(loop, length))\n        # Consume one more element to shift internal state of `cycle`\n        next(loop)\n        return addrs\n\n    def expired(self, key: Tuple[str, int]) -> bool:\n        if self._ttl is None:\n            return False\n\n        return self._timestamps[key] + self._ttl < monotonic()\n\n\ndef _make_ssl_context(verified: bool) -> SSLContext:\n    \"\"\"Create SSL context.\n\n    This method is not async-friendly and should be called from a thread\n    because it will load certificates from disk and do other blocking I/O.\n    \"\"\"\n    if ssl is None:\n        # No ssl support\n        return None\n    if verified:\n        return ssl.create_default_context()\n    sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n    sslcontext.options |= ssl.OP_NO_SSLv2\n    sslcontext.options |= ssl.OP_NO_SSLv3\n    sslcontext.check_hostname = False\n    sslcontext.verify_mode = ssl.CERT_NONE\n    sslcontext.options |= ssl.OP_NO_COMPRESSION\n    sslcontext.set_default_verify_paths()\n    return sslcontext\n\n\n# The default SSLContext objects are created at import time\n# since they do blocking I/O to load certificates from disk,\n# and imports should always be done before the event loop starts\n# or in a thread.\n_SSL_CONTEXT_VERIFIED = _make_ssl_context(True)\n_SSL_CONTEXT_UNVERIFIED = _make_ssl_context(False)\n\n\nclass TCPConnector(BaseConnector):\n    \"\"\"TCP connector.\n\n    verify_ssl - Set to True to check ssl certifications.\n    fingerprint - Pass the binary sha256\n        digest of the expected certificate in DER format to verify\n        that the certificate the server presents matches. See also\n        https://en.wikipedia.org/wiki/HTTP_Public_Key_Pinning\n    resolver - Enable DNS lookups and use this\n        resolver\n    use_dns_cache - Use memory cache for DNS lookups.\n    ttl_dns_cache - Max seconds having cached a DNS entry, None forever.\n    family - socket address family\n    local_addr - local tuple of (host, port) to bind socket to\n\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    enable_cleanup_closed - Enables clean-up closed ssl transports.\n                            Disabled by default.\n    happy_eyeballs_delay - This is the “Connection Attempt Delay”\n                           as defined in RFC 8305. To disable\n                           the happy eyeballs algorithm, set to None.\n    interleave - “First Address Family Count” as defined in RFC 8305\n    loop - Optional event loop.\n    \"\"\"\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({\"tcp\"})\n\n    def __init__(\n        self,\n        *,\n        verify_ssl: bool = True,\n        fingerprint: Optional[bytes] = None,\n        use_dns_cache: bool = True,\n        ttl_dns_cache: Optional[int] = 10,\n        family: socket.AddressFamily = socket.AddressFamily.AF_UNSPEC,\n        ssl_context: Optional[SSLContext] = None,\n        ssl: Union[bool, Fingerprint, SSLContext] = True,\n        local_addr: Optional[Tuple[str, int]] = None,\n        resolver: Optional[AbstractResolver] = None,\n        keepalive_timeout: Union[None, float, object] = sentinel,\n        force_close: bool = False,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        enable_cleanup_closed: bool = False,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n        timeout_ceil_threshold: float = 5,\n        happy_eyeballs_delay: Optional[float] = 0.25,\n        interleave: Optional[int] = None,\n    ):\n        super().__init__(\n            keepalive_timeout=keepalive_timeout,\n            force_close=force_close,\n            limit=limit,\n            limit_per_host=limit_per_host,\n            enable_cleanup_closed=enable_cleanup_closed,\n            loop=loop,\n            timeout_ceil_threshold=timeout_ceil_threshold,\n        )\n\n        self._ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)\n        if resolver is None:\n            resolver = DefaultResolver(loop=self._loop)\n        self._resolver = resolver\n\n        self._use_dns_cache = use_dns_cache\n        self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache)\n        self._throttle_dns_futures: Dict[\n            Tuple[str, int], Set[\"asyncio.Future[None]\"]\n        ] = {}\n        self._family = family\n        self._local_addr_infos = aiohappyeyeballs.addr_to_addr_infos(local_addr)\n        self._happy_eyeballs_delay = happy_eyeballs_delay\n        self._interleave = interleave\n        self._resolve_host_tasks: Set[\"asyncio.Task[List[ResolveResult]]\"] = set()\n\n    def close(self) -> Awaitable[None]:\n        \"\"\"Close all ongoing DNS calls.\"\"\"\n        for fut in chain.from_iterable(self._throttle_dns_futures.values()):\n            fut.cancel()\n\n        for t in self._resolve_host_tasks:\n            t.cancel()\n\n        return super().close()\n\n    @property\n    def family(self) -> int:\n        \"\"\"Socket family like AF_INET.\"\"\"\n        return self._family\n\n    @property\n    def use_dns_cache(self) -> bool:\n        \"\"\"True if local DNS caching is enabled.\"\"\"\n        return self._use_dns_cache\n\n    def clear_dns_cache(\n        self, host: Optional[str] = None, port: Optional[int] = None\n    ) -> None:\n        \"\"\"Remove specified host/port or clear all dns local cache.\"\"\"\n        if host is not None and port is not None:\n            self._cached_hosts.remove((host, port))\n        elif host is not None or port is not None:\n            raise ValueError(\"either both host and port or none of them are allowed\")\n        else:\n            self._cached_hosts.clear()\n\n    async def _resolve_host(\n        self, host: str, port: int, traces: Optional[Sequence[\"Trace\"]] = None\n    ) -> List[ResolveResult]:\n        \"\"\"Resolve host and return list of addresses.\"\"\"\n        if is_ip_address(host):\n            return [\n                {\n                    \"hostname\": host,\n                    \"host\": host,\n                    \"port\": port,\n                    \"family\": self._family,\n                    \"proto\": 0,\n                    \"flags\": 0,\n                }\n            ]\n\n        if not self._use_dns_cache:\n\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_start(host)\n\n            res = await self._resolver.resolve(host, port, family=self._family)\n\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_end(host)\n\n            return res\n\n        key = (host, port)\n        if key in self._cached_hosts and not self._cached_hosts.expired(key):\n            # get result early, before any await (#4014)\n            result = self._cached_hosts.next_addrs(key)\n\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_cache_hit(host)\n            return result\n\n        futures: Set[\"asyncio.Future[None]\"]\n        #\n        # If multiple connectors are resolving the same host, we wait\n        # for the first one to resolve and then use the result for all of them.\n        # We use a throttle to ensure that we only resolve the host once\n        # and then use the result for all the waiters.\n        #\n        if key in self._throttle_dns_futures:\n            # get futures early, before any await (#4014)\n            futures = self._throttle_dns_futures[key]\n            future: asyncio.Future[None] = self._loop.create_future()\n            futures.add(future)\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_cache_hit(host)\n            try:\n                await future\n            finally:\n                futures.discard(future)\n            return self._cached_hosts.next_addrs(key)\n\n        # update dict early, before any await (#4014)\n        self._throttle_dns_futures[key] = futures = set()\n        # In this case we need to create a task to ensure that we can shield\n        # the task from cancellation as cancelling this lookup should not cancel\n        # the underlying lookup or else the cancel event will get broadcast to\n        # all the waiters across all connections.\n        #\n        coro = self._resolve_host_with_throttle(key, host, port, futures, traces)\n        loop = asyncio.get_running_loop()\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send immediately\n            resolved_host_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            resolved_host_task = loop.create_task(coro)\n\n        if not resolved_host_task.done():\n            self._resolve_host_tasks.add(resolved_host_task)\n            resolved_host_task.add_done_callback(self._resolve_host_tasks.discard)\n\n        try:\n            return await asyncio.shield(resolved_host_task)\n        except asyncio.CancelledError:\n\n            def drop_exception(fut: \"asyncio.Future[List[ResolveResult]]\") -> None:\n                with suppress(Exception, asyncio.CancelledError):\n                    fut.result()\n\n            resolved_host_task.add_done_callback(drop_exception)\n            raise\n\n    async def _resolve_host_with_throttle(\n        self,\n        key: Tuple[str, int],\n        host: str,\n        port: int,\n        futures: Set[\"asyncio.Future[None]\"],\n        traces: Optional[Sequence[\"Trace\"]],\n    ) -> List[ResolveResult]:\n        \"\"\"Resolve host and set result for all waiters.\n\n        This method must be run in a task and shielded from cancellation\n        to avoid cancelling the underlying lookup.\n        \"\"\"\n        if traces:\n            for trace in traces:\n                await trace.send_dns_cache_miss(host)\n        try:\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_start(host)\n\n            addrs = await self._resolver.resolve(host, port, family=self._family)\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_end(host)\n\n            self._cached_hosts.add(key, addrs)\n            for fut in futures:\n                set_result(fut, None)\n        except BaseException as e:\n            # any DNS exception is set for the waiters to raise the same exception.\n            # This coro is always run in task that is shielded from cancellation so\n            # we should never be propagating cancellation here.\n            for fut in futures:\n                set_exception(fut, e)\n            raise\n        finally:\n            self._throttle_dns_futures.pop(key)\n\n        return self._cached_hosts.next_addrs(key)\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        \"\"\"Create connection.\n\n        Has same keyword arguments as BaseEventLoop.create_connection.\n        \"\"\"\n        if req.proxy:\n            _, proto = await self._create_proxy_connection(req, traces, timeout)\n        else:\n            _, proto = await self._create_direct_connection(req, traces, timeout)\n\n        return proto\n\n    def _get_ssl_context(self, req: ClientRequest) -> Optional[SSLContext]:\n        \"\"\"Logic to get the correct SSL context\n\n        0. if req.ssl is false, return None\n\n        1. if ssl_context is specified in req, use it\n        2. if _ssl_context is specified in self, use it\n        3. otherwise:\n            1. if verify_ssl is not specified in req, use self.ssl_context\n               (will generate a default context according to self.verify_ssl)\n            2. if verify_ssl is True in req, generate a default SSL context\n            3. if verify_ssl is False in req, generate a SSL context that\n               won't verify\n        \"\"\"\n        if not req.is_ssl():\n            return None\n\n        if ssl is None:  # pragma: no cover\n            raise RuntimeError(\"SSL is not supported.\")\n        sslcontext = req.ssl\n        if isinstance(sslcontext, ssl.SSLContext):\n            return sslcontext\n        if sslcontext is not True:\n            # not verified or fingerprinted\n            return _SSL_CONTEXT_UNVERIFIED\n        sslcontext = self._ssl\n        if isinstance(sslcontext, ssl.SSLContext):\n            return sslcontext\n        if sslcontext is not True:\n            # not verified or fingerprinted\n            return _SSL_CONTEXT_UNVERIFIED\n        return _SSL_CONTEXT_VERIFIED\n\n    def _get_fingerprint(self, req: ClientRequest) -> Optional[\"Fingerprint\"]:\n        ret = req.ssl\n        if isinstance(ret, Fingerprint):\n            return ret\n        ret = self._ssl\n        if isinstance(ret, Fingerprint):\n            return ret\n        return None\n\n    async def _wrap_create_connection(\n        self,\n        *args: Any,\n        addr_infos: List[aiohappyeyeballs.AddrInfoType],\n        req: ClientRequest,\n        timeout: \"ClientTimeout\",\n        client_error: Type[Exception] = ClientConnectorError,\n        **kwargs: Any,\n    ) -> Tuple[asyncio.Transport, ResponseHandler]:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                sock = await aiohappyeyeballs.start_connection(\n                    addr_infos=addr_infos,\n                    local_addr_infos=self._local_addr_infos,\n                    happy_eyeballs_delay=self._happy_eyeballs_delay,\n                    interleave=self._interleave,\n                    loop=self._loop,\n                )\n                return await self._loop.create_connection(*args, **kwargs, sock=sock)\n        except cert_errors as exc:\n            raise ClientConnectorCertificateError(req.connection_key, exc) from exc\n        except ssl_errors as exc:\n            raise ClientConnectorSSLError(req.connection_key, exc) from exc\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise client_error(req.connection_key, exc) from exc\n\n    async def _wrap_existing_connection(\n        self,\n        *args: Any,\n        req: ClientRequest,\n        timeout: \"ClientTimeout\",\n        client_error: Type[Exception] = ClientConnectorError,\n        **kwargs: Any,\n    ) -> Tuple[asyncio.Transport, ResponseHandler]:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                return await self._loop.create_connection(*args, **kwargs)\n        except cert_errors as exc:\n            raise ClientConnectorCertificateError(req.connection_key, exc) from exc\n        except ssl_errors as exc:\n            raise ClientConnectorSSLError(req.connection_key, exc) from exc\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise client_error(req.connection_key, exc) from exc\n\n    def _fail_on_no_start_tls(self, req: \"ClientRequest\") -> None:\n        \"\"\"Raise a :py:exc:`RuntimeError` on missing ``start_tls()``.\n\n        It is necessary for TLS-in-TLS so that it is possible to\n        send HTTPS queries through HTTPS proxies.\n\n        This doesn't affect regular HTTP requests, though.\n        \"\"\"\n        if not req.is_ssl():\n            return\n\n        proxy_url = req.proxy\n        assert proxy_url is not None\n        if proxy_url.scheme != \"https\":\n            return\n\n        self._check_loop_for_start_tls()\n\n    def _check_loop_for_start_tls(self) -> None:\n        try:\n            self._loop.start_tls\n        except AttributeError as attr_exc:\n            raise RuntimeError(\n                \"An HTTPS request is being sent through an HTTPS proxy. \"\n                \"This needs support for TLS in TLS but it is not implemented \"\n                \"in your runtime for the stdlib asyncio.\\n\\n\"\n                \"Please upgrade to Python 3.11 or higher. For more details, \"\n                \"please see:\\n\"\n                \"* https://bugs.python.org/issue37179\\n\"\n                \"* https://github.com/python/cpython/pull/28073\\n\"\n                \"* https://docs.aiohttp.org/en/stable/\"\n                \"client_advanced.html#proxy-support\\n\"\n                \"* https://github.com/aio-libs/aiohttp/discussions/6044\\n\",\n            ) from attr_exc\n\n    def _loop_supports_start_tls(self) -> bool:\n        try:\n            self._check_loop_for_start_tls()\n        except RuntimeError:\n            return False\n        else:\n            return True\n\n    def _warn_about_tls_in_tls(\n        self,\n        underlying_transport: asyncio.Transport,\n        req: ClientRequest,\n    ) -> None:\n        \"\"\"Issue a warning if the requested URL has HTTPS scheme.\"\"\"\n        if req.request_info.url.scheme != \"https\":\n            return\n\n        asyncio_supports_tls_in_tls = getattr(\n            underlying_transport,\n            \"_start_tls_compatible\",\n            False,\n        )\n\n        if asyncio_supports_tls_in_tls:\n            return\n\n        warnings.warn(\n            \"An HTTPS request is being sent through an HTTPS proxy. \"\n            \"This support for TLS in TLS is known to be disabled \"\n            \"in the stdlib asyncio (Python <3.11). This is why you'll probably see \"\n            \"an error in the log below.\\n\\n\"\n            \"It is possible to enable it via monkeypatching. \"\n            \"For more details, see:\\n\"\n            \"* https://bugs.python.org/issue37179\\n\"\n            \"* https://github.com/python/cpython/pull/28073\\n\\n\"\n            \"You can temporarily patch this as follows:\\n\"\n            \"* https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support\\n\"\n            \"* https://github.com/aio-libs/aiohttp/discussions/6044\\n\",\n            RuntimeWarning,\n            source=self,\n            # Why `4`? At least 3 of the calls in the stack originate\n            # from the methods in this class.\n            stacklevel=3,\n        )\n\n    async def _start_tls_connection(\n        self,\n        underlying_transport: asyncio.Transport,\n        req: ClientRequest,\n        timeout: \"ClientTimeout\",\n        client_error: Type[Exception] = ClientConnectorError,\n    ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:\n        \"\"\"Wrap the raw TCP transport with TLS.\"\"\"\n        tls_proto = self._factory()  # Create a brand new proto for TLS\n        sslcontext = self._get_ssl_context(req)\n        if TYPE_CHECKING:\n            # _start_tls_connection is unreachable in the current code path\n            # if sslcontext is None.\n            assert sslcontext is not None\n\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                try:\n                    tls_transport = await self._loop.start_tls(\n                        underlying_transport,\n                        tls_proto,\n                        sslcontext,\n                        server_hostname=req.server_hostname or req.host,\n                        ssl_handshake_timeout=timeout.total,\n                    )\n                except BaseException:\n                    # We need to close the underlying transport since\n                    # `start_tls()` probably failed before it had a\n                    # chance to do this:\n                    underlying_transport.close()\n                    raise\n                if isinstance(tls_transport, asyncio.Transport):\n                    fingerprint = self._get_fingerprint(req)\n                    if fingerprint:\n                        try:\n                            fingerprint.check(tls_transport)\n                        except ServerFingerprintMismatch:\n                            tls_transport.close()\n                            if not self._cleanup_closed_disabled:\n                                self._cleanup_closed_transports.append(tls_transport)\n                            raise\n        except cert_errors as exc:\n            raise ClientConnectorCertificateError(req.connection_key, exc) from exc\n        except ssl_errors as exc:\n            raise ClientConnectorSSLError(req.connection_key, exc) from exc\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise client_error(req.connection_key, exc) from exc\n        except TypeError as type_err:\n            # Example cause looks like this:\n            # TypeError: transport <asyncio.sslproto._SSLProtocolTransport\n            # object at 0x7f760615e460> is not supported by start_tls()\n\n            raise ClientConnectionError(\n                \"Cannot initialize a TLS-in-TLS connection to host \"\n                f\"{req.host!s}:{req.port:d} through an underlying connection \"\n                f\"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} \"\n                f\"[{type_err!s}]\"\n            ) from type_err\n        else:\n            if tls_transport is None:\n                msg = \"Failed to start TLS (possibly caused by closing transport)\"\n                raise client_error(req.connection_key, OSError(msg))\n            tls_proto.connection_made(\n                tls_transport\n            )  # Kick the state machine of the new TLS protocol\n\n        return tls_transport, tls_proto\n\n    def _convert_hosts_to_addr_infos(\n        self, hosts: List[ResolveResult]\n    ) -> List[aiohappyeyeballs.AddrInfoType]:\n        \"\"\"Converts the list of hosts to a list of addr_infos.\n\n        The list of hosts is the result of a DNS lookup. The list of\n        addr_infos is the result of a call to `socket.getaddrinfo()`.\n        \"\"\"\n        addr_infos: List[aiohappyeyeballs.AddrInfoType] = []\n        for hinfo in hosts:\n            host = hinfo[\"host\"]\n            is_ipv6 = \":\" in host\n            family = socket.AF_INET6 if is_ipv6 else socket.AF_INET\n            if self._family and self._family != family:\n                continue\n            addr = (host, hinfo[\"port\"], 0, 0) if is_ipv6 else (host, hinfo[\"port\"])\n            addr_infos.append(\n                (family, socket.SOCK_STREAM, socket.IPPROTO_TCP, \"\", addr)\n            )\n        return addr_infos\n\n    async def _create_direct_connection(\n        self,\n        req: ClientRequest,\n        traces: List[\"Trace\"],\n        timeout: \"ClientTimeout\",\n        *,\n        client_error: Type[Exception] = ClientConnectorError,\n    ) -> Tuple[asyncio.Transport, ResponseHandler]:\n        sslcontext = self._get_ssl_context(req)\n        fingerprint = self._get_fingerprint(req)\n\n        host = req.url.raw_host\n        assert host is not None\n        # Replace multiple trailing dots with a single one.\n        # A trailing dot is only present for fully-qualified domain names.\n        # See https://github.com/aio-libs/aiohttp/pull/7364.\n        if host.endswith(\"..\"):\n            host = host.rstrip(\".\") + \".\"\n        port = req.port\n        assert port is not None\n        try:\n            # Cancelling this lookup should not cancel the underlying lookup\n            #  or else the cancel event will get broadcast to all the waiters\n            #  across all connections.\n            hosts = await self._resolve_host(host, port, traces=traces)\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            # in case of proxy it is not ClientProxyConnectionError\n            # it is problem of resolving proxy ip itself\n            raise ClientConnectorDNSError(req.connection_key, exc) from exc\n\n        last_exc: Optional[Exception] = None\n        addr_infos = self._convert_hosts_to_addr_infos(hosts)\n        while addr_infos:\n            # Strip trailing dots, certificates contain FQDN without dots.\n            # See https://github.com/aio-libs/aiohttp/issues/3636\n            server_hostname = (\n                (req.server_hostname or host).rstrip(\".\") if sslcontext else None\n            )\n\n            try:\n                transp, proto = await self._wrap_create_connection(\n                    self._factory,\n                    timeout=timeout,\n                    ssl=sslcontext,\n                    addr_infos=addr_infos,\n                    server_hostname=server_hostname,\n                    req=req,\n                    client_error=client_error,\n                )\n            except (ClientConnectorError, asyncio.TimeoutError) as exc:\n                last_exc = exc\n                aiohappyeyeballs.pop_addr_infos_interleave(addr_infos, self._interleave)\n                continue\n\n            if req.is_ssl() and fingerprint:\n                try:\n                    fingerprint.check(transp)\n                except ServerFingerprintMismatch as exc:\n                    transp.close()\n                    if not self._cleanup_closed_disabled:\n                        self._cleanup_closed_transports.append(transp)\n                    last_exc = exc\n                    # Remove the bad peer from the list of addr_infos\n                    sock: socket.socket = transp.get_extra_info(\"socket\")\n                    bad_peer = sock.getpeername()\n                    aiohappyeyeballs.remove_addr_infos(addr_infos, bad_peer)\n                    continue\n\n            return transp, proto\n        else:\n            assert last_exc is not None\n            raise last_exc\n\n    async def _create_proxy_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:\n        self._fail_on_no_start_tls(req)\n        runtime_has_start_tls = self._loop_supports_start_tls()\n\n        headers: Dict[str, str] = {}\n        if req.proxy_headers is not None:\n            headers = req.proxy_headers  # type: ignore[assignment]\n        headers[hdrs.HOST] = req.headers[hdrs.HOST]\n\n        url = req.proxy\n        assert url is not None\n        proxy_req = ClientRequest(\n            hdrs.METH_GET,\n            url,\n            headers=headers,\n            auth=req.proxy_auth,\n            loop=self._loop,\n            ssl=req.ssl,\n        )\n\n        # create connection to proxy server\n        transport, proto = await self._create_direct_connection(\n            proxy_req, [], timeout, client_error=ClientProxyConnectionError\n        )\n\n        auth = proxy_req.headers.pop(hdrs.AUTHORIZATION, None)\n        if auth is not None:\n            if not req.is_ssl():\n                req.headers[hdrs.PROXY_AUTHORIZATION] = auth\n            else:\n                proxy_req.headers[hdrs.PROXY_AUTHORIZATION] = auth\n\n        if req.is_ssl():\n            if runtime_has_start_tls:\n                self._warn_about_tls_in_tls(transport, req)\n\n            # For HTTPS requests over HTTP proxy\n            # we must notify proxy to tunnel connection\n            # so we send CONNECT command:\n            #   CONNECT www.python.org:443 HTTP/1.1\n            #   Host: www.python.org\n            #\n            # next we must do TLS handshake and so on\n            # to do this we must wrap raw socket into secure one\n            # asyncio handles this perfectly\n            proxy_req.method = hdrs.METH_CONNECT\n            proxy_req.url = req.url\n            key = req.connection_key._replace(\n                proxy=None, proxy_auth=None, proxy_headers_hash=None\n            )\n            conn = Connection(self, key, proto, self._loop)\n            proxy_resp = await proxy_req.send(conn)\n            try:\n                protocol = conn._protocol\n                assert protocol is not None\n\n                # read_until_eof=True will ensure the connection isn't closed\n                # once the response is received and processed allowing\n                # START_TLS to work on the connection below.\n                protocol.set_response_params(\n                    read_until_eof=runtime_has_start_tls,\n                    timeout_ceil_threshold=self._timeout_ceil_threshold,\n                )\n                resp = await proxy_resp.start(conn)\n            except BaseException:\n                proxy_resp.close()\n                conn.close()\n                raise\n            else:\n                conn._protocol = None\n                try:\n                    if resp.status != 200:\n                        message = resp.reason\n                        if message is None:\n                            message = HTTPStatus(resp.status).phrase\n                        raise ClientHttpProxyError(\n                            proxy_resp.request_info,\n                            resp.history,\n                            status=resp.status,\n                            message=message,\n                            headers=resp.headers,\n                        )\n                    if not runtime_has_start_tls:\n                        rawsock = transport.get_extra_info(\"socket\", default=None)\n                        if rawsock is None:\n                            raise RuntimeError(\n                                \"Transport does not expose socket instance\"\n                            )\n                        # Duplicate the socket, so now we can close proxy transport\n                        rawsock = rawsock.dup()\n                except BaseException:\n                    # It shouldn't be closed in `finally` because it's fed to\n                    # `loop.start_tls()` and the docs say not to touch it after\n                    # passing there.\n                    transport.close()\n                    raise\n                finally:\n                    if not runtime_has_start_tls:\n                        transport.close()\n\n                if not runtime_has_start_tls:\n                    # HTTP proxy with support for upgrade to HTTPS\n                    sslcontext = self._get_ssl_context(req)\n                    return await self._wrap_existing_connection(\n                        self._factory,\n                        timeout=timeout,\n                        ssl=sslcontext,\n                        sock=rawsock,\n                        server_hostname=req.host,\n                        req=req,\n                    )\n\n                return await self._start_tls_connection(\n                    # Access the old transport for the last time before it's\n                    # closed and forgotten forever:\n                    transport,\n                    req=req,\n                    timeout=timeout,\n                )\n            finally:\n                proxy_resp.close()\n\n        return transport, proto\n\n\nclass UnixConnector(BaseConnector):\n    \"\"\"Unix socket connector.\n\n    path - Unix socket path.\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    loop - Optional event loop.\n    \"\"\"\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({\"unix\"})\n\n    def __init__(\n        self,\n        path: str,\n        force_close: bool = False,\n        keepalive_timeout: Union[object, float, None] = sentinel,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n    ) -> None:\n        super().__init__(\n            force_close=force_close,\n            keepalive_timeout=keepalive_timeout,\n            limit=limit,\n            limit_per_host=limit_per_host,\n            loop=loop,\n        )\n        self._path = path\n\n    @property\n    def path(self) -> str:\n        \"\"\"Path to unix socket.\"\"\"\n        return self._path\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                _, proto = await self._loop.create_unix_connection(\n                    self._factory, self._path\n                )\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc\n\n        return proto\n\n\nclass NamedPipeConnector(BaseConnector):\n    \"\"\"Named pipe connector.\n\n    Only supported by the proactor event loop.\n    See also: https://docs.python.org/3/library/asyncio-eventloop.html\n\n    path - Windows named pipe path.\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    loop - Optional event loop.\n    \"\"\"\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({\"npipe\"})\n\n    def __init__(\n        self,\n        path: str,\n        force_close: bool = False,\n        keepalive_timeout: Union[object, float, None] = sentinel,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n    ) -> None:\n        super().__init__(\n            force_close=force_close,\n            keepalive_timeout=keepalive_timeout,\n            limit=limit,\n            limit_per_host=limit_per_host,\n            loop=loop,\n        )\n        if not isinstance(\n            self._loop, asyncio.ProactorEventLoop  # type: ignore[attr-defined]\n        ):\n            raise RuntimeError(\n                \"Named Pipes only available in proactor loop under windows\"\n            )\n        self._path = path\n\n    @property\n    def path(self) -> str:\n        \"\"\"Path to the named pipe.\"\"\"\n        return self._path\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                _, proto = await self._loop.create_pipe_connection(  # type: ignore[attr-defined]\n                    self._factory, self._path\n                )\n                # the drain is required so that the connection_made is called\n                # and transport is set otherwise it is not set before the\n                # `assert conn.transport is not None`\n                # in client.py's _request method\n                await asyncio.sleep(0)\n                # other option is to manually set transport like\n                # `proto.transport = trans`\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise ClientConnectorError(req.connection_key, exc) from exc\n\n        return cast(ResponseHandler, proto)\n",
            "header": {
                "file": {
                    "path": "aiohttp/connector.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "03147cb3",
                "new_commit_hash": "282d0a97",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/aiohttp/connector.py"
            },
            "plus_file": {
                "path": "b/aiohttp/connector.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 186,
                            "length": 9
                        },
                        "new_range": {
                            "start": 186,
                            "length": 7
                        },
                        "section": "class Connection:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self._notify_release()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        if self._protocol is not None:",
                                "type": "context"
                            },
                            {
                                "content": "            self._connector._release(",
                                "type": "deleted"
                            },
                            {
                                "content": "                self._key, self._protocol, should_close=self._protocol.should_close",
                                "type": "deleted"
                            },
                            {
                                "content": "            )",
                                "type": "deleted"
                            },
                            {
                                "content": "            self._connector._release(self._key, self._protocol)",
                                "type": "added"
                            },
                            {
                                "content": "            self._protocol = None",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @property",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/connector.py",
                            "type": "method",
                            "name": "Connection.release",
                            "content": "class Connection:\n\n    _source_traceback = None\n\n    def __init__(\n        self,\n        connector: \"BaseConnector\",\n        key: \"ConnectionKey\",\n        protocol: ResponseHandler,\n        loop: asyncio.AbstractEventLoop,\n    ) -> None:\n        self._key = key\n        self._connector = connector\n        self._loop = loop\n        self._protocol: Optional[ResponseHandler] = protocol\n        self._callbacks: List[Callable[[], None]] = []\n\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n    def __repr__(self) -> str:\n        return f\"Connection<{self._key}>\"\n\n    def __del__(self, _warnings: Any = warnings) -> None:\n        if self._protocol is not None:\n            kwargs = {\"source\": self}\n            _warnings.warn(f\"Unclosed connection {self!r}\", ResourceWarning, **kwargs)\n            if self._loop.is_closed():\n                return\n\n            self._connector._release(self._key, self._protocol, should_close=True)\n\n            context = {\"client_connection\": self, \"message\": \"Unclosed connection\"}\n            if self._source_traceback is not None:\n                context[\"source_traceback\"] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def __bool__(self) -> Literal[True]:\n        \"\"\"Force subclasses to not be falsy, to make checks simpler.\"\"\"\n        return True\n\n    @property\n    def loop(self) -> asyncio.AbstractEventLoop:\n        warnings.warn(\n            \"connector.loop property is deprecated\", DeprecationWarning, stacklevel=2\n        )\n        return self._loop\n\n    @property\n    def transport(self) -> Optional[asyncio.Transport]:\n        if self._protocol is None:\n            return None\n        return self._protocol.transport\n\n    @property\n    def protocol(self) -> Optional[ResponseHandler]:\n        return self._protocol\n\n    def add_callback(self, callback: Callable[[], None]) -> None:\n        if callback is not None:\n            self._callbacks.append(callback)\n\n    def _notify_release(self) -> None:\n        callbacks, self._callbacks = self._callbacks[:], []\n\n        for cb in callbacks:\n            with suppress(Exception):\n                cb()\n\n    def close(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(self._key, self._protocol, should_close=True)\n            self._protocol = None\n\n    def release(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(\n                self._key, self._protocol, should_close=self._protocol.should_close\n            )\n            self._protocol = None\n\n    @property\n    def closed(self) -> bool:\n        return self._protocol is None or not self._protocol.is_connected()",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 185,
                            "end_lineno": 192,
                            "parent": {
                                "file_name": "aiohttp/connector.py",
                                "type": "class",
                                "name": "Connection",
                                "content": "class Connection:\n\n    _source_traceback = None\n\n    def __init__(\n        self,\n        connector: \"BaseConnector\",\n        key: \"ConnectionKey\",\n        protocol: ResponseHandler,\n        loop: asyncio.AbstractEventLoop,\n    ) -> None:\n        self._key = key\n        self._connector = connector\n        self._loop = loop\n        self._protocol: Optional[ResponseHandler] = protocol\n        self._callbacks: List[Callable[[], None]] = []\n\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n    def __repr__(self) -> str:\n        return f\"Connection<{self._key}>\"\n\n    def __del__(self, _warnings: Any = warnings) -> None:\n        if self._protocol is not None:\n            kwargs = {\"source\": self}\n            _warnings.warn(f\"Unclosed connection {self!r}\", ResourceWarning, **kwargs)\n            if self._loop.is_closed():\n                return\n\n            self._connector._release(self._key, self._protocol, should_close=True)\n\n            context = {\"client_connection\": self, \"message\": \"Unclosed connection\"}\n            if self._source_traceback is not None:\n                context[\"source_traceback\"] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def __bool__(self) -> Literal[True]:\n        \"\"\"Force subclasses to not be falsy, to make checks simpler.\"\"\"\n        return True\n\n    @property\n    def loop(self) -> asyncio.AbstractEventLoop:\n        warnings.warn(\n            \"connector.loop property is deprecated\", DeprecationWarning, stacklevel=2\n        )\n        return self._loop\n\n    @property\n    def transport(self) -> Optional[asyncio.Transport]:\n        if self._protocol is None:\n            return None\n        return self._protocol.transport\n\n    @property\n    def protocol(self) -> Optional[ResponseHandler]:\n        return self._protocol\n\n    def add_callback(self, callback: Callable[[], None]) -> None:\n        if callback is not None:\n            self._callbacks.append(callback)\n\n    def _notify_release(self) -> None:\n        callbacks, self._callbacks = self._callbacks[:], []\n\n        for cb in callbacks:\n            with suppress(Exception):\n                cb()\n\n    def close(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(self._key, self._protocol, should_close=True)\n            self._protocol = None\n\n    def release(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(\n                self._key, self._protocol, should_close=self._protocol.should_close\n            )\n            self._protocol = None\n\n    @property\n    def closed(self) -> bool:\n        return self._protocol is None or not self._protocol.is_connected()",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 109,
                                "end_lineno": 196,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "aiohttp/connector.py",
                            "type": "class",
                            "name": "Connection",
                            "content": "class Connection:\n\n    _source_traceback = None\n\n    def __init__(\n        self,\n        connector: \"BaseConnector\",\n        key: \"ConnectionKey\",\n        protocol: ResponseHandler,\n        loop: asyncio.AbstractEventLoop,\n    ) -> None:\n        self._key = key\n        self._connector = connector\n        self._loop = loop\n        self._protocol: Optional[ResponseHandler] = protocol\n        self._callbacks: List[Callable[[], None]] = []\n\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n    def __repr__(self) -> str:\n        return f\"Connection<{self._key}>\"\n\n    def __del__(self, _warnings: Any = warnings) -> None:\n        if self._protocol is not None:\n            kwargs = {\"source\": self}\n            _warnings.warn(f\"Unclosed connection {self!r}\", ResourceWarning, **kwargs)\n            if self._loop.is_closed():\n                return\n\n            self._connector._release(self._key, self._protocol, should_close=True)\n\n            context = {\"client_connection\": self, \"message\": \"Unclosed connection\"}\n            if self._source_traceback is not None:\n                context[\"source_traceback\"] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def __bool__(self) -> Literal[True]:\n        \"\"\"Force subclasses to not be falsy, to make checks simpler.\"\"\"\n        return True\n\n    @property\n    def loop(self) -> asyncio.AbstractEventLoop:\n        warnings.warn(\n            \"connector.loop property is deprecated\", DeprecationWarning, stacklevel=2\n        )\n        return self._loop\n\n    @property\n    def transport(self) -> Optional[asyncio.Transport]:\n        if self._protocol is None:\n            return None\n        return self._protocol.transport\n\n    @property\n    def protocol(self) -> Optional[ResponseHandler]:\n        return self._protocol\n\n    def add_callback(self, callback: Callable[[], None]) -> None:\n        if callback is not None:\n            self._callbacks.append(callback)\n\n    def _notify_release(self) -> None:\n        callbacks, self._callbacks = self._callbacks[:], []\n\n        for cb in callbacks:\n            with suppress(Exception):\n                cb()\n\n    def close(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(self._key, self._protocol, should_close=True)\n            self._protocol = None\n\n    def release(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(\n                self._key, self._protocol, should_close=self._protocol.should_close\n            )\n            self._protocol = None\n\n    @property\n    def closed(self) -> bool:\n        return self._protocol is None or not self._protocol.is_connected()",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 109,
                            "end_lineno": 196,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import gc\nfrom unittest import mock\n\nimport pytest\n\nfrom aiohttp.connector import Connection\n\n\n@pytest.fixture\ndef key():\n    return object()\n\n\n@pytest.fixture\ndef loop():\n    return mock.Mock()\n\n\n@pytest.fixture\ndef connector():\n    return mock.Mock()\n\n\n@pytest.fixture\ndef protocol():\n    return mock.Mock(should_close=False)\n\n\ndef test_ctor(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    with pytest.warns(DeprecationWarning):\n        assert conn.loop is loop\n    assert conn.protocol is protocol\n    conn.close()\n\n\ndef test_callbacks_on_close(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    notified = False\n\n    def cb():\n        nonlocal notified\n        notified = True\n\n    conn.add_callback(cb)\n    conn.close()\n    assert notified\n\n\ndef test_callbacks_on_release(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    notified = False\n\n    def cb():\n        nonlocal notified\n        notified = True\n\n    conn.add_callback(cb)\n    conn.release()\n    assert notified\n\n\ndef test_callbacks_exception(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    notified = False\n\n    def cb1():\n        raise Exception\n\n    def cb2():\n        nonlocal notified\n        notified = True\n\n    conn.add_callback(cb1)\n    conn.add_callback(cb2)\n    conn.close()\n    assert notified\n\n\ndef test_del(connector, key, protocol, loop) -> None:\n    loop.is_closed.return_value = False\n    conn = Connection(connector, key, protocol, loop)\n    exc_handler = mock.Mock()\n    loop.set_exception_handler(exc_handler)\n\n    with pytest.warns(ResourceWarning):\n        del conn\n        gc.collect()\n\n    connector._release.assert_called_with(key, protocol, should_close=True)\n    msg = {\n        \"client_connection\": mock.ANY,  # conn was deleted\n        \"message\": \"Unclosed connection\",\n    }\n    if loop.get_debug():\n        msg[\"source_traceback\"] = mock.ANY\n    loop.call_exception_handler.assert_called_with(msg)\n\n\ndef test_close(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    assert not conn.closed\n    conn.close()\n    assert conn._protocol is None\n    connector._release.assert_called_with(key, protocol, should_close=True)\n    assert conn.closed\n\n\ndef test_release(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    assert not conn.closed\n    conn.release()\n    assert not protocol.transport.close.called\n    assert conn._protocol is None\n    connector._release.assert_called_with(key, protocol, should_close=False)\n    assert conn.closed\n\n\ndef test_release_proto_should_close(connector, key, protocol, loop) -> None:\n    protocol.should_close = True\n    conn = Connection(connector, key, protocol, loop)\n    assert not conn.closed\n    conn.release()\n    assert not protocol.transport.close.called\n    assert conn._protocol is None\n    connector._release.assert_called_with(key, protocol, should_close=True)\n    assert conn.closed\n\n\ndef test_release_released(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    conn.release()\n    connector._release.reset_mock()\n    conn.release()\n    assert not protocol.transport.close.called\n    assert conn._protocol is None\n    assert not connector._release.called\n",
            "new_file_content": "import gc\nfrom unittest import mock\n\nimport pytest\n\nfrom aiohttp.connector import Connection\n\n\n@pytest.fixture\ndef key():\n    return object()\n\n\n@pytest.fixture\ndef loop():\n    return mock.Mock()\n\n\n@pytest.fixture\ndef connector():\n    return mock.Mock()\n\n\n@pytest.fixture\ndef protocol():\n    return mock.Mock(should_close=False)\n\n\ndef test_ctor(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    with pytest.warns(DeprecationWarning):\n        assert conn.loop is loop\n    assert conn.protocol is protocol\n    conn.close()\n\n\ndef test_callbacks_on_close(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    notified = False\n\n    def cb():\n        nonlocal notified\n        notified = True\n\n    conn.add_callback(cb)\n    conn.close()\n    assert notified\n\n\ndef test_callbacks_on_release(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    notified = False\n\n    def cb():\n        nonlocal notified\n        notified = True\n\n    conn.add_callback(cb)\n    conn.release()\n    assert notified\n\n\ndef test_callbacks_exception(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    notified = False\n\n    def cb1():\n        raise Exception\n\n    def cb2():\n        nonlocal notified\n        notified = True\n\n    conn.add_callback(cb1)\n    conn.add_callback(cb2)\n    conn.close()\n    assert notified\n\n\ndef test_del(connector, key, protocol, loop) -> None:\n    loop.is_closed.return_value = False\n    conn = Connection(connector, key, protocol, loop)\n    exc_handler = mock.Mock()\n    loop.set_exception_handler(exc_handler)\n\n    with pytest.warns(ResourceWarning):\n        del conn\n        gc.collect()\n\n    connector._release.assert_called_with(key, protocol, should_close=True)\n    msg = {\n        \"client_connection\": mock.ANY,  # conn was deleted\n        \"message\": \"Unclosed connection\",\n    }\n    if loop.get_debug():\n        msg[\"source_traceback\"] = mock.ANY\n    loop.call_exception_handler.assert_called_with(msg)\n\n\ndef test_close(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    assert not conn.closed\n    conn.close()\n    assert conn._protocol is None\n    connector._release.assert_called_with(key, protocol, should_close=True)\n    assert conn.closed\n\n\ndef test_release(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    assert not conn.closed\n    conn.release()\n    assert not protocol.transport.close.called\n    assert conn._protocol is None\n    connector._release.assert_called_with(key, protocol)\n    assert conn.closed\n\n\ndef test_release_proto_should_close(connector, key, protocol, loop) -> None:\n    protocol.should_close = True\n    conn = Connection(connector, key, protocol, loop)\n    assert not conn.closed\n    conn.release()\n    assert not protocol.transport.close.called\n    assert conn._protocol is None\n    connector._release.assert_called_with(key, protocol)\n    assert conn.closed\n\n\ndef test_release_released(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    conn.release()\n    connector._release.reset_mock()\n    conn.release()\n    assert not protocol.transport.close.called\n    assert conn._protocol is None\n    assert not connector._release.called\n",
            "header": {
                "file": {
                    "path": "tests/test_client_connection.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "5a0739b6",
                "new_commit_hash": "1be3f019",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tests/test_client_connection.py"
            },
            "plus_file": {
                "path": "b/tests/test_client_connection.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 112,
                            "length": 7
                        },
                        "new_range": {
                            "start": 112,
                            "length": 7
                        },
                        "section": "def test_release(connector, key, protocol, loop) -> None:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    conn.release()",
                                "type": "context"
                            },
                            {
                                "content": "    assert not protocol.transport.close.called",
                                "type": "context"
                            },
                            {
                                "content": "    assert conn._protocol is None",
                                "type": "context"
                            },
                            {
                                "content": "    connector._release.assert_called_with(key, protocol, should_close=False)",
                                "type": "deleted"
                            },
                            {
                                "content": "    connector._release.assert_called_with(key, protocol)",
                                "type": "added"
                            },
                            {
                                "content": "    assert conn.closed",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_client_connection.py",
                            "type": "function",
                            "name": "test_release",
                            "content": "def test_release(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    assert not conn.closed\n    conn.release()\n    assert not protocol.transport.close.called\n    assert conn._protocol is None\n    connector._release.assert_called_with(key, protocol, should_close=False)\n    assert conn.closed",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 109,
                            "end_lineno": 116,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 123,
                            "length": 7
                        },
                        "new_range": {
                            "start": 123,
                            "length": 7
                        },
                        "section": "def test_release_proto_should_close(connector, key, protocol, loop) -> None:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    conn.release()",
                                "type": "context"
                            },
                            {
                                "content": "    assert not protocol.transport.close.called",
                                "type": "context"
                            },
                            {
                                "content": "    assert conn._protocol is None",
                                "type": "context"
                            },
                            {
                                "content": "    connector._release.assert_called_with(key, protocol, should_close=True)",
                                "type": "deleted"
                            },
                            {
                                "content": "    connector._release.assert_called_with(key, protocol)",
                                "type": "added"
                            },
                            {
                                "content": "    assert conn.closed",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_client_connection.py",
                            "type": "function",
                            "name": "test_release_proto_should_close",
                            "content": "def test_release_proto_should_close(connector, key, protocol, loop) -> None:\n    protocol.should_close = True\n    conn = Connection(connector, key, protocol, loop)\n    assert not conn.closed\n    conn.release()\n    assert not protocol.transport.close.called\n    assert conn._protocol is None\n    connector._release.assert_called_with(key, protocol, should_close=True)\n    assert conn.closed",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 119,
                            "end_lineno": 127,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "d5bbb80195513268c604a908c31870db6b49310c^",
    "new_commit_hash": "d5bbb80195513268c604a908c31870db6b49310c",
    "commit_message": "[PR #9710/b40265e backport][3.11] Remove redundant `protocol.should_close` check in `Connection._release` (#9712)",
    "commit_date": "2024-11-07T22:03:31Z",
    "metadata": {}
}
{
    "repo_name": "aiohttp",
    "new_commit_hash": "d5bbb80195513268c604a908c31870db6b49310c",
    "test_file_codes": [
        "import gc\nfrom unittest import mock\n\nimport pytest\n\nfrom aiohttp.connector import Connection\n\n\n@pytest.fixture\ndef key():\n    return object()\n\n\n@pytest.fixture\ndef loop():\n    return mock.Mock()\n\n\n@pytest.fixture\ndef connector():\n    return mock.Mock()\n\n\n@pytest.fixture\ndef protocol():\n    return mock.Mock(should_close=False)\n\n\ndef test_ctor(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    with pytest.warns(DeprecationWarning):\n        assert conn.loop is loop\n    assert conn.protocol is protocol\n    conn.close()\n\n\ndef test_callbacks_on_close(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    notified = False\n\n    def cb():\n        nonlocal notified\n        notified = True\n\n    conn.add_callback(cb)\n    conn.close()\n    assert notified\n\n\ndef test_callbacks_on_release(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    notified = False\n\n    def cb():\n        nonlocal notified\n        notified = True\n\n    conn.add_callback(cb)\n    conn.release()\n    assert notified\n\n\ndef test_callbacks_exception(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    notified = False\n\n    def cb1():\n        raise Exception\n\n    def cb2():\n        nonlocal notified\n        notified = True\n\n    conn.add_callback(cb1)\n    conn.add_callback(cb2)\n    conn.close()\n    assert notified\n\n\ndef test_del(connector, key, protocol, loop) -> None:\n    loop.is_closed.return_value = False\n    conn = Connection(connector, key, protocol, loop)\n    exc_handler = mock.Mock()\n    loop.set_exception_handler(exc_handler)\n\n    with pytest.warns(ResourceWarning):\n        del conn\n        gc.collect()\n\n    connector._release.assert_called_with(key, protocol, should_close=True)\n    msg = {\n        \"client_connection\": mock.ANY,  # conn was deleted\n        \"message\": \"Unclosed connection\",\n    }\n    if loop.get_debug():\n        msg[\"source_traceback\"] = mock.ANY\n    loop.call_exception_handler.assert_called_with(msg)\n\n\ndef test_close(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    assert not conn.closed\n    conn.close()\n    assert conn._protocol is None\n    connector._release.assert_called_with(key, protocol, should_close=True)\n    assert conn.closed\n\n\ndef test_release(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    assert not conn.closed\n    conn.release()\n    assert not protocol.transport.close.called\n    assert conn._protocol is None\n    connector._release.assert_called_with(key, protocol)\n    assert conn.closed\n\n\ndef test_release_proto_should_close(connector, key, protocol, loop) -> None:\n    protocol.should_close = True\n    conn = Connection(connector, key, protocol, loop)\n    assert not conn.closed\n    conn.release()\n    assert not protocol.transport.close.called\n    assert conn._protocol is None\n    connector._release.assert_called_with(key, protocol)\n    assert conn.closed\n\n\ndef test_release_released(connector, key, protocol, loop) -> None:\n    conn = Connection(connector, key, protocol, loop)\n    conn.release()\n    connector._release.reset_mock()\n    conn.release()\n    assert not protocol.transport.close.called\n    assert conn._protocol is None\n    assert not connector._release.called\n",
        "import asyncio\nimport base64\nimport os\nimport socket\nimport ssl\nimport sys\nfrom hashlib import md5, sha1, sha256\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\nfrom typing import Any\nfrom unittest import mock\nfrom uuid import uuid4\n\nimport pytest\n\nfrom aiohttp.client_proto import ResponseHandler\nfrom aiohttp.http import WS_KEY\nfrom aiohttp.test_utils import loop_context\n\ntry:\n    import trustme\n\n    # Check if the CA is available in runtime, MacOS on Py3.10 fails somehow\n    trustme.CA()\n\n    TRUSTME: bool = True\nexcept ImportError:\n    TRUSTME = False\n\npytest_plugins = [\"aiohttp.pytest_plugin\", \"pytester\"]\n\nIS_HPUX = sys.platform.startswith(\"hp-ux\")\nIS_LINUX = sys.platform.startswith(\"linux\")\n\n\n@pytest.fixture\ndef tls_certificate_authority():\n    if not TRUSTME:\n        pytest.xfail(\"trustme is not supported\")\n    return trustme.CA()\n\n\n@pytest.fixture\ndef tls_certificate(tls_certificate_authority):\n    return tls_certificate_authority.issue_cert(\n        \"localhost\",\n        \"xn--prklad-4va.localhost\",\n        \"127.0.0.1\",\n        \"::1\",\n    )\n\n\n@pytest.fixture\ndef ssl_ctx(tls_certificate):\n    ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n    tls_certificate.configure_cert(ssl_ctx)\n    return ssl_ctx\n\n\n@pytest.fixture\ndef client_ssl_ctx(tls_certificate_authority):\n    ssl_ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)\n    tls_certificate_authority.configure_trust(ssl_ctx)\n    return ssl_ctx\n\n\n@pytest.fixture\ndef tls_ca_certificate_pem_path(tls_certificate_authority):\n    with tls_certificate_authority.cert_pem.tempfile() as ca_cert_pem:\n        yield ca_cert_pem\n\n\n@pytest.fixture\ndef tls_certificate_pem_path(tls_certificate):\n    with tls_certificate.private_key_and_cert_chain_pem.tempfile() as cert_pem:\n        yield cert_pem\n\n\n@pytest.fixture\ndef tls_certificate_pem_bytes(tls_certificate):\n    return tls_certificate.cert_chain_pems[0].bytes()\n\n\n@pytest.fixture\ndef tls_certificate_fingerprint_sha256(tls_certificate_pem_bytes):\n    tls_cert_der = ssl.PEM_cert_to_DER_cert(tls_certificate_pem_bytes.decode())\n    return sha256(tls_cert_der).digest()\n\n\n@pytest.fixture\ndef unix_sockname(tmp_path, tmp_path_factory):\n    \"\"\"Generate an fs path to the UNIX domain socket for testing.\n\n    N.B. Different OS kernels have different fs path length limitations\n    for it. For Linux, it's 108, for HP-UX it's 92 (or higher) depending\n    on its version. For for most of the BSDs (Open, Free, macOS) it's\n    mostly 104 but sometimes it can be down to 100.\n\n    Ref: https://github.com/aio-libs/aiohttp/issues/3572\n    \"\"\"\n    if not hasattr(socket, \"AF_UNIX\"):\n        pytest.skip(\"requires UNIX sockets\")\n\n    max_sock_len = 92 if IS_HPUX else 108 if IS_LINUX else 100\n    \"\"\"Amount of bytes allocated for the UNIX socket path by OS kernel.\n\n    Ref: https://unix.stackexchange.com/a/367012/27133\n    \"\"\"\n\n    sock_file_name = \"unix.sock\"\n    unique_prefix = f\"{uuid4()!s}-\"\n    unique_prefix_len = len(unique_prefix.encode())\n\n    root_tmp_dir = Path(\"/tmp\").resolve()\n    os_tmp_dir = Path(os.getenv(\"TMPDIR\", \"/tmp\")).resolve()\n    original_base_tmp_path = Path(\n        str(tmp_path_factory.getbasetemp()),\n    ).resolve()\n\n    original_base_tmp_path_hash = md5(\n        str(original_base_tmp_path).encode(),\n    ).hexdigest()\n\n    def make_tmp_dir(base_tmp_dir):\n        return TemporaryDirectory(\n            dir=str(base_tmp_dir),\n            prefix=\"pt-\",\n            suffix=f\"-{original_base_tmp_path_hash!s}\",\n        )\n\n    def assert_sock_fits(sock_path):\n        sock_path_len = len(sock_path.encode())\n        # exit-check to verify that it's correct and simplify debugging\n        # in the future\n        assert sock_path_len <= max_sock_len, (\n            \"Suggested UNIX socket ({sock_path}) is {sock_path_len} bytes \"\n            \"long but the current kernel only has {max_sock_len} bytes \"\n            \"allocated to hold it so it must be shorter. \"\n            \"See https://github.com/aio-libs/aiohttp/issues/3572 \"\n            \"for more info.\"\n        ).format_map(locals())\n\n    paths = original_base_tmp_path, os_tmp_dir, root_tmp_dir\n    unique_paths = [p for n, p in enumerate(paths) if p not in paths[:n]]\n    paths_num = len(unique_paths)\n\n    for num, tmp_dir_path in enumerate(paths, 1):\n        with make_tmp_dir(tmp_dir_path) as tmpd:\n            tmpd = Path(tmpd).resolve()\n            sock_path = str(tmpd / sock_file_name)\n            sock_path_len = len(sock_path.encode())\n\n            if num >= paths_num:\n                # exit-check to verify that it's correct and simplify\n                # debugging in the future\n                assert_sock_fits(sock_path)\n\n            if sock_path_len <= max_sock_len:\n                if max_sock_len - sock_path_len >= unique_prefix_len:\n                    # If we're lucky to have extra space in the path,\n                    # let's also make it more unique\n                    sock_path = str(tmpd / \"\".join((unique_prefix, sock_file_name)))\n                    # Double-checking it:\n                    assert_sock_fits(sock_path)\n                yield sock_path\n                return\n\n\n@pytest.fixture\ndef pipe_name():\n    name = rf\"\\\\.\\pipe\\{uuid4().hex}\"\n    return name\n\n\n@pytest.fixture\ndef create_mocked_conn(loop: Any):\n    def _proto_factory(conn_closing_result=None, **kwargs):\n        proto = mock.create_autospec(ResponseHandler, **kwargs)\n        proto.closed = loop.create_future()\n        proto.closed.set_result(conn_closing_result)\n        return proto\n\n    yield _proto_factory\n\n\n@pytest.fixture\ndef selector_loop():\n    policy = asyncio.WindowsSelectorEventLoopPolicy()\n    asyncio.set_event_loop_policy(policy)\n\n    with loop_context(policy.new_event_loop) as _loop:\n        asyncio.set_event_loop(_loop)\n        yield _loop\n\n\n@pytest.fixture\ndef netrc_contents(\n    tmp_path: Path,\n    monkeypatch: pytest.MonkeyPatch,\n    request: pytest.FixtureRequest,\n):\n    \"\"\"\n    Prepare :file:`.netrc` with given contents.\n\n    Monkey-patches :envvar:`NETRC` to point to created file.\n    \"\"\"\n    netrc_contents = getattr(request, \"param\", None)\n\n    netrc_file_path = tmp_path / \".netrc\"\n    if netrc_contents is not None:\n        netrc_file_path.write_text(netrc_contents)\n\n    monkeypatch.setenv(\"NETRC\", str(netrc_file_path))\n\n    return netrc_file_path\n\n\n@pytest.fixture\ndef start_connection():\n    with mock.patch(\n        \"aiohttp.connector.aiohappyeyeballs.start_connection\",\n        autospec=True,\n        spec_set=True,\n    ) as start_connection_mock:\n        yield start_connection_mock\n\n\n@pytest.fixture\ndef key_data():\n    return os.urandom(16)\n\n\n@pytest.fixture\ndef key(key_data: Any):\n    return base64.b64encode(key_data)\n\n\n@pytest.fixture\ndef ws_key(key: Any):\n    return base64.b64encode(sha1(key + WS_KEY).digest()).decode()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "conftest.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "re-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/requirements/cython.txt\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/tools/gen.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/hdrs.py\n./tools/gen.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_http_parser.pyx\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_http_writer.pyx\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_cparser.pxd\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_find_header.pxd\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_websocket/mask.pyx\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_websocket/mask.pxd\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_websocket/reader_c.pxd\ncython -3 -o aiohttp/_http_parser.c aiohttp/_http_parser.pyx -I aiohttp -Werror\ncython -3 -o aiohttp/_http_writer.c aiohttp/_http_writer.pyx -I aiohttp -Werror\ncython -3 -o aiohttp/_websocket/mask.c aiohttp/_websocket/mask.pyx -I aiohttp -Werror\ncd vendor/llhttp; npm ci\n\n> llhttp@9.2.1 prepare\n> npm run clean && npm run build-ts\n\n\n> llhttp@9.2.1 clean\n> rm -rf lib && rm -rf test/tmp\n\n\n> llhttp@9.2.1 build-ts\n> tsc\n\n\nadded 213 packages, and audited 214 packages in 5s\n\n41 packages are looking for funding\n  run `npm fund` for details\n\n5 vulnerabilities (3 moderate, 2 high)\n\nTo address issues that do not require attention, run:\n  npm audit fix\n\nSome issues need review, and may require choosing\na different dependency.\n\nRun `npm audit` for details.\nmake -C vendor/llhttp generate\nmake[1]: Entering directory '/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/vendor/llhttp'\nnpx ts-node bin/generate.ts\nmake[1]: Leaving directory '/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/vendor/llhttp'\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/__init__.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/abc.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/base_protocol.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/client.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/client_exceptions.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/client_proto.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/client_reqrep.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/client_ws.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/compression_utils.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/connector.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/cookiejar.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/formdata.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/helpers.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/http.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/http_exceptions.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/http_parser.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/http_websocket.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/http_writer.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/log.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/multipart.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/payload.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/payload_streamer.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/pytest_plugin.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/resolver.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/streams.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/tcp_helpers.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/test_utils.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/tracing.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/typedefs.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_app.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_exceptions.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_fileresponse.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_log.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_middlewares.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_protocol.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_request.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_response.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_routedef.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_runner.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_server.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_urldispatcher.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/web_ws.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/worker.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_websocket/__init__.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_websocket/helpers.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_websocket/models.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_websocket/reader.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_websocket/reader_c.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_websocket/reader_py.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/aiohttp/_websocket/writer.py\nuv pip install -e . -c requirements/runtime-deps.txt\n",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 40ms\nPrepared 1 package in 0.35ms\nInstalled 1 package in 18ms\n + pip==24.3.1\nResolved 3 packages in 14ms\nInstalled 3 packages in 18ms\n + cython==3.0.11\n + multidict==6.1.0\n + typing-extensions==4.12.2\nResolved 97 packages in 76ms\nInstalled 94 packages in 262ms\n + aiodns==3.2.0\n + aiohappyeyeballs==2.4.3\n + aiohttp-theme==0.1.7\n + aiosignal==1.3.1\n + alabaster==0.7.13\n + annotated-types==0.7.0\n + async-timeout==4.0.3\n + attrs==24.2.0\n + babel==2.16.0\n + brotli==1.1.0\n + build==1.2.2.post1\n + certifi==2024.8.30\n + cffi==1.17.1\n + cfgv==3.4.0\n + charset-normalizer==3.4.0\n + cherry-picker==2.2.0\n + click==8.1.7\n + coverage==7.6.1\n + cryptography==43.0.3\n + distlib==0.3.9\n + docutils==0.20.1\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + freezegun==1.5.1\n + frozenlist==1.5.0\n + gidgethub==5.3.0\n + gunicorn==23.0.0\n + identify==2.6.1\n + idna==3.4\n + imagesize==1.4.1\n + importlib-metadata==8.5.0\n + importlib-resources==6.4.5\n + incremental==24.7.2\n + iniconfig==2.0.0\n + jinja2==3.1.4\n + markdown-it-py==3.0.0\n + markupsafe==2.1.5\n + mdurl==0.1.2\n + mypy==1.11.2\n + mypy-extensions==1.0.0\n + nodeenv==1.9.1\n + packaging==24.1\n + pip-tools==7.4.1\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pre-commit==3.5.0\n + propcache==0.2.0\n + proxy-py==2.4.9\n + pycares==4.4.0\n + pycparser==2.22\n + pydantic==2.9.2\n + pydantic-core==2.23.4\n + pygments==2.18.0\n + pyjwt==2.8.0\n + pyproject-hooks==1.2.0\n + pytest==8.3.3\n + pytest-codspeed==3.0.0\n + pytest-cov==5.0.0\n + pytest-mock==3.14.0\n + python-dateutil==2.9.0.post0\n + python-on-whales==0.73.0\n + pyyaml==6.0.2\n + re-assert==1.1.0\n + regex==2024.9.11\n + requests==2.32.3\n + rich==13.9.3\n + setuptools==75.2.0\n + setuptools-git==1.2\n + shellingham==1.5.4\n + six==1.16.0\n + slotscheck==0.19.1\n + snowballstemmer==2.2.0\n + sphinx==7.1.2\n + sphinxcontrib-applehelp==1.0.4\n + sphinxcontrib-devhelp==1.0.2\n + sphinxcontrib-htmlhelp==2.0.1\n + sphinxcontrib-jsmath==1.0.1\n + sphinxcontrib-qthelp==1.0.3\n + sphinxcontrib-serializinghtml==1.1.5\n + sphinxcontrib-towncrier==0.4.0a0\n + tomli==2.0.2\n + towncrier==23.11.0\n + tqdm==4.66.5\n + trustme==1.1.0\n + typer==0.12.5\n + uritemplate==4.1.1\n + urllib3==2.2.3\n + uvloop==0.21.0\n + valkey==6.0.2\n + virtualenv==20.27.0\n + wait-for-it==2.2.2\n + wheel==0.44.0\n + yarl==1.17.1\n + zipp==3.20.2\nResolved 11 packages in 1.72s\n  × Failed to build `aiohttp @ file:///home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c`\n  ├─▶ The build backend returned an error\n  ╰─▶ Call to `setuptools.build_meta.build_editable` failed (exit status: 1)\n\n      [stdout]\n      running editable_wheel\n      creating /home/gcpuser/.cache/uv/builds-v0/.tmpnUUJJl/.tmp-ks579gd_/aiohttp.egg-info\n      writing /home/gcpuser/.cache/uv/builds-v0/.tmpnUUJJl/.tmp-ks579gd_/aiohttp.egg-info/PKG-INFO\n      writing dependency_links to /home/gcpuser/.cache/uv/builds-v0/.tmpnUUJJl/.tmp-ks579gd_/aiohttp.egg-info/dependency_links.txt\n      writing requirements to /home/gcpuser/.cache/uv/builds-v0/.tmpnUUJJl/.tmp-ks579gd_/aiohttp.egg-info/requires.txt\n      writing top-level names to /home/gcpuser/.cache/uv/builds-v0/.tmpnUUJJl/.tmp-ks579gd_/aiohttp.egg-info/top_level.txt\n      writing manifest file '/home/gcpuser/.cache/uv/builds-v0/.tmpnUUJJl/.tmp-ks579gd_/aiohttp.egg-info/SOURCES.txt'\n      reading manifest file '/home/gcpuser/.cache/uv/builds-v0/.tmpnUUJJl/.tmp-ks579gd_/aiohttp.egg-info/SOURCES.txt'\n      reading manifest template 'MANIFEST.in'\n      adding license file 'LICENSE.txt'\n      writing manifest file '/home/gcpuser/.cache/uv/builds-v0/.tmpnUUJJl/.tmp-ks579gd_/aiohttp.egg-info/SOURCES.txt'\n      creating '/home/gcpuser/.cache/uv/builds-v0/.tmpnUUJJl/.tmp-ks579gd_/aiohttp-3.11.0b3.dist-info'\n      creating /home/gcpuser/.cache/uv/builds-v0/.tmpnUUJJl/.tmp-ks579gd_/aiohttp-3.11.0b3.dist-info/WHEEL\n      running build_py\n      running build_ext\n      building 'aiohttp._websocket.mask' extension\n      creating /tmp/tmpfouut4lb.build-temp/aiohttp/_websocket\n      cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -fPIC\n      -I/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/include -I/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/include/python3.9 -c\n      aiohttp/_websocket/mask.c -o /tmp/tmpfouut4lb.build-temp/aiohttp/_websocket/mask.o\n      creating /tmp/tmpiyd88jtg.build-lib/aiohttp/_websocket\n      cc -pthread -shared -Wl,--exclude-libs,ALL /tmp/tmpfouut4lb.build-temp/aiohttp/_websocket/mask.o\n      -L/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib -o /tmp/tmpiyd88jtg.build-lib/aiohttp/_websocket/mask.cpython-39-x86_64-linux-gnu.so\n      building 'aiohttp._http_parser' extension\n      creating /tmp/tmpfouut4lb.build-temp/vendor/llhttp/build/c\n      creating /tmp/tmpfouut4lb.build-temp/vendor/llhttp/src/native\n      cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -fPIC -DLLHTTP_STRICT_MODE=0 -Ivendor/llhttp/build\n      -I/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/include -I/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/include/python3.9 -c\n      aiohttp/_find_header.c -o /tmp/tmpfouut4lb.build-temp/aiohttp/_find_header.o\n      cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -fPIC -DLLHTTP_STRICT_MODE=0 -Ivendor/llhttp/build\n      -I/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/include -I/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/include/python3.9 -c\n      aiohttp/_http_parser.c -o /tmp/tmpfouut4lb.build-temp/aiohttp/_http_parser.o\n      cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -fPIC -DLLHTTP_STRICT_MODE=0 -Ivendor/llhttp/build\n      -I/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/include -I/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/include/python3.9 -c\n      vendor/llhttp/build/c/llhttp.c -o /tmp/tmpfouut4lb.build-temp/vendor/llhttp/build/c/llhttp.o\n      cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -fPIC -DLLHTTP_STRICT_MODE=0 -Ivendor/llhttp/build\n      -I/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/include -I/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/include/python3.9 -c\n      vendor/llhttp/src/native/api.c -o /tmp/tmpfouut4lb.build-temp/vendor/llhttp/src/native/api.o\n      cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -fPIC -DLLHTTP_STRICT_MODE=0 -Ivendor/llhttp/build\n      -I/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/include -I/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/include/python3.9 -c\n      vendor/llhttp/src/native/http.c -o /tmp/tmpfouut4lb.build-temp/vendor/llhttp/src/native/http.o\n      cc -pthread -shared -Wl,--exclude-libs,ALL /tmp/tmpfouut4lb.build-temp/aiohttp/_find_header.o /tmp/tmpfouut4lb.build-temp/aiohttp/_http_parser.o\n      /tmp/tmpfouut4lb.build-temp/vendor/llhttp/build/c/llhttp.o /tmp/tmpfouut4lb.build-temp/vendor/llhttp/src/native/api.o\n      /tmp/tmpfouut4lb.build-temp/vendor/llhttp/src/native/http.o -L/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib -o\n      /tmp/tmpiyd88jtg.build-lib/aiohttp/_http_parser.cpython-39-x86_64-linux-gnu.so\n      building 'aiohttp._http_writer' extension\n      cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -fPIC\n      -I/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/include -I/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/include/python3.9 -c\n      aiohttp/_http_writer.c -o /tmp/tmpfouut4lb.build-temp/aiohttp/_http_writer.o\n      cc -pthread -shared -Wl,--exclude-libs,ALL /tmp/tmpfouut4lb.build-temp/aiohttp/_http_writer.o\n      -L/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib -o /tmp/tmpiyd88jtg.build-lib/aiohttp/_http_writer.cpython-39-x86_64-linux-gnu.so\n      building 'aiohttp._websocket.reader_c' extension\n      cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -fPIC\n      -I/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/include -I/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/include/python3.9 -c\n      aiohttp/_websocket/reader_c.c -o /tmp/tmpfouut4lb.build-temp/aiohttp/_websocket/reader_c.o\n\n      [stderr]\n      *********************\n      * Accelerated build *\n      *********************\n      warning: no files found matching 'aiohttp' anywhere in distribution\n      warning: no previously-included files matching '*.pyd' found anywhere in distribution\n      warning: no previously-included files matching '*.so' found anywhere in distribution\n      warning: no previously-included files matching '*.lib' found anywhere in distribution\n      warning: no previously-included files matching '*.dll' found anywhere in distribution\n      warning: no previously-included files matching '*.a' found anywhere in distribution\n      warning: no previously-included files matching '*.obj' found anywhere in distribution\n      warning: no previously-included files found matching 'aiohttp/*.html'\n      no previously-included directories found matching 'docs/_build'\n      aiohttp/_find_header.c: In function ‘find_header’:\n      aiohttp/_find_header.c:21:19: warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]\n         21 |     char *pchar = str;\n            |                   ^~~\n      aiohttp/_find_header.c:9867:1: warning: label ‘missing’ defined but not used [-Wunused-label]\n       9867 | missing:\n            | ^~~~~~~\n      aiohttp/_http_parser.c: In function ‘__pyx_f_7aiohttp_12_http_parser_cb_on_header_field’:\n      aiohttp/_http_parser.c:16286:33: warning: comparison of integer expressions of different signedness: ‘Py_ssize_t’ {aka ‘long int’} and ‘size_t’ {aka ‘long\n      unsigned int’} [-Wsign-compare]\n      16286 |       __pyx_t_6 = (__pyx_v_size > __pyx_v_pyparser->_max_field_size);\n            |                                 ^\n      aiohttp/_http_parser.c:16354:148: warning: passing argument 2 of ‘__pyx_v_pyparser->__pyx_vtab->_on_header_field’ discards ‘const’ qualifier from pointer\n      target type [-Wdiscarded-qualifiers]\n      16354 |       __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_header_field(__pyx_v_pyparser,\n      __pyx_v_at, __pyx_v_length); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 723, __pyx_L3_error)\n            |                                                                                                                                                    ^~~~~~~~~~\n      aiohttp/_http_parser.c:16354:148: note: expected ‘char *’ but argument is of type ‘const char *’\n      aiohttp/_http_parser.c: In function ‘__pyx_f_7aiohttp_12_http_parser_cb_on_header_value’:\n      aiohttp/_http_parser.c:16576:33: warning: comparison of integer expressions of different signedness: ‘Py_ssize_t’ {aka ‘long int’} and ‘size_t’ {aka ‘long\n      unsigned int’} [-Wsign-compare]\n      16576 |       __pyx_t_6 = (__pyx_v_size > __pyx_v_pyparser->_max_field_size);\n            |                                 ^\n      aiohttp/_http_parser.c:16644:148: warning: passing argument 2 of ‘__pyx_v_pyparser->__pyx_vtab->_on_header_value’ discards ‘const’ qualifier from pointer\n      target type [-Wdiscarded-qualifiers]\n      16644 |       __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_header_value(__pyx_v_pyparser,\n      __pyx_v_at, __pyx_v_length); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 740, __pyx_L3_error)\n            |                                                                                                                                                    ^~~~~~~~~~\n      aiohttp/_http_parser.c:16644:148: note: expected ‘char *’ but argument is of type ‘const char *’\n      aiohttp/_http_parser.c: In function ‘__pyx_pw_7aiohttp_12_http_parser_10HttpParser_7feed_data’:\n      aiohttp/_http_parser.c:13135:17: warning: ‘__pyx_v_nb’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n      13135 |     __pyx_t_4 = __Pyx_PyObject_GetSlice(__pyx_v_data, __pyx_v_nb, 0, NULL, NULL, NULL, 1, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 572,\n      __pyx_L1_error)\n            |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n      aiohttp/_http_parser.c:12742:10: note: ‘__pyx_v_nb’ was declared here\n      12742 |   size_t __pyx_v_nb;\n            |          ^~~~~~~~~~\n      cc1: fatal error: aiohttp/_websocket/reader_c.c: No such file or directory\n      compilation terminated.\n      Traceback (most recent call last):\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/spawn.py\", line 70, in spawn\n          subprocess.check_call(cmd, env=_inject_macos_ver(env))\n        File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/subprocess.py\", line 373, in check_call\n          raise CalledProcessError(retcode, cmd)\n      subprocess.CalledProcessError: Command '['/usr/bin/cc', '-pthread', '-Wno-unused-result', '-Wsign-compare', '-Wunreachable-code',\n      '-DNDEBUG', '-g', '-fwrapv', '-O3', '-Wall', '-fPIC', '-fPIC', '-I/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/include',\n      '-I/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/include/python3.9', '-c', 'aiohttp/_websocket/reader_c.c', '-o',\n      '/tmp/tmpfouut4lb.build-temp/aiohttp/_websocket/reader_c.o']' returned non-zero exit status 1.\n\n      The above exception was the direct cause of the following exception:\n\n      Traceback (most recent call last):\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/unixccompiler.py\", line 200, in _compile\n          self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs)\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/ccompiler.py\", line 1045, in spawn\n          spawn(cmd, dry_run=self.dry_run, **kwargs)\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/spawn.py\", line 76, in spawn\n          raise DistutilsExecError(\n      distutils.errors.DistutilsExecError: command '/usr/bin/cc' failed with exit code 1\n\n      During handling of the above exception, another exception occurred:\n\n      Traceback (most recent call last):\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/command/editable_wheel.py\", line 139, in run\n          self._create_wheel_file(bdist_wheel)\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/command/editable_wheel.py\", line 340, in _create_wheel_file\n          files, mapping = self._run_build_commands(dist_name, unpacked, lib, tmp)\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/command/editable_wheel.py\", line 263, in _run_build_commands\n          self._run_build_subcommands()\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/command/editable_wheel.py\", line 290, in _run_build_subcommands\n          self.run_command(name)\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/cmd.py\", line 316, in run_command\n          self.distribution.run_command(command)\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/dist.py\", line 995, in run_command\n          super().run_command(command)\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/dist.py\", line 973, in run_command\n          cmd_obj.run()\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/command/build_ext.py\", line 99, in run\n          _build_ext.run(self)\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py\", line 359, in run\n          self.build_extensions()\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py\", line 476, in build_extensions\n          self._build_extensions_serial()\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py\", line 502, in\n      _build_extensions_serial\n          self.build_extension(ext)\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/command/build_ext.py\", line 264, in build_extension\n          _build_ext.build_extension(self, ext)\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py\", line 557, in build_extension\n          objects = self.compiler.compile(\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/ccompiler.py\", line 606, in compile\n          self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)\n        File \"/home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/unixccompiler.py\", line 202, in _compile\n          raise CompileError(msg)\n      distutils.errors.CompileError: command '/usr/bin/cc' failed with exit code 1\n      /home/gcpuser/.cache/uv/builds-v0/.tmpr4FjnK/lib/python3.9/site-packages/setuptools/_distutils/dist.py:973: _DebuggingTips: Problem in editable installation.\n      !!\n\n              ********************************************************************************\n              An error happened while installing `aiohttp` in editable mode.\n\n              The following steps are recommended to help debug this problem:\n\n              - Try to install the project normally, without using the editable mode.\n                Does the error still persist?\n                (If it does, try fixing the problem before attempting the editable mode).\n              - If you are using binary extensions, make sure you have all OS-level\n                dependencies installed (e.g. compilers, toolchains, binary libraries, ...).\n              - Try the latest version of setuptools (maybe the error was already fixed).\n              - If you (or your project dependencies) are using any setuptools extension\n                or customization, make sure they support the editable mode.\n\n              After following the steps above, if the problem still persists and\n              you think this is related to how setuptools handles editable installations,\n              please submit a reproducible example\n              (see https://stackoverflow.com/help/minimal-reproducible-example) to:\n\n                  https://github.com/pypa/setuptools/issues\n\n              See https://setuptools.pypa.io/en/latest/userguide/development_mode.html for details.\n              ********************************************************************************\n\n      !!\n        cmd_obj.run()\n      error: command '/usr/bin/cc' failed with exit code 1\n\n      hint: This usually indicates a problem with the package or the build environment.\nmake: *** [Makefile:100: .develop] Error 1\nResolved 26 packages in 16ms\nInstalled 5 packages in 5ms\n + async-generator==1.10\n + brotlipy==0.7.0\n + chardet==5.2.0\n + multdict==0.0.5\n + pytest-asyncio==0.25.1\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.3, pluggy-1.5.0 -- /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/.venv/bin/python\ncodspeed: 3.0.0 (disabled, mode: walltime, timer_resolution: 1.0ns)\ncachedir: .pytest_cache\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c\nconfigfile: setup.cfg\nplugins: cov-5.0.0, mock-3.14.0, asyncio-0.25.1, codspeed-3.0.0\nasyncio: mode=strict, asyncio_default_fixture_loop_scope=None\ncollecting ... collected 9 items\n\nr2e_tests/test_1.py::test_ctor PASSED                                    [ 11%]\nr2e_tests/test_1.py::test_callbacks_on_close PASSED                      [ 22%]\nr2e_tests/test_1.py::test_callbacks_on_release PASSED                    [ 33%]\nr2e_tests/test_1.py::test_callbacks_exception PASSED                     [ 44%]\nr2e_tests/test_1.py::test_del PASSED                                     [ 55%]\nr2e_tests/test_1.py::test_close PASSED                                   [ 66%]\nr2e_tests/test_1.py::test_release PASSED                                 [ 77%]\nr2e_tests/test_1.py::test_release_proto_should_close PASSED              [ 88%]\nr2e_tests/test_1.py::test_release_released PASSED                        [100%]\n\n==================================== PASSES ====================================\n\n---------- coverage: platform linux, python 3.9.21-final-0 -----------\nName                                      Stmts   Miss Branch BrPart  Cover\n---------------------------------------------------------------------------\naiohttp/__init__.py                          27     10      2      0    59%\naiohttp/_websocket/__init__.py                0      0      0      0   100%\naiohttp/_websocket/helpers.py                77     52     38      0    22%\naiohttp/_websocket/models.py                 51      4      0      0    92%\naiohttp/_websocket/reader.py                  5      0      0      0   100%\naiohttp/_websocket/reader_py.py             208    180     92      0    10%\naiohttp/_websocket/writer.py                 75     58     24      0    17%\naiohttp/abc.py                               98      8      0      0    92%\naiohttp/base_protocol.py                     68     51     22      0    19%\naiohttp/client.py                           561    413    210      3    20%\naiohttp/client_exceptions.py                156     69     20      0    49%\naiohttp/client_proto.py                     164    131     56      0    15%\naiohttp/client_reqrep.py                    697    523    294      0    18%\naiohttp/client_ws.py                        274    217     84      1    17%\naiohttp/compression_utils.py                 70     36     14      0    40%\naiohttp/connector.py                        761    580    332      6    18%\naiohttp/cookiejar.py                        274    217    130      0    14%\naiohttp/formdata.py                          97     79     46      0    13%\naiohttp/hdrs.py                              90      0      0      0   100%\naiohttp/helpers.py                          470    308    168      1    28%\naiohttp/http.py                              11      0      2      0   100%\naiohttp/http_exceptions.py                   50     20      4      0    56%\naiohttp/http_parser.py                      508    412    210      1    14%\naiohttp/http_websocket.py                     6      0      0      0   100%\naiohttp/http_writer.py                      119     82     50      0    22%\naiohttp/log.py                                7      0      0      0   100%\naiohttp/multipart.py                        623    508    266      1    13%\naiohttp/payload.py                          237    113     58      1    44%\naiohttp/payload_streamer.py                  31     11      4      0    69%\naiohttp/pytest_plugin.py                    163    110     42      5    28%\naiohttp/resolver.py                          79     58     26      0    20%\naiohttp/streams.py                          413    325    152      0    16%\naiohttp/tcp_helpers.py                       19     11      6      0    32%\naiohttp/test_utils.py                       324    213     54      2    30%\naiohttp/tracing.py                          191     69     32      0    69%\naiohttp/typedefs.py                          24      0      0      0   100%\naiohttp/web.py                              126     88     54      0    22%\naiohttp/web_app.py                          292    196     82      0    26%\naiohttp/web_exceptions.py                   157     25      8      0    80%\naiohttp/web_fileresponse.py                 160    126     52      0    18%\naiohttp/web_log.py                          102     58     20      0    36%\naiohttp/web_middlewares.py                   59     46     22      0    16%\naiohttp/web_protocol.py                     367    306    158      0    12%\naiohttp/web_request.py                      445    294    140      1    27%\naiohttp/web_response.py                     485    367    226      0    17%\naiohttp/web_routedef.py                     100     44     10      0    55%\naiohttp/web_runner.py                       213    130     36      0    33%\naiohttp/web_server.py                        42     24     12      0    33%\naiohttp/web_urldispatcher.py                740    474    163      0    29%\naiohttp/web_ws.py                           388    312    136      1    15%\naiohttp/worker.py                           126    126     30      0     0%\ntests/conftest.py                           131    131     16      0     0%\ntests/test_base_protocol.py                 198    198      2      0     0%\ntests/test_benchmarks_client.py              18     18      2      0     0%\ntests/test_benchmarks_client_request.py      48     48      2      0     0%\ntests/test_benchmarks_client_ws.py           66     66     12      0     0%\ntests/test_benchmarks_cookiejar.py           14     14      0      0     0%\ntests/test_benchmarks_http_websocket.py      49     49      8      0     0%\ntests/test_benchmarks_http_writer.py         11     11      2      0     0%\ntests/test_circular_imports.py               29     29     13      0     0%\ntests/test_classbasedview.py                 39     39      0      0     0%\ntests/test_client_connection.py              94     94      2      0     0%\ntests/test_client_exceptions.py             199    199     14      0     0%\ntests/test_client_fingerprint.py             59     59      0      0     0%\ntests/test_client_functional.py            2616   2616     88      0     0%\ntests/test_client_proto.py                   99     99      0      0     0%\ntests/test_client_request.py                827    827     18      0     0%\ntests/test_client_response.py               480    480      6      0     0%\ntests/test_client_session.py                593    593     29      0     0%\ntests/test_client_ws.py                     489    489      2      0     0%\ntests/test_client_ws_functional.py          831    831     32      0     0%\ntests/test_connector.py                    2050   2050    106      0     0%\ntests/test_cookiejar.py                     461    461     32      0     0%\ntests/test_flowcontrol_streams.py            96     96      0      0     0%\ntests/test_formdata.py                       86     86      6      0     0%\ntests/test_helpers.py                       454    454     22      0     0%\ntests/test_http_exceptions.py               109    109     10      0     0%\ntests/test_http_parser.py                  1092   1092     66      0     0%\ntests/test_http_writer.py                   182    182     10      0     0%\ntests/test_imports.py                        34     34      6      0     0%\ntests/test_loop.py                           36     36      0      0     0%\ntests/test_multipart.py                     826    826     32      0     0%\ntests/test_multipart_helpers.py             446    446      0      0     0%\ntests/test_payload.py                        95     95      0      0     0%\ntests/test_proxy.py                         324    324      2      0     0%\ntests/test_proxy_functional.py              459    459     18      0     0%\ntests/test_pytest_plugin.py                  27     27      0      0     0%\ntests/test_resolver.py                      231    231     20      0     0%\ntests/test_route_def.py                     210    210      0      0     0%\ntests/test_run_app.py                       563    563     30      0     0%\ntests/test_streams.py                      1077   1077     38      0     0%\ntests/test_tcp_helpers.py                    52     52      2      0     0%\ntests/test_test_utils.py                    273    273     12      0     0%\ntests/test_tracing.py                        48     48      0      0     0%\ntests/test_urldispatch.py                   859    859     24      0     0%\ntests/test_web_app.py                       454    454      6      0     0%\ntests/test_web_cli.py                        94     94      0      0     0%\ntests/test_web_exceptions.py                179    179     22      0     0%\ntests/test_web_functional.py               1605   1605     36      0     0%\ntests/test_web_log.py                       116    116      2      0     0%\ntests/test_web_middleware.py                268    268     16      0     0%\ntests/test_web_request.py                   513    513      8      0     0%\ntests/test_web_request_handler.py            42     42      0      0     0%\ntests/test_web_response.py                  905    905      6      0     0%\ntests/test_web_runner.py                    151    151      4      0     0%\ntests/test_web_sendfile.py                   84     84      0      0     0%\ntests/test_web_sendfile_functional.py       673    673     18      0     0%\ntests/test_web_server.py                    162    162      0      0     0%\ntests/test_web_urldispatcher.py             524    524     24      0     0%\ntests/test_web_websocket.py                 444    444      8      0     0%\ntests/test_web_websocket_functional.py      862    862     28      0     0%\ntests/test_websocket_handshake.py           152    152     12      0     0%\ntests/test_websocket_parser.py              364    364     12      0     0%\ntests/test_websocket_writer.py               95     95      6      0     0%\ntests/test_worker.py                        191    191      2      0     0%\n---------------------------------------------------------------------------\nTOTAL                                     35688  32342   4481     23     9%\n\n============================= slowest 10 durations =============================\n0.02s call     r2e_tests/test_1.py::test_del\n\n(9 durations < 0.005s hidden.  Use -vv to show these durations.)\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_ctor\nPASSED r2e_tests/test_1.py::test_callbacks_on_close\nPASSED r2e_tests/test_1.py::test_callbacks_on_release\nPASSED r2e_tests/test_1.py::test_callbacks_exception\nPASSED r2e_tests/test_1.py::test_del\nPASSED r2e_tests/test_1.py::test_close\nPASSED r2e_tests/test_1.py::test_release\nPASSED r2e_tests/test_1.py::test_release_proto_should_close\nPASSED r2e_tests/test_1.py::test_release_released\n============================== 9 passed in 4.57s ===============================\n",
    "new_commit_res_stderr": "/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/.venv/lib/python3.9/site-packages/pytest_asyncio/plugin.py:207: PytestDeprecationWarning: The configuration option \"asyncio_default_fixture_loop_scope\" is unset.\nThe event loop scope for asynchronous fixtures will default to the fixture caching scope. Future versions of pytest-asyncio will default the loop scope for asynchronous fixtures to function scope. Set the default fixture loop scope explicitly in order to avoid unexpected behavior in the future. Valid fixture loop scopes are: \"function\", \"class\", \"module\", \"package\", \"session\"\n\n  warnings.warn(PytestDeprecationWarning(_DEFAULT_FIXTURE_LOOP_SCOPE_UNSET))\n",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.3, pluggy-1.5.0 -- /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/.venv/bin/python\ncodspeed: 3.0.0 (disabled, mode: walltime, timer_resolution: 1.0ns)\ncachedir: .pytest_cache\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c\nconfigfile: setup.cfg\nplugins: cov-5.0.0, mock-3.14.0, asyncio-0.25.1, codspeed-3.0.0\nasyncio: mode=strict, asyncio_default_fixture_loop_scope=None\ncollecting ... collected 9 items\n\nr2e_tests/test_1.py::test_ctor PASSED                                    [ 11%]\nr2e_tests/test_1.py::test_callbacks_on_close PASSED                      [ 22%]\nr2e_tests/test_1.py::test_callbacks_on_release PASSED                    [ 33%]\nr2e_tests/test_1.py::test_callbacks_exception PASSED                     [ 44%]\nr2e_tests/test_1.py::test_del PASSED                                     [ 55%]\nr2e_tests/test_1.py::test_close PASSED                                   [ 66%]\nr2e_tests/test_1.py::test_release FAILED                                 [ 77%]\nr2e_tests/test_1.py::test_release_proto_should_close FAILED              [ 88%]\nr2e_tests/test_1.py::test_release_released PASSED                        [100%]\n\n=================================== FAILURES ===================================\n_________________________________ test_release _________________________________\n\nself = <Mock name='mock._release' id='124676633696528'>\nargs = (<object object at 0x71648c46ee90>, <Mock id='124676632824320'>)\nkwargs = {}\nexpected = call(<object object at 0x71648c46ee90>, <Mock id='124676632824320'>)\nactual = call(<object object at 0x71648c46ee90>, <Mock id='124676632824320'>, should_close=False)\n_error_message = <function NonCallableMock.assert_called_with.<locals>._error_message at 0x71648a68e4c0>\ncause = None\n\n    def assert_called_with(self, /, *args, **kwargs):\n        \"\"\"assert that the last call was made with the specified arguments.\n    \n        Raises an AssertionError if the args and keyword args passed in are\n        different to the last call to the mock.\"\"\"\n        if self.call_args is None:\n            expected = self._format_mock_call_signature(args, kwargs)\n            actual = 'not called.'\n            error_message = ('expected call not found.\\nExpected: %s\\nActual: %s'\n                    % (expected, actual))\n            raise AssertionError(error_message)\n    \n        def _error_message():\n            msg = self._format_mock_failure_message(args, kwargs)\n            return msg\n        expected = self._call_matcher(_Call((args, kwargs), two=True))\n        actual = self._call_matcher(self.call_args)\n        if actual != expected:\n            cause = expected if isinstance(expected, Exception) else None\n>           raise AssertionError(_error_message()) from cause\nE           AssertionError: expected call not found.\nE           Expected: _release(<object object at 0x71648c46ee90>, <Mock id='124676632824320'>)\nE           Actual: _release(<object object at 0x71648c46ee90>, <Mock id='124676632824320'>, should_close=False)\n\n_error_message = <function NonCallableMock.assert_called_with.<locals>._error_message at 0x71648a68e4c0>\nactual     = call(<object object at 0x71648c46ee90>, <Mock id='124676632824320'>, should_close=False)\nargs       = (<object object at 0x71648c46ee90>, <Mock id='124676632824320'>)\ncause      = None\nexpected   = call(<object object at 0x71648c46ee90>, <Mock id='124676632824320'>)\nkwargs     = {}\nself       = <Mock name='mock._release' id='124676633696528'>\n\n../../../../.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/mock.py:907: AssertionError\n\nDuring handling of the above exception, another exception occurred:\n\nconnector = <Mock id='124676632822784'>, key = <object object at 0x71648c46ee90>\nprotocol = <Mock id='124676632824320'>, loop = <Mock id='124676632823408'>\n\n    def test_release(connector, key, protocol, loop) -> None:\n        conn = Connection(connector, key, protocol, loop)\n        assert not conn.closed\n        conn.release()\n        assert not protocol.transport.close.called\n        assert conn._protocol is None\n>       connector._release.assert_called_with(key, protocol)\nE       AssertionError: expected call not found.\nE       Expected: _release(<object object at 0x71648c46ee90>, <Mock id='124676632824320'>)\nE       Actual: _release(<object object at 0x71648c46ee90>, <Mock id='124676632824320'>, should_close=False)\nE       \nE       pytest introspection follows:\nE       \nE       Kwargs:\nE       assert {'should_close': False} == {}\nE         \nE         Left contains 1 more item:\nE         {'should_close': False}\nE         \nE         Full diff:\nE         - {}\nE         + {\nE         +     'should_close': False,\nE         + }\n\nconn       = Connection<<object object at 0x71648c46ee90>>\nconnector  = <Mock id='124676632822784'>\nkey        = <object object at 0x71648c46ee90>\nloop       = <Mock id='124676632823408'>\nprotocol   = <Mock id='124676632824320'>\n\nr2e_tests/test_1.py:115: AssertionError\n_______________________ test_release_proto_should_close ________________________\n\nself = <Mock name='mock._release' id='124676633414480'>\nargs = (<object object at 0x71648c46ef00>, <Mock id='124676632825568'>)\nkwargs = {}\nexpected = call(<object object at 0x71648c46ef00>, <Mock id='124676632825568'>)\nactual = call(<object object at 0x71648c46ef00>, <Mock id='124676632825568'>, should_close=True)\n_error_message = <function NonCallableMock.assert_called_with.<locals>._error_message at 0x71648a68e430>\ncause = None\n\n    def assert_called_with(self, /, *args, **kwargs):\n        \"\"\"assert that the last call was made with the specified arguments.\n    \n        Raises an AssertionError if the args and keyword args passed in are\n        different to the last call to the mock.\"\"\"\n        if self.call_args is None:\n            expected = self._format_mock_call_signature(args, kwargs)\n            actual = 'not called.'\n            error_message = ('expected call not found.\\nExpected: %s\\nActual: %s'\n                    % (expected, actual))\n            raise AssertionError(error_message)\n    \n        def _error_message():\n            msg = self._format_mock_failure_message(args, kwargs)\n            return msg\n        expected = self._call_matcher(_Call((args, kwargs), two=True))\n        actual = self._call_matcher(self.call_args)\n        if actual != expected:\n            cause = expected if isinstance(expected, Exception) else None\n>           raise AssertionError(_error_message()) from cause\nE           AssertionError: expected call not found.\nE           Expected: _release(<object object at 0x71648c46ef00>, <Mock id='124676632825568'>)\nE           Actual: _release(<object object at 0x71648c46ef00>, <Mock id='124676632825568'>, should_close=True)\n\n_error_message = <function NonCallableMock.assert_called_with.<locals>._error_message at 0x71648a68e430>\nactual     = call(<object object at 0x71648c46ef00>, <Mock id='124676632825568'>, should_close=True)\nargs       = (<object object at 0x71648c46ef00>, <Mock id='124676632825568'>)\ncause      = None\nexpected   = call(<object object at 0x71648c46ef00>, <Mock id='124676632825568'>)\nkwargs     = {}\nself       = <Mock name='mock._release' id='124676633414480'>\n\n../../../../.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/mock.py:907: AssertionError\n\nDuring handling of the above exception, another exception occurred:\n\nconnector = <Mock id='124676632824512'>, key = <object object at 0x71648c46ef00>\nprotocol = <Mock id='124676632825568'>, loop = <Mock id='124676632825808'>\n\n    def test_release_proto_should_close(connector, key, protocol, loop) -> None:\n        protocol.should_close = True\n        conn = Connection(connector, key, protocol, loop)\n        assert not conn.closed\n        conn.release()\n        assert not protocol.transport.close.called\n        assert conn._protocol is None\n>       connector._release.assert_called_with(key, protocol)\nE       AssertionError: expected call not found.\nE       Expected: _release(<object object at 0x71648c46ef00>, <Mock id='124676632825568'>)\nE       Actual: _release(<object object at 0x71648c46ef00>, <Mock id='124676632825568'>, should_close=True)\nE       \nE       pytest introspection follows:\nE       \nE       Kwargs:\nE       assert {'should_close': True} == {}\nE         \nE         Left contains 1 more item:\nE         {'should_close': True}\nE         \nE         Full diff:\nE         - {}\nE         + {\nE         +     'should_close': True,\nE         + }\n\nconn       = Connection<<object object at 0x71648c46ef00>>\nconnector  = <Mock id='124676632824512'>\nkey        = <object object at 0x71648c46ef00>\nloop       = <Mock id='124676632825808'>\nprotocol   = <Mock id='124676632825568'>\n\nr2e_tests/test_1.py:126: AssertionError\n==================================== PASSES ====================================\n\n---------- coverage: platform linux, python 3.9.21-final-0 -----------\nName                                      Stmts   Miss Branch BrPart  Cover\n---------------------------------------------------------------------------\naiohttp/__init__.py                          27     10      2      0    59%\naiohttp/_websocket/__init__.py                0      0      0      0   100%\naiohttp/_websocket/helpers.py                77     52     38      0    22%\naiohttp/_websocket/models.py                 51      4      0      0    92%\naiohttp/_websocket/reader.py                  5      0      0      0   100%\naiohttp/_websocket/reader_py.py             208    180     92      0    10%\naiohttp/_websocket/writer.py                 75     58     24      0    17%\naiohttp/abc.py                               98      8      0      0    92%\naiohttp/base_protocol.py                     68     51     22      0    19%\naiohttp/client.py                           561    413    210      3    20%\naiohttp/client_exceptions.py                156     69     20      0    49%\naiohttp/client_proto.py                     164    131     56      0    15%\naiohttp/client_reqrep.py                    697    523    294      0    18%\naiohttp/client_ws.py                        274    217     84      1    17%\naiohttp/compression_utils.py                 70     36     14      0    40%\naiohttp/connector.py                        761    580    332      6    18%\naiohttp/cookiejar.py                        274    217    130      0    14%\naiohttp/formdata.py                          97     79     46      0    13%\naiohttp/hdrs.py                              90      0      0      0   100%\naiohttp/helpers.py                          470    308    168      1    28%\naiohttp/http.py                              11      0      2      0   100%\naiohttp/http_exceptions.py                   50     20      4      0    56%\naiohttp/http_parser.py                      508    412    210      1    14%\naiohttp/http_websocket.py                     6      0      0      0   100%\naiohttp/http_writer.py                      119     82     50      0    22%\naiohttp/log.py                                7      0      0      0   100%\naiohttp/multipart.py                        623    508    266      1    13%\naiohttp/payload.py                          237    113     58      1    44%\naiohttp/payload_streamer.py                  31     11      4      0    69%\naiohttp/pytest_plugin.py                    163    110     42      5    28%\naiohttp/resolver.py                          79     58     26      0    20%\naiohttp/streams.py                          413    325    152      0    16%\naiohttp/tcp_helpers.py                       19     11      6      0    32%\naiohttp/test_utils.py                       324    213     54      2    30%\naiohttp/tracing.py                          191     69     32      0    69%\naiohttp/typedefs.py                          24      0      0      0   100%\naiohttp/web.py                              126     88     54      0    22%\naiohttp/web_app.py                          292    196     82      0    26%\naiohttp/web_exceptions.py                   157     25      8      0    80%\naiohttp/web_fileresponse.py                 160    126     52      0    18%\naiohttp/web_log.py                          102     58     20      0    36%\naiohttp/web_middlewares.py                   59     46     22      0    16%\naiohttp/web_protocol.py                     367    306    158      0    12%\naiohttp/web_request.py                      445    294    140      1    27%\naiohttp/web_response.py                     485    367    226      0    17%\naiohttp/web_routedef.py                     100     44     10      0    55%\naiohttp/web_runner.py                       213    130     36      0    33%\naiohttp/web_server.py                        42     24     12      0    33%\naiohttp/web_urldispatcher.py                740    474    163      0    29%\naiohttp/web_ws.py                           388    312    136      1    15%\naiohttp/worker.py                           126    126     30      0     0%\ntests/conftest.py                           131    131     16      0     0%\ntests/test_base_protocol.py                 198    198      2      0     0%\ntests/test_benchmarks_client.py              18     18      2      0     0%\ntests/test_benchmarks_client_request.py      48     48      2      0     0%\ntests/test_benchmarks_client_ws.py           66     66     12      0     0%\ntests/test_benchmarks_cookiejar.py           14     14      0      0     0%\ntests/test_benchmarks_http_websocket.py      49     49      8      0     0%\ntests/test_benchmarks_http_writer.py         11     11      2      0     0%\ntests/test_circular_imports.py               29     29     13      0     0%\ntests/test_classbasedview.py                 39     39      0      0     0%\ntests/test_client_connection.py              94     94      2      0     0%\ntests/test_client_exceptions.py             199    199     14      0     0%\ntests/test_client_fingerprint.py             59     59      0      0     0%\ntests/test_client_functional.py            2616   2616     88      0     0%\ntests/test_client_proto.py                   99     99      0      0     0%\ntests/test_client_request.py                827    827     18      0     0%\ntests/test_client_response.py               480    480      6      0     0%\ntests/test_client_session.py                593    593     29      0     0%\ntests/test_client_ws.py                     489    489      2      0     0%\ntests/test_client_ws_functional.py          831    831     32      0     0%\ntests/test_connector.py                    2050   2050    106      0     0%\ntests/test_cookiejar.py                     461    461     32      0     0%\ntests/test_flowcontrol_streams.py            96     96      0      0     0%\ntests/test_formdata.py                       86     86      6      0     0%\ntests/test_helpers.py                       454    454     22      0     0%\ntests/test_http_exceptions.py               109    109     10      0     0%\ntests/test_http_parser.py                  1092   1092     66      0     0%\ntests/test_http_writer.py                   182    182     10      0     0%\ntests/test_imports.py                        34     34      6      0     0%\ntests/test_loop.py                           36     36      0      0     0%\ntests/test_multipart.py                     826    826     32      0     0%\ntests/test_multipart_helpers.py             446    446      0      0     0%\ntests/test_payload.py                        95     95      0      0     0%\ntests/test_proxy.py                         324    324      2      0     0%\ntests/test_proxy_functional.py              459    459     18      0     0%\ntests/test_pytest_plugin.py                  27     27      0      0     0%\ntests/test_resolver.py                      231    231     20      0     0%\ntests/test_route_def.py                     210    210      0      0     0%\ntests/test_run_app.py                       563    563     30      0     0%\ntests/test_streams.py                      1077   1077     38      0     0%\ntests/test_tcp_helpers.py                    52     52      2      0     0%\ntests/test_test_utils.py                    273    273     12      0     0%\ntests/test_tracing.py                        48     48      0      0     0%\ntests/test_urldispatch.py                   859    859     24      0     0%\ntests/test_web_app.py                       454    454      6      0     0%\ntests/test_web_cli.py                        94     94      0      0     0%\ntests/test_web_exceptions.py                179    179     22      0     0%\ntests/test_web_functional.py               1605   1605     36      0     0%\ntests/test_web_log.py                       116    116      2      0     0%\ntests/test_web_middleware.py                268    268     16      0     0%\ntests/test_web_request.py                   513    513      8      0     0%\ntests/test_web_request_handler.py            42     42      0      0     0%\ntests/test_web_response.py                  905    905      6      0     0%\ntests/test_web_runner.py                    151    151      4      0     0%\ntests/test_web_sendfile.py                   84     84      0      0     0%\ntests/test_web_sendfile_functional.py       673    673     18      0     0%\ntests/test_web_server.py                    162    162      0      0     0%\ntests/test_web_urldispatcher.py             524    524     24      0     0%\ntests/test_web_websocket.py                 444    444      8      0     0%\ntests/test_web_websocket_functional.py      862    862     28      0     0%\ntests/test_websocket_handshake.py           152    152     12      0     0%\ntests/test_websocket_parser.py              364    364     12      0     0%\ntests/test_websocket_writer.py               95     95      6      0     0%\ntests/test_worker.py                        191    191      2      0     0%\n---------------------------------------------------------------------------\nTOTAL                                     35688  32342   4481     23     9%\n\n============================= slowest 10 durations =============================\n0.02s call     r2e_tests/test_1.py::test_del\n\n(9 durations < 0.005s hidden.  Use -vv to show these durations.)\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_ctor\nPASSED r2e_tests/test_1.py::test_callbacks_on_close\nPASSED r2e_tests/test_1.py::test_callbacks_on_release\nPASSED r2e_tests/test_1.py::test_callbacks_exception\nPASSED r2e_tests/test_1.py::test_del\nPASSED r2e_tests/test_1.py::test_close\nPASSED r2e_tests/test_1.py::test_release_released\nFAILED r2e_tests/test_1.py::test_release - AssertionError: expected call not ...\nFAILED r2e_tests/test_1.py::test_release_proto_should_close - AssertionError:...\n========================= 2 failed, 7 passed in 5.54s ==========================\n",
    "old_commit_res_stderr": "/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d5bbb80195513268c604a908c31870db6b49310c/.venv/lib/python3.9/site-packages/pytest_asyncio/plugin.py:207: PytestDeprecationWarning: The configuration option \"asyncio_default_fixture_loop_scope\" is unset.\nThe event loop scope for asynchronous fixtures will default to the fixture caching scope. Future versions of pytest-asyncio will default the loop scope for asynchronous fixtures to function scope. Set the default fixture loop scope explicitly in order to avoid unexpected behavior in the future. Valid fixture loop scopes are: \"function\", \"class\", \"module\", \"package\", \"session\"\n\n  warnings.warn(PytestDeprecationWarning(_DEFAULT_FIXTURE_LOOP_SCOPE_UNSET))\n"
}
aiohttp/connector.py tests/test_client_connection.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `Connection.release` method includes redundant `should_close` argument when calling connector's `_release`

**Description:**
When releasing a connection, the `Connection.release()` method unnecessarily passes the `should_close` parameter to the connector's `_release` method. This redundant argument causes issues where connector implementations expecting only `key` and `protocol` parameters fail or behave unexpectedly.

**Example Code:**
```python
connector = Connector()
key = 'unique_key'
protocol = Protocol()

connection = Connection(connector, key, protocol, loop)
connection.release()
```

**Expected Behavior:**
The `connector._release` method should be called with only `key` and `protocol`:
```python
connector._release(key, protocol)
```

**Actual Behavior:**
The `connector._release` method is called with an additional `should_close` argument:
```python
connector._release(key, protocol, should_close=protocol.should_close)
```
This extra argument leads to assertion failures or unexpected behavior in connector implementations that do not handle the `should_close` parameter.
[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### aiohttp/connector.py
import asyncio
import functools
import random
import socket
import sys
import traceback
import warnings
from collections import OrderedDict, defaultdict, deque
from contextlib import suppress
from http import HTTPStatus
from itertools import chain, cycle, islice
from time import monotonic
from types import TracebackType
from typing import (
    TYPE_CHECKING,
    Any,
    Awaitable,
    Callable,
    DefaultDict,
    Deque,
    Dict,
    Iterator,
    List,
    Literal,
    Optional,
    Sequence,
    Set,
    Tuple,
    Type,
    Union,
    cast,
)

import aiohappyeyeballs

from . import hdrs, helpers
from .abc import AbstractResolver, ResolveResult
from .client_exceptions import (
    ClientConnectionError,
    ClientConnectorCertificateError,
    ClientConnectorDNSError,
    ClientConnectorError,
    ClientConnectorSSLError,
    ClientHttpProxyError,
    ClientProxyConnectionError,
    ServerFingerprintMismatch,
    UnixClientConnectorError,
    cert_errors,
    ssl_errors,
)
from .client_proto import ResponseHandler
from .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params
from .helpers import (
    ceil_timeout,
    is_ip_address,
    noop,
    sentinel,
    set_exception,
    set_result,
)
from .resolver import DefaultResolver

try:
    import ssl

    SSLContext = ssl.SSLContext
except ImportError:  # pragma: no cover
    ssl = None  # type: ignore[assignment]
    SSLContext = object  # type: ignore[misc,assignment]


EMPTY_SCHEMA_SET = frozenset({""})
HTTP_SCHEMA_SET = frozenset({"http", "https"})
WS_SCHEMA_SET = frozenset({"ws", "wss"})

HTTP_AND_EMPTY_SCHEMA_SET = HTTP_SCHEMA_SET | EMPTY_SCHEMA_SET
HIGH_LEVEL_SCHEMA_SET = HTTP_AND_EMPTY_SCHEMA_SET | WS_SCHEMA_SET


__all__ = ("BaseConnector", "TCPConnector", "UnixConnector", "NamedPipeConnector")


if TYPE_CHECKING:
    from .client import ClientTimeout
    from .client_reqrep import ConnectionKey
    from .tracing import Trace


class _DeprecationWaiter:
    __slots__ = ("_awaitable", "_awaited")

    def __init__(self, awaitable: Awaitable[Any]) -> None:
        self._awaitable = awaitable
        self._awaited = False

    def __await__(self) -> Any:
        self._awaited = True
        return self._awaitable.__await__()

    def __del__(self) -> None:
        if not self._awaited:
            warnings.warn(
                "Connector.close() is a coroutine, "
                "please use await connector.close()",
                DeprecationWarning,
            )


class Connection:

    _source_traceback = None

    def __init__(
        self,
        connector: "BaseConnector",
        key: "ConnectionKey",
        protocol: ResponseHandler,
        loop: asyncio.AbstractEventLoop,
    ) -> None:
        self._key = key
        self._connector = connector
        self._loop = loop
        self._protocol: Optional[ResponseHandler] = protocol
        self._callbacks: List[Callable[[], None]] = []

        if loop.get_debug():
            self._source_traceback = traceback.extract_stack(sys._getframe(1))

    def __repr__(self) -> str:
        return f"Connection<{self._key}>"

    def __del__(self, _warnings: Any = warnings) -> None:
        if self._protocol is not None:
            kwargs = {"source": self}
            _warnings.warn(f"Unclosed connection {self!r}", ResourceWarning, **kwargs)
            if self._loop.is_closed():
                return

            self._connector._release(self._key, self._protocol, should_close=True)

            context = {"client_connection": self, "message": "Unclosed connection"}
            if self._source_traceback is not None:
                context["source_traceback"] = self._source_traceback
            self._loop.call_exception_handler(context)

    def __bool__(self) -> Literal[True]:
        """Force subclasses to not be falsy, to make checks simpler."""
        return True

    @property
    def loop(self) -> asyncio.AbstractEventLoop:
        warnings.warn(
            "connector.loop property is deprecated", DeprecationWarning, stacklevel=2
        )
        return self._loop

    @property
    def transport(self) -> Optional[asyncio.Transport]:
        if self._protocol is None:
            return None
        return self._protocol.transport

    @property
    def protocol(self) -> Optional[ResponseHandler]:
        return self._protocol

    def add_callback(self, callback: Callable[[], None]) -> None:
        if callback is not None:
            self._callbacks.append(callback)

    def _notify_release(self) -> None:
        callbacks, self._callbacks = self._callbacks[:], []

        for cb in callbacks:
            with suppress(Exception):
                cb()

    def close(self) -> None:
        self._notify_release()

        if self._protocol is not None:
            self._connector._release(self._key, self._protocol, should_close=True)
            self._protocol = None

    def release(self) -> None:
        self._notify_release()

        if self._protocol is not None:
            self._connector._release(
                self._key, self._protocol, should_close=self._protocol.should_close
            )
            self._protocol = None

    @property
    def closed(self) -> bool:
        return self._protocol is None or not self._protocol.is_connected()


class _TransportPlaceholder:
    """placeholder for BaseConnector.connect function"""

    __slots__ = ()

    def close(self) -> None:
        """Close the placeholder transport."""


class BaseConnector:
    """Base connector class.

    keepalive_timeout - (optional) Keep-alive timeout.
    force_close - Set to True to force close and do reconnect
        after each request (and between redirects).
    limit - The total number of simultaneous connections.
    limit_per_host - Number of simultaneous connections to one host.
    enable_cleanup_closed - Enables clean-up closed ssl transports.
                            Disabled by default.
    timeout_ceil_threshold - Trigger ceiling of timeout values when
                             it's above timeout_ceil_threshold.
    loop - Optional event loop.
    """

    _closed = True  # prevent AttributeError in __del__ if ctor was failed
    _source_traceback = None

    # abort transport after 2 seconds (cleanup broken connections)
    _cleanup_closed_period = 2.0

    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET

    def __init__(
        self,
        *,
        keepalive_timeout: Union[object, None, float] = sentinel,
        force_close: bool = False,
        limit: int = 100,
        limit_per_host: int = 0,
        enable_cleanup_closed: bool = False,
        loop: Optional[asyncio.AbstractEventLoop] = None,
        timeout_ceil_threshold: float = 5,
    ) -> None:

        if force_close:
            if keepalive_timeout is not None and keepalive_timeout is not sentinel:
                raise ValueError(
                    "keepalive_timeout cannot be set if force_close is True"
                )
        else:
            if keepalive_timeout is sentinel:
                keepalive_timeout = 15.0

        loop = loop or asyncio.get_running_loop()
        self._timeout_ceil_threshold = timeout_ceil_threshold

        self._closed = False
        if loop.get_debug():
            self._source_traceback = traceback.extract_stack(sys._getframe(1))

        # Connection pool of reusable connections.
        # We use a deque to store connections because it has O(1) popleft()
        # and O(1) append() operations to implement a FIFO queue.
        self._conns: DefaultDict[
            ConnectionKey, Deque[Tuple[ResponseHandler, float]]
        ] = defaultdict(deque)
        self._limit = limit
        self._limit_per_host = limit_per_host
        self._acquired: Set[ResponseHandler] = set()
        self._acquired_per_host: DefaultDict[ConnectionKey, Set[ResponseHandler]] = (
            defaultdict(set)
        )
        self._keepalive_timeout = cast(float, keepalive_timeout)
        self._force_close = force_close

        # {host_key: FIFO list of waiters}
        # The FIFO is implemented with an OrderedDict with None keys because
        # python does not have an ordered set.
        self._waiters: DefaultDict[
            ConnectionKey, OrderedDict[asyncio.Future[None], None]
        ] = defaultdict(OrderedDict)

        self._loop = loop
        self._factory = functools.partial(ResponseHandler, loop=loop)

        # start keep-alive connection cleanup task
        self._cleanup_handle: Optional[asyncio.TimerHandle] = None

        # start cleanup closed transports task
        self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None
        self._cleanup_closed_disabled = not enable_cleanup_closed
        self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = []
        self._cleanup_closed()

    def __del__(self, _warnings: Any = warnings) -> None:
        if self._closed:
            return
        if not self._conns:
            return

        conns = [repr(c) for c in self._conns.values()]

        self._close()

        kwargs = {"source": self}
        _warnings.warn(f"Unclosed connector {self!r}", ResourceWarning, **kwargs)
        context = {
            "connector": self,
            "connections": conns,
            "message": "Unclosed connector",
        }
        if self._source_traceback is not None:
            context["source_traceback"] = self._source_traceback
        self._loop.call_exception_handler(context)

    def __enter__(self) -> "BaseConnector":
        warnings.warn(
            '"with Connector():" is deprecated, '
            'use "async with Connector():" instead',
            DeprecationWarning,
        )
        return self

    def __exit__(self, *exc: Any) -> None:
        self._close()

    async def __aenter__(self) -> "BaseConnector":
        return self

    async def __aexit__(
        self,
        exc_type: Optional[Type[BaseException]] = None,
        exc_value: Optional[BaseException] = None,
        exc_traceback: Optional[TracebackType] = None,
    ) -> None:
        await self.close()

    @property
    def force_close(self) -> bool:
        """Ultimately close connection on releasing if True."""
        return self._force_close

    @property
    def limit(self) -> int:
        """The total number for simultaneous connections.

        If limit is 0 the connector has no limit.
        The default limit size is 100.
        """
        return self._limit

    @property
    def limit_per_host(self) -> int:
        """The limit for simultaneous connections to the same endpoint.

        Endpoints are the same if they are have equal
        (host, port, is_ssl) triple.
        """
        return self._limit_per_host

    def _cleanup(self) -> None:
        """Cleanup unused transports."""
        if self._cleanup_handle:
            self._cleanup_handle.cancel()
            # _cleanup_handle should be unset, otherwise _release() will not
            # recreate it ever!
            self._cleanup_handle = None

        now = monotonic()
        timeout = self._keepalive_timeout

        if self._conns:
            connections = defaultdict(deque)
            deadline = now - timeout
            for key, conns in self._conns.items():
                alive: Deque[Tuple[ResponseHandler, float]] = deque()
                for proto, use_time in conns:
                    if proto.is_connected() and use_time - deadline >= 0:
                        alive.append((proto, use_time))
                        continue
                    transport = proto.transport
                    proto.close()
                    if not self._cleanup_closed_disabled and key.is_ssl:
                        self._cleanup_closed_transports.append(transport)

                if alive:
                    connections[key] = alive

            self._conns = connections

        if self._conns:
            self._cleanup_handle = helpers.weakref_handle(
                self,
                "_cleanup",
                timeout,
                self._loop,
                timeout_ceil_threshold=self._timeout_ceil_threshold,
            )

    def _cleanup_closed(self) -> None:
        """Double confirmation for transport close.

        Some broken ssl servers may leave socket open without proper close.
        """
        if self._cleanup_closed_handle:
            self._cleanup_closed_handle.cancel()

        for transport in self._cleanup_closed_transports:
            if transport is not None:
                transport.abort()

        self._cleanup_closed_transports = []

        if not self._cleanup_closed_disabled:
            self._cleanup_closed_handle = helpers.weakref_handle(
                self,
                "_cleanup_closed",
                self._cleanup_closed_period,
                self._loop,
                timeout_ceil_threshold=self._timeout_ceil_threshold,
            )

    def close(self) -> Awaitable[None]:
        """Close all opened transports."""
        self._close()
        return _DeprecationWaiter(noop())

    def _close(self) -> None:
        if self._closed:
            return

        self._closed = True

        try:
            if self._loop.is_closed():
                return

            # cancel cleanup task
            if self._cleanup_handle:
                self._cleanup_handle.cancel()

            # cancel cleanup close task
            if self._cleanup_closed_handle:
                self._cleanup_closed_handle.cancel()

            for data in self._conns.values():
                for proto, t0 in data:
                    proto.close()

            for proto in self._acquired:
                proto.close()

            for transport in self._cleanup_closed_transports:
                if transport is not None:
                    transport.abort()

        finally:
            self._conns.clear()
            self._acquired.clear()
            for keyed_waiters in self._waiters.values():
                for keyed_waiter in keyed_waiters:
                    keyed_waiter.cancel()
            self._waiters.clear()
            self._cleanup_handle = None
            self._cleanup_closed_transports.clear()
            self._cleanup_closed_handle = None

    @property
    def closed(self) -> bool:
        """Is connector closed.

        A readonly property.
        """
        return self._closed

    def _available_connections(self, key: "ConnectionKey") -> int:
        """
        Return number of available connections.

        The limit, limit_per_host and the connection key are taken into account.

        If it returns less than 1 means that there are no connections
        available.
        """
        # check total available connections
        # If there are no limits, this will always return 1
        total_remain = 1

        if self._limit and (total_remain := self._limit - len(self._acquired)) <= 0:
            return total_remain

        # check limit per host
        if host_remain := self._limit_per_host:
            if acquired := self._acquired_per_host.get(key):
                host_remain -= len(acquired)
            if total_remain > host_remain:
                return host_remain

        return total_remain

    async def connect(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> Connection:
        """Get from pool or create new connection."""
        key = req.connection_key
        if (conn := await self._get(key, traces)) is not None:
            # If we do not have to wait and we can get a connection from the pool
            # we can avoid the timeout ceil logic and directly return the connection
            return conn

        async with ceil_timeout(timeout.connect, timeout.ceil_threshold):
            if self._available_connections(key) <= 0:
                await self._wait_for_available_connection(key, traces)
                if (conn := await self._get(key, traces)) is not None:
                    return conn

            placeholder = cast(ResponseHandler, _TransportPlaceholder())
            self._acquired.add(placeholder)
            self._acquired_per_host[key].add(placeholder)

            try:
                # Traces are done inside the try block to ensure that the
                # that the placeholder is still cleaned up if an exception
                # is raised.
                if traces:
                    for trace in traces:
                        await trace.send_connection_create_start()
                proto = await self._create_connection(req, traces, timeout)
                if traces:
                    for trace in traces:
                        await trace.send_connection_create_end()
            except BaseException:
                self._release_acquired(key, placeholder)
                raise
            else:
                if self._closed:
                    proto.close()
                    raise ClientConnectionError("Connector is closed.")

        # The connection was successfully created, drop the placeholder
        # and add the real connection to the acquired set. There should
        # be no awaits after the proto is added to the acquired set
        # to ensure that the connection is not left in the acquired set
        # on cancellation.
        acquired_per_host = self._acquired_per_host[key]
        self._acquired.remove(placeholder)
        acquired_per_host.remove(placeholder)
        self._acquired.add(proto)
        acquired_per_host.add(proto)
        return Connection(self, key, proto, self._loop)

    async def _wait_for_available_connection(
        self, key: "ConnectionKey", traces: List["Trace"]
    ) -> None:
        """Wait for an available connection slot."""
        # We loop here because there is a race between
        # the connection limit check and the connection
        # being acquired. If the connection is acquired
        # between the check and the await statement, we
        # need to loop again to check if the connection
        # slot is still available.
        attempts = 0
        while True:
            fut: asyncio.Future[None] = self._loop.create_future()
            keyed_waiters = self._waiters[key]
            keyed_waiters[fut] = None
            if attempts:
                # If we have waited before, we need to move the waiter
                # to the front of the queue as otherwise we might get
                # starved and hit the timeout.
                keyed_waiters.move_to_end(fut, last=False)

            try:
                # Traces happen in the try block to ensure that the
                # the waiter is still cleaned up if an exception is raised.
                if traces:
                    for trace in traces:
                        await trace.send_connection_queued_start()
                await fut
                if traces:
                    for trace in traces:
                        await trace.send_connection_queued_end()
            finally:
                # pop the waiter from the queue if its still
                # there and not already removed by _release_waiter
                keyed_waiters.pop(fut, None)
                if not self._waiters.get(key, True):
                    del self._waiters[key]

            if self._available_connections(key) > 0:
                break
            attempts += 1

    async def _get(
        self, key: "ConnectionKey", traces: List["Trace"]
    ) -> Optional[Connection]:
        """Get next reusable connection for the key or None.

        The connection will be marked as acquired.
        """
        if (conns := self._conns.get(key)) is None:
            return None

        t1 = monotonic()
        while conns:
            proto, t0 = conns.popleft()
            # We will we reuse the connection if its connected and
            # the keepalive timeout has not been exceeded
            if proto.is_connected() and t1 - t0 <= self._keepalive_timeout:
                if not conns:
                    # The very last connection was reclaimed: drop the key
                    del self._conns[key]
                self._acquired.add(proto)
                self._acquired_per_host[key].add(proto)
                if traces:
                    for trace in traces:
                        try:
                            await trace.send_connection_reuseconn()
                        except BaseException:
                            self._release_acquired(key, proto)
                            raise
                return Connection(self, key, proto, self._loop)

            # Connection cannot be reused, close it
            transport = proto.transport
            proto.close()
            # only for SSL transports
            if not self._cleanup_closed_disabled and key.is_ssl:
                self._cleanup_closed_transports.append(transport)

        # No more connections: drop the key
        del self._conns[key]
        return None

    def _release_waiter(self) -> None:
        """
        Iterates over all waiters until one to be released is found.

        The one to be released is not finished and
        belongs to a host that has available connections.
        """
        if not self._waiters:
            return

        # Having the dict keys ordered this avoids to iterate
        # at the same order at each call.
        queues = list(self._waiters)
        random.shuffle(queues)

        for key in queues:
            if self._available_connections(key) < 1:
                continue

            waiters = self._waiters[key]
            while waiters:
                waiter, _ = waiters.popitem(last=False)
                if not waiter.done():
                    waiter.set_result(None)
                    return

    def _release_acquired(self, key: "ConnectionKey", proto: ResponseHandler) -> None:
        """Release acquired connection."""
        if self._closed:
            # acquired connection is already released on connector closing
            return

        self._acquired.discard(proto)
        if conns := self._acquired_per_host.get(key):
            conns.discard(proto)
            if not conns:
                del self._acquired_per_host[key]
        self._release_waiter()

    def _release(
        self,
        key: "ConnectionKey",
        protocol: ResponseHandler,
        *,
        should_close: bool = False,
    ) -> None:
        if self._closed:
            # acquired connection is already released on connector closing
            return

        self._release_acquired(key, protocol)

        if self._force_close:
            should_close = True

        if should_close or protocol.should_close:
            transport = protocol.transport
            protocol.close()

            if key.is_ssl and not self._cleanup_closed_disabled:
                self._cleanup_closed_transports.append(transport)
            return

        self._conns[key].append((protocol, monotonic()))

        if self._cleanup_handle is None:
            self._cleanup_handle = helpers.weakref_handle(
                self,
                "_cleanup",
                self._keepalive_timeout,
                self._loop,
                timeout_ceil_threshold=self._timeout_ceil_threshold,
            )

    async def _create_connection(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> ResponseHandler:
        raise NotImplementedError()


class _DNSCacheTable:
    def __init__(self, ttl: Optional[float] = None) -> None:
        self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[ResolveResult], int]] = {}
        self._timestamps: Dict[Tuple[str, int], float] = {}
        self._ttl = ttl

    def __contains__(self, host: object) -> bool:
        return host in self._addrs_rr

    def add(self, key: Tuple[str, int], addrs: List[ResolveResult]) -> None:
        self._addrs_rr[key] = (cycle(addrs), len(addrs))

        if self._ttl is not None:
            self._timestamps[key] = monotonic()

    def remove(self, key: Tuple[str, int]) -> None:
        self._addrs_rr.pop(key, None)

        if self._ttl is not None:
            self._timestamps.pop(key, None)

    def clear(self) -> None:
        self._addrs_rr.clear()
        self._timestamps.clear()

    def next_addrs(self, key: Tuple[str, int]) -> List[ResolveResult]:
        loop, length = self._addrs_rr[key]
        addrs = list(islice(loop, length))
        # Consume one more element to shift internal state of `cycle`
        next(loop)
        return addrs

    def expired(self, key: Tuple[str, int]) -> bool:
        if self._ttl is None:
            return False

        return self._timestamps[key] + self._ttl < monotonic()


def _make_ssl_context(verified: bool) -> SSLContext:
    """Create SSL context.

    This method is not async-friendly and should be called from a thread
    because it will load certificates from disk and do other blocking I/O.
    """
    if ssl is None:
        # No ssl support
        return None
    if verified:
        return ssl.create_default_context()
    sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    sslcontext.options |= ssl.OP_NO_SSLv2
    sslcontext.options |= ssl.OP_NO_SSLv3
    sslcontext.check_hostname = False
    sslcontext.verify_mode = ssl.CERT_NONE
    sslcontext.options |= ssl.OP_NO_COMPRESSION
    sslcontext.set_default_verify_paths()
    return sslcontext


# The default SSLContext objects are created at import time
# since they do blocking I/O to load certificates from disk,
# and imports should always be done before the event loop starts
# or in a thread.
_SSL_CONTEXT_VERIFIED = _make_ssl_context(True)
_SSL_CONTEXT_UNVERIFIED = _make_ssl_context(False)


class TCPConnector(BaseConnector):
    """TCP connector.

    verify_ssl - Set to True to check ssl certifications.
    fingerprint - Pass the binary sha256
        digest of the expected certificate in DER format to verify
        that the certificate the server presents matches. See also
        https://en.wikipedia.org/wiki/HTTP_Public_Key_Pinning
    resolver - Enable DNS lookups and use this
        resolver
    use_dns_cache - Use memory cache for DNS lookups.
    ttl_dns_cache - Max seconds having cached a DNS entry, None forever.
    family - socket address family
    local_addr - local tuple of (host, port) to bind socket to

    keepalive_timeout - (optional) Keep-alive timeout.
    force_close - Set to True to force close and do reconnect
        after each request (and between redirects).
    limit - The total number of simultaneous connections.
    limit_per_host - Number of simultaneous connections to one host.
    enable_cleanup_closed - Enables clean-up closed ssl transports.
                            Disabled by default.
    happy_eyeballs_delay - This is the “Connection Attempt Delay”
                           as defined in RFC 8305. To disable
                           the happy eyeballs algorithm, set to None.
    interleave - “First Address Family Count” as defined in RFC 8305
    loop - Optional event loop.
    """

    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"tcp"})

    def __init__(
        self,
        *,
        verify_ssl: bool = True,
        fingerprint: Optional[bytes] = None,
        use_dns_cache: bool = True,
        ttl_dns_cache: Optional[int] = 10,
        family: socket.AddressFamily = socket.AddressFamily.AF_UNSPEC,
        ssl_context: Optional[SSLContext] = None,
        ssl: Union[bool, Fingerprint, SSLContext] = True,
        local_addr: Optional[Tuple[str, int]] = None,
        resolver: Optional[AbstractResolver] = None,
        keepalive_timeout: Union[None, float, object] = sentinel,
        force_close: bool = False,
        limit: int = 100,
        limit_per_host: int = 0,
        enable_cleanup_closed: bool = False,
        loop: Optional[asyncio.AbstractEventLoop] = None,
        timeout_ceil_threshold: float = 5,
        happy_eyeballs_delay: Optional[float] = 0.25,
        interleave: Optional[int] = None,
    ):
        super().__init__(
            keepalive_timeout=keepalive_timeout,
            force_close=force_close,
            limit=limit,
            limit_per_host=limit_per_host,
            enable_cleanup_closed=enable_cleanup_closed,
            loop=loop,
            timeout_ceil_threshold=timeout_ceil_threshold,
        )

        self._ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)
        if resolver is None:
            resolver = DefaultResolver(loop=self._loop)
        self._resolver = resolver

        self._use_dns_cache = use_dns_cache
        self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache)
        self._throttle_dns_futures: Dict[
            Tuple[str, int], Set["asyncio.Future[None]"]
        ] = {}
        self._family = family
        self._local_addr_infos = aiohappyeyeballs.addr_to_addr_infos(local_addr)
        self._happy_eyeballs_delay = happy_eyeballs_delay
        self._interleave = interleave
        self._resolve_host_tasks: Set["asyncio.Task[List[ResolveResult]]"] = set()

    def close(self) -> Awaitable[None]:
        """Close all ongoing DNS calls."""
        for fut in chain.from_iterable(self._throttle_dns_futures.values()):
            fut.cancel()

        for t in self._resolve_host_tasks:
            t.cancel()

        return super().close()

    @property
    def family(self) -> int:
        """Socket family like AF_INET."""
        return self._family

    @property
    def use_dns_cache(self) -> bool:
        """True if local DNS caching is enabled."""
        return self._use_dns_cache

    def clear_dns_cache(
        self, host: Optional[str] = None, port: Optional[int] = None
    ) -> None:
        """Remove specified host/port or clear all dns local cache."""
        if host is not None and port is not None:
            self._cached_hosts.remove((host, port))
        elif host is not None or port is not None:
            raise ValueError("either both host and port or none of them are allowed")
        else:
            self._cached_hosts.clear()

    async def _resolve_host(
        self, host: str, port: int, traces: Optional[Sequence["Trace"]] = None
    ) -> List[ResolveResult]:
        """Resolve host and return list of addresses."""
        if is_ip_address(host):
            return [
                {
                    "hostname": host,
                    "host": host,
                    "port": port,
                    "family": self._family,
                    "proto": 0,
                    "flags": 0,
                }
            ]

        if not self._use_dns_cache:

            if traces:
                for trace in traces:
                    await trace.send_dns_resolvehost_start(host)

            res = await self._resolver.resolve(host, port, family=self._family)

            if traces:
                for trace in traces:
                    await trace.send_dns_resolvehost_end(host)

            return res

        key = (host, port)
        if key in self._cached_hosts and not self._cached_hosts.expired(key):
            # get result early, before any await (#4014)
            result = self._cached_hosts.next_addrs(key)

            if traces:
                for trace in traces:
                    await trace.send_dns_cache_hit(host)
            return result

        futures: Set["asyncio.Future[None]"]
        #
        # If multiple connectors are resolving the same host, we wait
        # for the first one to resolve and then use the result for all of them.
        # We use a throttle to ensure that we only resolve the host once
        # and then use the result for all the waiters.
        #
        if key in self._throttle_dns_futures:
            # get futures early, before any await (#4014)
            futures = self._throttle_dns_futures[key]
            future: asyncio.Future[None] = self._loop.create_future()
            futures.add(future)
            if traces:
                for trace in traces:
                    await trace.send_dns_cache_hit(host)
            try:
                await future
            finally:
                futures.discard(future)
            return self._cached_hosts.next_addrs(key)

        # update dict early, before any await (#4014)
        self._throttle_dns_futures[key] = futures = set()
        # In this case we need to create a task to ensure that we can shield
        # the task from cancellation as cancelling this lookup should not cancel
        # the underlying lookup or else the cancel event will get broadcast to
        # all the waiters across all connections.
        #
        coro = self._resolve_host_with_throttle(key, host, port, futures, traces)
        loop = asyncio.get_running_loop()
        if sys.version_info >= (3, 12):
            # Optimization for Python 3.12, try to send immediately
            resolved_host_task = asyncio.Task(coro, loop=loop, eager_start=True)
        else:
            resolved_host_task = loop.create_task(coro)

        if not resolved_host_task.done():
            self._resolve_host_tasks.add(resolved_host_task)
            resolved_host_task.add_done_callback(self._resolve_host_tasks.discard)

        try:
            return await asyncio.shield(resolved_host_task)
        except asyncio.CancelledError:

            def drop_exception(fut: "asyncio.Future[List[ResolveResult]]") -> None:
                with suppress(Exception, asyncio.CancelledError):
                    fut.result()

            resolved_host_task.add_done_callback(drop_exception)
            raise

    async def _resolve_host_with_throttle(
        self,
        key: Tuple[str, int],
        host: str,
        port: int,
        futures: Set["asyncio.Future[None]"],
        traces: Optional[Sequence["Trace"]],
    ) -> List[ResolveResult]:
        """Resolve host and set result for all waiters.

        This method must be run in a task and shielded from cancellation
        to avoid cancelling the underlying lookup.
        """
        if traces:
            for trace in traces:
                await trace.send_dns_cache_miss(host)
        try:
            if traces:
                for trace in traces:
                    await trace.send_dns_resolvehost_start(host)

            addrs = await self._resolver.resolve(host, port, family=self._family)
            if traces:
                for trace in traces:
                    await trace.send_dns_resolvehost_end(host)

            self._cached_hosts.add(key, addrs)
            for fut in futures:
                set_result(fut, None)
        except BaseException as e:
            # any DNS exception is set for the waiters to raise the same exception.
            # This coro is always run in task that is shielded from cancellation so
            # we should never be propagating cancellation here.
            for fut in futures:
                set_exception(fut, e)
            raise
        finally:
            self._throttle_dns_futures.pop(key)

        return self._cached_hosts.next_addrs(key)

    async def _create_connection(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> ResponseHandler:
        """Create connection.

        Has same keyword arguments as BaseEventLoop.create_connection.
        """
        if req.proxy:
            _, proto = await self._create_proxy_connection(req, traces, timeout)
        else:
            _, proto = await self._create_direct_connection(req, traces, timeout)

        return proto

    def _get_ssl_context(self, req: ClientRequest) -> Optional[SSLContext]:
        """Logic to get the correct SSL context

        0. if req.ssl is false, return None

        1. if ssl_context is specified in req, use it
        2. if _ssl_context is specified in self, use it
        3. otherwise:
            1. if verify_ssl is not specified in req, use self.ssl_context
               (will generate a default context according to self.verify_ssl)
            2. if verify_ssl is True in req, generate a default SSL context
            3. if verify_ssl is False in req, generate a SSL context that
               won't verify
        """
        if not req.is_ssl():
            return None

        if ssl is None:  # pragma: no cover
            raise RuntimeError("SSL is not supported.")
        sslcontext = req.ssl
        if isinstance(sslcontext, ssl.SSLContext):
            return sslcontext
        if sslcontext is not True:
            # not verified or fingerprinted
            return _SSL_CONTEXT_UNVERIFIED
        sslcontext = self._ssl
        if isinstance(sslcontext, ssl.SSLContext):
            return sslcontext
        if sslcontext is not True:
            # not verified or fingerprinted
            return _SSL_CONTEXT_UNVERIFIED
        return _SSL_CONTEXT_VERIFIED

    def _get_fingerprint(self, req: ClientRequest) -> Optional["Fingerprint"]:
        ret = req.ssl
        if isinstance(ret, Fingerprint):
            return ret
        ret = self._ssl
        if isinstance(ret, Fingerprint):
            return ret
        return None

    async def _wrap_create_connection(
        self,
        *args: Any,
        addr_infos: List[aiohappyeyeballs.AddrInfoType],
        req: ClientRequest,
        timeout: "ClientTimeout",
        client_error: Type[Exception] = ClientConnectorError,
        **kwargs: Any,
    ) -> Tuple[asyncio.Transport, ResponseHandler]:
        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                sock = await aiohappyeyeballs.start_connection(
                    addr_infos=addr_infos,
                    local_addr_infos=self._local_addr_infos,
                    happy_eyeballs_delay=self._happy_eyeballs_delay,
                    interleave=self._interleave,
                    loop=self._loop,
                )
                return await self._loop.create_connection(*args, **kwargs, sock=sock)
        except cert_errors as exc:
            raise ClientConnectorCertificateError(req.connection_key, exc) from exc
        except ssl_errors as exc:
            raise ClientConnectorSSLError(req.connection_key, exc) from exc
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            raise client_error(req.connection_key, exc) from exc

    async def _wrap_existing_connection(
        self,
        *args: Any,
        req: ClientRequest,
        timeout: "ClientTimeout",
        client_error: Type[Exception] = ClientConnectorError,
        **kwargs: Any,
    ) -> Tuple[asyncio.Transport, ResponseHandler]:
        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                return await self._loop.create_connection(*args, **kwargs)
        except cert_errors as exc:
            raise ClientConnectorCertificateError(req.connection_key, exc) from exc
        except ssl_errors as exc:
            raise ClientConnectorSSLError(req.connection_key, exc) from exc
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            raise client_error(req.connection_key, exc) from exc

    def _fail_on_no_start_tls(self, req: "ClientRequest") -> None:
        """Raise a :py:exc:`RuntimeError` on missing ``start_tls()``.

        It is necessary for TLS-in-TLS so that it is possible to
        send HTTPS queries through HTTPS proxies.

        This doesn't affect regular HTTP requests, though.
        """
        if not req.is_ssl():
            return

        proxy_url = req.proxy
        assert proxy_url is not None
        if proxy_url.scheme != "https":
            return

        self._check_loop_for_start_tls()

    def _check_loop_for_start_tls(self) -> None:
        try:
            self._loop.start_tls
        except AttributeError as attr_exc:
            raise RuntimeError(
                "An HTTPS request is being sent through an HTTPS proxy. "
                "This needs support for TLS in TLS but it is not implemented "
                "in your runtime for the stdlib asyncio.\n\n"
                "Please upgrade to Python 3.11 or higher. For more details, "
                "please see:\n"
                "* https://bugs.python.org/issue37179\n"
                "* https://github.com/python/cpython/pull/28073\n"
                "* https://docs.aiohttp.org/en/stable/"
                "client_advanced.html#proxy-support\n"
                "* https://github.com/aio-libs/aiohttp/discussions/6044\n",
            ) from attr_exc

    def _loop_supports_start_tls(self) -> bool:
        try:
            self._check_loop_for_start_tls()
        except RuntimeError:
            return False
        else:
            return True

    def _warn_about_tls_in_tls(
        self,
        underlying_transport: asyncio.Transport,
        req: ClientRequest,
    ) -> None:
        """Issue a warning if the requested URL has HTTPS scheme."""
        if req.request_info.url.scheme != "https":
            return

        asyncio_supports_tls_in_tls = getattr(
            underlying_transport,
            "_start_tls_compatible",
            False,
        )

        if asyncio_supports_tls_in_tls:
            return

        warnings.warn(
            "An HTTPS request is being sent through an HTTPS proxy. "
            "This support for TLS in TLS is known to be disabled "
            "in the stdlib asyncio (Python <3.11). This is why you'll probably see "
            "an error in the log below.\n\n"
            "It is possible to enable it via monkeypatching. "
            "For more details, see:\n"
            "* https://bugs.python.org/issue37179\n"
            "* https://github.com/python/cpython/pull/28073\n\n"
            "You can temporarily patch this as follows:\n"
            "* https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support\n"
            "* https://github.com/aio-libs/aiohttp/discussions/6044\n",
            RuntimeWarning,
            source=self,
            # Why `4`? At least 3 of the calls in the stack originate
            # from the methods in this class.
            stacklevel=3,
        )

    async def _start_tls_connection(
        self,
        underlying_transport: asyncio.Transport,
        req: ClientRequest,
        timeout: "ClientTimeout",
        client_error: Type[Exception] = ClientConnectorError,
    ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
        """Wrap the raw TCP transport with TLS."""
        tls_proto = self._factory()  # Create a brand new proto for TLS
        sslcontext = self._get_ssl_context(req)
        if TYPE_CHECKING:
            # _start_tls_connection is unreachable in the current code path
            # if sslcontext is None.
            assert sslcontext is not None

        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                try:
                    tls_transport = await self._loop.start_tls(
                        underlying_transport,
                        tls_proto,
                        sslcontext,
                        server_hostname=req.server_hostname or req.host,
                        ssl_handshake_timeout=timeout.total,
                    )
                except BaseException:
                    # We need to close the underlying transport since
                    # `start_tls()` probably failed before it had a
                    # chance to do this:
                    underlying_transport.close()
                    raise
                if isinstance(tls_transport, asyncio.Transport):
                    fingerprint = self._get_fingerprint(req)
                    if fingerprint:
                        try:
                            fingerprint.check(tls_transport)
                        except ServerFingerprintMismatch:
                            tls_transport.close()
                            if not self._cleanup_closed_disabled:
                                self._cleanup_closed_transports.append(tls_transport)
                            raise
        except cert_errors as exc:
            raise ClientConnectorCertificateError(req.connection_key, exc) from exc
        except ssl_errors as exc:
            raise ClientConnectorSSLError(req.connection_key, exc) from exc
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            raise client_error(req.connection_key, exc) from exc
        except TypeError as type_err:
            # Example cause looks like this:
            # TypeError: transport <asyncio.sslproto._SSLProtocolTransport
            # object at 0x7f760615e460> is not supported by start_tls()

            raise ClientConnectionError(
                "Cannot initialize a TLS-in-TLS connection to host "
                f"{req.host!s}:{req.port:d} through an underlying connection "
                f"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} "
                f"[{type_err!s}]"
            ) from type_err
        else:
            if tls_transport is None:
                msg = "Failed to start TLS (possibly caused by closing transport)"
                raise client_error(req.connection_key, OSError(msg))
            tls_proto.connection_made(
                tls_transport
            )  # Kick the state machine of the new TLS protocol

        return tls_transport, tls_proto

    def _convert_hosts_to_addr_infos(
        self, hosts: List[ResolveResult]
    ) -> List[aiohappyeyeballs.AddrInfoType]:
        """Converts the list of hosts to a list of addr_infos.

        The list of hosts is the result of a DNS lookup. The list of
        addr_infos is the result of a call to `socket.getaddrinfo()`.
        """
        addr_infos: List[aiohappyeyeballs.AddrInfoType] = []
        for hinfo in hosts:
            host = hinfo["host"]
            is_ipv6 = ":" in host
            family = socket.AF_INET6 if is_ipv6 else socket.AF_INET
            if self._family and self._family != family:
                continue
            addr = (host, hinfo["port"], 0, 0) if is_ipv6 else (host, hinfo["port"])
            addr_infos.append(
                (family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", addr)
            )
        return addr_infos

    async def _create_direct_connection(
        self,
        req: ClientRequest,
        traces: List["Trace"],
        timeout: "ClientTimeout",
        *,
        client_error: Type[Exception] = ClientConnectorError,
    ) -> Tuple[asyncio.Transport, ResponseHandler]:
        sslcontext = self._get_ssl_context(req)
        fingerprint = self._get_fingerprint(req)

        host = req.url.raw_host
        assert host is not None
        # Replace multiple trailing dots with a single one.
        # A trailing dot is only present for fully-qualified domain names.
        # See https://github.com/aio-libs/aiohttp/pull/7364.
        if host.endswith(".."):
            host = host.rstrip(".") + "."
        port = req.port
        assert port is not None
        try:
            # Cancelling this lookup should not cancel the underlying lookup
            #  or else the cancel event will get broadcast to all the waiters
            #  across all connections.
            hosts = await self._resolve_host(host, port, traces=traces)
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            # in case of proxy it is not ClientProxyConnectionError
            # it is problem of resolving proxy ip itself
            raise ClientConnectorDNSError(req.connection_key, exc) from exc

        last_exc: Optional[Exception] = None
        addr_infos = self._convert_hosts_to_addr_infos(hosts)
        while addr_infos:
            # Strip trailing dots, certificates contain FQDN without dots.
            # See https://github.com/aio-libs/aiohttp/issues/3636
            server_hostname = (
                (req.server_hostname or host).rstrip(".") if sslcontext else None
            )

            try:
                transp, proto = await self._wrap_create_connection(
                    self._factory,
                    timeout=timeout,
                    ssl=sslcontext,
                    addr_infos=addr_infos,
                    server_hostname=server_hostname,
                    req=req,
                    client_error=client_error,
                )
            except (ClientConnectorError, asyncio.TimeoutError) as exc:
                last_exc = exc
                aiohappyeyeballs.pop_addr_infos_interleave(addr_infos, self._interleave)
                continue

            if req.is_ssl() and fingerprint:
                try:
                    fingerprint.check(transp)
                except ServerFingerprintMismatch as exc:
                    transp.close()
                    if not self._cleanup_closed_disabled:
                        self._cleanup_closed_transports.append(transp)
                    last_exc = exc
                    # Remove the bad peer from the list of addr_infos
                    sock: socket.socket = transp.get_extra_info("socket")
                    bad_peer = sock.getpeername()
                    aiohappyeyeballs.remove_addr_infos(addr_infos, bad_peer)
                    continue

            return transp, proto
        else:
            assert last_exc is not None
            raise last_exc

    async def _create_proxy_connection(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
        self._fail_on_no_start_tls(req)
        runtime_has_start_tls = self._loop_supports_start_tls()

        headers: Dict[str, str] = {}
        if req.proxy_headers is not None:
            headers = req.proxy_headers  # type: ignore[assignment]
        headers[hdrs.HOST] = req.headers[hdrs.HOST]

        url = req.proxy
        assert url is not None
        proxy_req = ClientRequest(
            hdrs.METH_GET,
            url,
            headers=headers,
            auth=req.proxy_auth,
            loop=self._loop,
            ssl=req.ssl,
        )

        # create connection to proxy server
        transport, proto = await self._create_direct_connection(
            proxy_req, [], timeout, client_error=ClientProxyConnectionError
        )

        auth = proxy_req.headers.pop(hdrs.AUTHORIZATION, None)
        if auth is not None:
            if not req.is_ssl():
                req.headers[hdrs.PROXY_AUTHORIZATION] = auth
            else:
                proxy_req.headers[hdrs.PROXY_AUTHORIZATION] = auth

        if req.is_ssl():
            if runtime_has_start_tls:
                self._warn_about_tls_in_tls(transport, req)

            # For HTTPS requests over HTTP proxy
            # we must notify proxy to tunnel connection
            # so we send CONNECT command:
            #   CONNECT www.python.org:443 HTTP/1.1
            #   Host: www.python.org
            #
            # next we must do TLS handshake and so on
            # to do this we must wrap raw socket into secure one
            # asyncio handles this perfectly
            proxy_req.method = hdrs.METH_CONNECT
            proxy_req.url = req.url
            key = req.connection_key._replace(
                proxy=None, proxy_auth=None, proxy_headers_hash=None
            )
            conn = Connection(self, key, proto, self._loop)
            proxy_resp = await proxy_req.send(conn)
            try:
                protocol = conn._protocol
                assert protocol is not None

                # read_until_eof=True will ensure the connection isn't closed
                # once the response is received and processed allowing
                # START_TLS to work on the connection below.
                protocol.set_response_params(
                    read_until_eof=runtime_has_start_tls,
                    timeout_ceil_threshold=self._timeout_ceil_threshold,
                )
                resp = await proxy_resp.start(conn)
            except BaseException:
                proxy_resp.close()
                conn.close()
                raise
            else:
                conn._protocol = None
                try:
                    if resp.status != 200:
                        message = resp.reason
                        if message is None:
                            message = HTTPStatus(resp.status).phrase
                        raise ClientHttpProxyError(
                            proxy_resp.request_info,
                            resp.history,
                            status=resp.status,
                            message=message,
                            headers=resp.headers,
                        )
                    if not runtime_has_start_tls:
                        rawsock = transport.get_extra_info("socket", default=None)
                        if rawsock is None:
                            raise RuntimeError(
                                "Transport does not expose socket instance"
                            )
                        # Duplicate the socket, so now we can close proxy transport
                        rawsock = rawsock.dup()
                except BaseException:
                    # It shouldn't be closed in `finally` because it's fed to
                    # `loop.start_tls()` and the docs say not to touch it after
                    # passing there.
                    transport.close()
                    raise
                finally:
                    if not runtime_has_start_tls:
                        transport.close()

                if not runtime_has_start_tls:
                    # HTTP proxy with support for upgrade to HTTPS
                    sslcontext = self._get_ssl_context(req)
                    return await self._wrap_existing_connection(
                        self._factory,
                        timeout=timeout,
                        ssl=sslcontext,
                        sock=rawsock,
                        server_hostname=req.host,
                        req=req,
                    )

                return await self._start_tls_connection(
                    # Access the old transport for the last time before it's
                    # closed and forgotten forever:
                    transport,
                    req=req,
                    timeout=timeout,
                )
            finally:
                proxy_resp.close()

        return transport, proto


class UnixConnector(BaseConnector):
    """Unix socket connector.

    path - Unix socket path.
    keepalive_timeout - (optional) Keep-alive timeout.
    force_close - Set to True to force close and do reconnect
        after each request (and between redirects).
    limit - The total number of simultaneous connections.
    limit_per_host - Number of simultaneous connections to one host.
    loop - Optional event loop.
    """

    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"unix"})

    def __init__(
        self,
        path: str,
        force_close: bool = False,
        keepalive_timeout: Union[object, float, None] = sentinel,
        limit: int = 100,
        limit_per_host: int = 0,
        loop: Optional[asyncio.AbstractEventLoop] = None,
    ) -> None:
        super().__init__(
            force_close=force_close,
            keepalive_timeout=keepalive_timeout,
            limit=limit,
            limit_per_host=limit_per_host,
            loop=loop,
        )
        self._path = path

    @property
    def path(self) -> str:
        """Path to unix socket."""
        return self._path

    async def _create_connection(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> ResponseHandler:
        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                _, proto = await self._loop.create_unix_connection(
                    self._factory, self._path
                )
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc

        return proto


class NamedPipeConnector(BaseConnector):
    """Named pipe connector.

    Only supported by the proactor event loop.
    See also: https://docs.python.org/3/library/asyncio-eventloop.html

    path - Windows named pipe path.
    keepalive_timeout - (optional) Keep-alive timeout.
    force_close - Set to True to force close and do reconnect
        after each request (and between redirects).
    limit - The total number of simultaneous connections.
    limit_per_host - Number of simultaneous connections to one host.
    loop - Optional event loop.
    """

    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"npipe"})

    def __init__(
        self,
        path: str,
        force_close: bool = False,
        keepalive_timeout: Union[object, float, None] = sentinel,
        limit: int = 100,
        limit_per_host: int = 0,
        loop: Optional[asyncio.AbstractEventLoop] = None,
    ) -> None:
        super().__init__(
            force_close=force_close,
            keepalive_timeout=keepalive_timeout,
            limit=limit,
            limit_per_host=limit_per_host,
            loop=loop,
        )
        if not isinstance(
            self._loop, asyncio.ProactorEventLoop  # type: ignore[attr-defined]
        ):
            raise RuntimeError(
                "Named Pipes only available in proactor loop under windows"
            )
        self._path = path

    @property
    def path(self) -> str:
        """Path to the named pipe."""
        return self._path

    async def _create_connection(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> ResponseHandler:
        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                _, proto = await self._loop.create_pipe_connection(  # type: ignore[attr-defined]
                    self._factory, self._path
                )
                # the drain is required so that the connection_made is called
                # and transport is set otherwise it is not set before the
                # `assert conn.transport is not None`
                # in client.py's _request method
                await asyncio.sleep(0)
                # other option is to manually set transport like
                # `proto.transport = trans`
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            raise ClientConnectorError(req.connection_key, exc) from exc

        return cast(ResponseHandler, proto)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** `Connection.release` method includes redundant `should_close` argument when calling connector's `_release`

**Description:**
When releasing a connection, the `Connection.release()` method unnecessarily passes the `should_close` parameter to the connector's `_release` method. This redundant argument causes issues where connector implementations expecting only `key` and `protocol` parameters fail or behave unexpectedly.

**Example Code:**
```python
connector = Connector()
key = 'unique_key'
protocol = Protocol()

connection = Connection(connector, key, protocol, loop)
connection.release()
```

**Expected Behavior:**
The `connector._release` method should be called with only `key` and `protocol`:
```python
connector._release(key, protocol)
```

**Actual Behavior:**
The `connector._release` method is called with an additional `should_close` argument:
```python
connector._release(key, protocol, should_close=protocol.should_close)
```
This extra argument leads to assertion failures or unexpected behavior in connector implementations that do not handle the `should_close` parameter.
[/ISSUE]
{
    "test_ctor": "PASSED",
    "test_callbacks_on_close": "PASSED",
    "test_callbacks_on_release": "PASSED",
    "test_callbacks_exception": "PASSED",
    "test_del": "PASSED",
    "test_close": "PASSED",
    "test_release": "PASSED",
    "test_release_proto_should_close": "PASSED",
    "test_release_released": "PASSED"
}
diff --git a/aiohttp/connector.py b/aiohttp/connector.py
index 03147cb3..282d0a97 100644
--- a/aiohttp/connector.py
+++ b/aiohttp/connector.py
@@ -186,9 +186,7 @@ class Connection:
         self._notify_release()
 
         if self._protocol is not None:
-            self._connector._release(
-                self._key, self._protocol, should_close=self._protocol.should_close
-            )
+            self._connector._release(self._key, self._protocol)
             self._protocol = None
 
     @property

{"aiohttp/connector.py": "import asyncio\nimport functools\nimport random\nimport socket\nimport sys\nimport traceback\nimport warnings\nfrom collections import OrderedDict, defaultdict, deque\nfrom contextlib import suppress\nfrom http import HTTPStatus\nfrom itertools import chain, cycle, islice\nfrom time import monotonic\nfrom types import TracebackType\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Awaitable,\n    Callable,\n    DefaultDict,\n    Deque,\n    Dict,\n    Iterator,\n    List,\n    Literal,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Type,\n    Union,\n    cast,\n)\n\nimport aiohappyeyeballs\n\nfrom . import hdrs, helpers\nfrom .abc import AbstractResolver, ResolveResult\nfrom .client_exceptions import (\n    ClientConnectionError,\n    ClientConnectorCertificateError,\n    ClientConnectorDNSError,\n    ClientConnectorError,\n    ClientConnectorSSLError,\n    ClientHttpProxyError,\n    ClientProxyConnectionError,\n    ServerFingerprintMismatch,\n    UnixClientConnectorError,\n    cert_errors,\n    ssl_errors,\n)\nfrom .client_proto import ResponseHandler\nfrom .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params\nfrom .helpers import (\n    ceil_timeout,\n    is_ip_address,\n    noop,\n    sentinel,\n    set_exception,\n    set_result,\n)\nfrom .resolver import DefaultResolver\n\ntry:\n    import ssl\n\n    SSLContext = ssl.SSLContext\nexcept ImportError:  # pragma: no cover\n    ssl = None  # type: ignore[assignment]\n    SSLContext = object  # type: ignore[misc,assignment]\n\n\nEMPTY_SCHEMA_SET = frozenset({\"\"})\nHTTP_SCHEMA_SET = frozenset({\"http\", \"https\"})\nWS_SCHEMA_SET = frozenset({\"ws\", \"wss\"})\n\nHTTP_AND_EMPTY_SCHEMA_SET = HTTP_SCHEMA_SET | EMPTY_SCHEMA_SET\nHIGH_LEVEL_SCHEMA_SET = HTTP_AND_EMPTY_SCHEMA_SET | WS_SCHEMA_SET\n\n\n__all__ = (\"BaseConnector\", \"TCPConnector\", \"UnixConnector\", \"NamedPipeConnector\")\n\n\nif TYPE_CHECKING:\n    from .client import ClientTimeout\n    from .client_reqrep import ConnectionKey\n    from .tracing import Trace\n\n\nclass _DeprecationWaiter:\n    __slots__ = (\"_awaitable\", \"_awaited\")\n\n    def __init__(self, awaitable: Awaitable[Any]) -> None:\n        self._awaitable = awaitable\n        self._awaited = False\n\n    def __await__(self) -> Any:\n        self._awaited = True\n        return self._awaitable.__await__()\n\n    def __del__(self) -> None:\n        if not self._awaited:\n            warnings.warn(\n                \"Connector.close() is a coroutine, \"\n                \"please use await connector.close()\",\n                DeprecationWarning,\n            )\n\n\nclass Connection:\n\n    _source_traceback = None\n\n    def __init__(\n        self,\n        connector: \"BaseConnector\",\n        key: \"ConnectionKey\",\n        protocol: ResponseHandler,\n        loop: asyncio.AbstractEventLoop,\n    ) -> None:\n        self._key = key\n        self._connector = connector\n        self._loop = loop\n        self._protocol: Optional[ResponseHandler] = protocol\n        self._callbacks: List[Callable[[], None]] = []\n\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n    def __repr__(self) -> str:\n        return f\"Connection<{self._key}>\"\n\n    def __del__(self, _warnings: Any = warnings) -> None:\n        if self._protocol is not None:\n            kwargs = {\"source\": self}\n            _warnings.warn(f\"Unclosed connection {self!r}\", ResourceWarning, **kwargs)\n            if self._loop.is_closed():\n                return\n\n            self._connector._release(self._key, self._protocol, should_close=True)\n\n            context = {\"client_connection\": self, \"message\": \"Unclosed connection\"}\n            if self._source_traceback is not None:\n                context[\"source_traceback\"] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def __bool__(self) -> Literal[True]:\n        \"\"\"Force subclasses to not be falsy, to make checks simpler.\"\"\"\n        return True\n\n    @property\n    def loop(self) -> asyncio.AbstractEventLoop:\n        warnings.warn(\n            \"connector.loop property is deprecated\", DeprecationWarning, stacklevel=2\n        )\n        return self._loop\n\n    @property\n    def transport(self) -> Optional[asyncio.Transport]:\n        if self._protocol is None:\n            return None\n        return self._protocol.transport\n\n    @property\n    def protocol(self) -> Optional[ResponseHandler]:\n        return self._protocol\n\n    def add_callback(self, callback: Callable[[], None]) -> None:\n        if callback is not None:\n            self._callbacks.append(callback)\n\n    def _notify_release(self) -> None:\n        callbacks, self._callbacks = self._callbacks[:], []\n\n        for cb in callbacks:\n            with suppress(Exception):\n                cb()\n\n    def close(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(self._key, self._protocol, should_close=True)\n            self._protocol = None\n\n    def release(self) -> None:\n        self._notify_release()\n\n        if self._protocol is not None:\n            self._connector._release(\n                self._key, self._protocol, should_close=self._protocol.should_close\n            )\n            self._protocol = None\n\n    @property\n    def closed(self) -> bool:\n        return self._protocol is None or not self._protocol.is_connected()\n\n\nclass _TransportPlaceholder:\n    \"\"\"placeholder for BaseConnector.connect function\"\"\"\n\n    __slots__ = ()\n\n    def close(self) -> None:\n        \"\"\"Close the placeholder transport.\"\"\"\n\n\nclass BaseConnector:\n    \"\"\"Base connector class.\n\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    enable_cleanup_closed - Enables clean-up closed ssl transports.\n                            Disabled by default.\n    timeout_ceil_threshold - Trigger ceiling of timeout values when\n                             it's above timeout_ceil_threshold.\n    loop - Optional event loop.\n    \"\"\"\n\n    _closed = True  # prevent AttributeError in __del__ if ctor was failed\n    _source_traceback = None\n\n    # abort transport after 2 seconds (cleanup broken connections)\n    _cleanup_closed_period = 2.0\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET\n\n    def __init__(\n        self,\n        *,\n        keepalive_timeout: Union[object, None, float] = sentinel,\n        force_close: bool = False,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        enable_cleanup_closed: bool = False,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n        timeout_ceil_threshold: float = 5,\n    ) -> None:\n\n        if force_close:\n            if keepalive_timeout is not None and keepalive_timeout is not sentinel:\n                raise ValueError(\n                    \"keepalive_timeout cannot be set if force_close is True\"\n                )\n        else:\n            if keepalive_timeout is sentinel:\n                keepalive_timeout = 15.0\n\n        loop = loop or asyncio.get_running_loop()\n        self._timeout_ceil_threshold = timeout_ceil_threshold\n\n        self._closed = False\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        # Connection pool of reusable connections.\n        # We use a deque to store connections because it has O(1) popleft()\n        # and O(1) append() operations to implement a FIFO queue.\n        self._conns: DefaultDict[\n            ConnectionKey, Deque[Tuple[ResponseHandler, float]]\n        ] = defaultdict(deque)\n        self._limit = limit\n        self._limit_per_host = limit_per_host\n        self._acquired: Set[ResponseHandler] = set()\n        self._acquired_per_host: DefaultDict[ConnectionKey, Set[ResponseHandler]] = (\n            defaultdict(set)\n        )\n        self._keepalive_timeout = cast(float, keepalive_timeout)\n        self._force_close = force_close\n\n        # {host_key: FIFO list of waiters}\n        # The FIFO is implemented with an OrderedDict with None keys because\n        # python does not have an ordered set.\n        self._waiters: DefaultDict[\n            ConnectionKey, OrderedDict[asyncio.Future[None], None]\n        ] = defaultdict(OrderedDict)\n\n        self._loop = loop\n        self._factory = functools.partial(ResponseHandler, loop=loop)\n\n        # start keep-alive connection cleanup task\n        self._cleanup_handle: Optional[asyncio.TimerHandle] = None\n\n        # start cleanup closed transports task\n        self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None\n        self._cleanup_closed_disabled = not enable_cleanup_closed\n        self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = []\n        self._cleanup_closed()\n\n    def __del__(self, _warnings: Any = warnings) -> None:\n        if self._closed:\n            return\n        if not self._conns:\n            return\n\n        conns = [repr(c) for c in self._conns.values()]\n\n        self._close()\n\n        kwargs = {\"source\": self}\n        _warnings.warn(f\"Unclosed connector {self!r}\", ResourceWarning, **kwargs)\n        context = {\n            \"connector\": self,\n            \"connections\": conns,\n            \"message\": \"Unclosed connector\",\n        }\n        if self._source_traceback is not None:\n            context[\"source_traceback\"] = self._source_traceback\n        self._loop.call_exception_handler(context)\n\n    def __enter__(self) -> \"BaseConnector\":\n        warnings.warn(\n            '\"with Connector():\" is deprecated, '\n            'use \"async with Connector():\" instead',\n            DeprecationWarning,\n        )\n        return self\n\n    def __exit__(self, *exc: Any) -> None:\n        self._close()\n\n    async def __aenter__(self) -> \"BaseConnector\":\n        return self\n\n    async def __aexit__(\n        self,\n        exc_type: Optional[Type[BaseException]] = None,\n        exc_value: Optional[BaseException] = None,\n        exc_traceback: Optional[TracebackType] = None,\n    ) -> None:\n        await self.close()\n\n    @property\n    def force_close(self) -> bool:\n        \"\"\"Ultimately close connection on releasing if True.\"\"\"\n        return self._force_close\n\n    @property\n    def limit(self) -> int:\n        \"\"\"The total number for simultaneous connections.\n\n        If limit is 0 the connector has no limit.\n        The default limit size is 100.\n        \"\"\"\n        return self._limit\n\n    @property\n    def limit_per_host(self) -> int:\n        \"\"\"The limit for simultaneous connections to the same endpoint.\n\n        Endpoints are the same if they are have equal\n        (host, port, is_ssl) triple.\n        \"\"\"\n        return self._limit_per_host\n\n    def _cleanup(self) -> None:\n        \"\"\"Cleanup unused transports.\"\"\"\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            # _cleanup_handle should be unset, otherwise _release() will not\n            # recreate it ever!\n            self._cleanup_handle = None\n\n        now = monotonic()\n        timeout = self._keepalive_timeout\n\n        if self._conns:\n            connections = defaultdict(deque)\n            deadline = now - timeout\n            for key, conns in self._conns.items():\n                alive: Deque[Tuple[ResponseHandler, float]] = deque()\n                for proto, use_time in conns:\n                    if proto.is_connected() and use_time - deadline >= 0:\n                        alive.append((proto, use_time))\n                        continue\n                    transport = proto.transport\n                    proto.close()\n                    if not self._cleanup_closed_disabled and key.is_ssl:\n                        self._cleanup_closed_transports.append(transport)\n\n                if alive:\n                    connections[key] = alive\n\n            self._conns = connections\n\n        if self._conns:\n            self._cleanup_handle = helpers.weakref_handle(\n                self,\n                \"_cleanup\",\n                timeout,\n                self._loop,\n                timeout_ceil_threshold=self._timeout_ceil_threshold,\n            )\n\n    def _cleanup_closed(self) -> None:\n        \"\"\"Double confirmation for transport close.\n\n        Some broken ssl servers may leave socket open without proper close.\n        \"\"\"\n        if self._cleanup_closed_handle:\n            self._cleanup_closed_handle.cancel()\n\n        for transport in self._cleanup_closed_transports:\n            if transport is not None:\n                transport.abort()\n\n        self._cleanup_closed_transports = []\n\n        if not self._cleanup_closed_disabled:\n            self._cleanup_closed_handle = helpers.weakref_handle(\n                self,\n                \"_cleanup_closed\",\n                self._cleanup_closed_period,\n                self._loop,\n                timeout_ceil_threshold=self._timeout_ceil_threshold,\n            )\n\n    def close(self) -> Awaitable[None]:\n        \"\"\"Close all opened transports.\"\"\"\n        self._close()\n        return _DeprecationWaiter(noop())\n\n    def _close(self) -> None:\n        if self._closed:\n            return\n\n        self._closed = True\n\n        try:\n            if self._loop.is_closed():\n                return\n\n            # cancel cleanup task\n            if self._cleanup_handle:\n                self._cleanup_handle.cancel()\n\n            # cancel cleanup close task\n            if self._cleanup_closed_handle:\n                self._cleanup_closed_handle.cancel()\n\n            for data in self._conns.values():\n                for proto, t0 in data:\n                    proto.close()\n\n            for proto in self._acquired:\n                proto.close()\n\n            for transport in self._cleanup_closed_transports:\n                if transport is not None:\n                    transport.abort()\n\n        finally:\n            self._conns.clear()\n            self._acquired.clear()\n            for keyed_waiters in self._waiters.values():\n                for keyed_waiter in keyed_waiters:\n                    keyed_waiter.cancel()\n            self._waiters.clear()\n            self._cleanup_handle = None\n            self._cleanup_closed_transports.clear()\n            self._cleanup_closed_handle = None\n\n    @property\n    def closed(self) -> bool:\n        \"\"\"Is connector closed.\n\n        A readonly property.\n        \"\"\"\n        return self._closed\n\n    def _available_connections(self, key: \"ConnectionKey\") -> int:\n        \"\"\"\n        Return number of available connections.\n\n        The limit, limit_per_host and the connection key are taken into account.\n\n        If it returns less than 1 means that there are no connections\n        available.\n        \"\"\"\n        # check total available connections\n        # If there are no limits, this will always return 1\n        total_remain = 1\n\n        if self._limit and (total_remain := self._limit - len(self._acquired)) <= 0:\n            return total_remain\n\n        # check limit per host\n        if host_remain := self._limit_per_host:\n            if acquired := self._acquired_per_host.get(key):\n                host_remain -= len(acquired)\n            if total_remain > host_remain:\n                return host_remain\n\n        return total_remain\n\n    async def connect(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> Connection:\n        \"\"\"Get from pool or create new connection.\"\"\"\n        key = req.connection_key\n        if (conn := await self._get(key, traces)) is not None:\n            # If we do not have to wait and we can get a connection from the pool\n            # we can avoid the timeout ceil logic and directly return the connection\n            return conn\n\n        async with ceil_timeout(timeout.connect, timeout.ceil_threshold):\n            if self._available_connections(key) <= 0:\n                await self._wait_for_available_connection(key, traces)\n                if (conn := await self._get(key, traces)) is not None:\n                    return conn\n\n            placeholder = cast(ResponseHandler, _TransportPlaceholder())\n            self._acquired.add(placeholder)\n            self._acquired_per_host[key].add(placeholder)\n\n            try:\n                # Traces are done inside the try block to ensure that the\n                # that the placeholder is still cleaned up if an exception\n                # is raised.\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_create_start()\n                proto = await self._create_connection(req, traces, timeout)\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_create_end()\n            except BaseException:\n                self._release_acquired(key, placeholder)\n                raise\n            else:\n                if self._closed:\n                    proto.close()\n                    raise ClientConnectionError(\"Connector is closed.\")\n\n        # The connection was successfully created, drop the placeholder\n        # and add the real connection to the acquired set. There should\n        # be no awaits after the proto is added to the acquired set\n        # to ensure that the connection is not left in the acquired set\n        # on cancellation.\n        acquired_per_host = self._acquired_per_host[key]\n        self._acquired.remove(placeholder)\n        acquired_per_host.remove(placeholder)\n        self._acquired.add(proto)\n        acquired_per_host.add(proto)\n        return Connection(self, key, proto, self._loop)\n\n    async def _wait_for_available_connection(\n        self, key: \"ConnectionKey\", traces: List[\"Trace\"]\n    ) -> None:\n        \"\"\"Wait for an available connection slot.\"\"\"\n        # We loop here because there is a race between\n        # the connection limit check and the connection\n        # being acquired. If the connection is acquired\n        # between the check and the await statement, we\n        # need to loop again to check if the connection\n        # slot is still available.\n        attempts = 0\n        while True:\n            fut: asyncio.Future[None] = self._loop.create_future()\n            keyed_waiters = self._waiters[key]\n            keyed_waiters[fut] = None\n            if attempts:\n                # If we have waited before, we need to move the waiter\n                # to the front of the queue as otherwise we might get\n                # starved and hit the timeout.\n                keyed_waiters.move_to_end(fut, last=False)\n\n            try:\n                # Traces happen in the try block to ensure that the\n                # the waiter is still cleaned up if an exception is raised.\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_queued_start()\n                await fut\n                if traces:\n                    for trace in traces:\n                        await trace.send_connection_queued_end()\n            finally:\n                # pop the waiter from the queue if its still\n                # there and not already removed by _release_waiter\n                keyed_waiters.pop(fut, None)\n                if not self._waiters.get(key, True):\n                    del self._waiters[key]\n\n            if self._available_connections(key) > 0:\n                break\n            attempts += 1\n\n    async def _get(\n        self, key: \"ConnectionKey\", traces: List[\"Trace\"]\n    ) -> Optional[Connection]:\n        \"\"\"Get next reusable connection for the key or None.\n\n        The connection will be marked as acquired.\n        \"\"\"\n        if (conns := self._conns.get(key)) is None:\n            return None\n\n        t1 = monotonic()\n        while conns:\n            proto, t0 = conns.popleft()\n            # We will we reuse the connection if its connected and\n            # the keepalive timeout has not been exceeded\n            if proto.is_connected() and t1 - t0 <= self._keepalive_timeout:\n                if not conns:\n                    # The very last connection was reclaimed: drop the key\n                    del self._conns[key]\n                self._acquired.add(proto)\n                self._acquired_per_host[key].add(proto)\n                if traces:\n                    for trace in traces:\n                        try:\n                            await trace.send_connection_reuseconn()\n                        except BaseException:\n                            self._release_acquired(key, proto)\n                            raise\n                return Connection(self, key, proto, self._loop)\n\n            # Connection cannot be reused, close it\n            transport = proto.transport\n            proto.close()\n            # only for SSL transports\n            if not self._cleanup_closed_disabled and key.is_ssl:\n                self._cleanup_closed_transports.append(transport)\n\n        # No more connections: drop the key\n        del self._conns[key]\n        return None\n\n    def _release_waiter(self) -> None:\n        \"\"\"\n        Iterates over all waiters until one to be released is found.\n\n        The one to be released is not finished and\n        belongs to a host that has available connections.\n        \"\"\"\n        if not self._waiters:\n            return\n\n        # Having the dict keys ordered this avoids to iterate\n        # at the same order at each call.\n        queues = list(self._waiters)\n        random.shuffle(queues)\n\n        for key in queues:\n            if self._available_connections(key) < 1:\n                continue\n\n            waiters = self._waiters[key]\n            while waiters:\n                waiter, _ = waiters.popitem(last=False)\n                if not waiter.done():\n                    waiter.set_result(None)\n                    return\n\n    def _release_acquired(self, key: \"ConnectionKey\", proto: ResponseHandler) -> None:\n        \"\"\"Release acquired connection.\"\"\"\n        if self._closed:\n            # acquired connection is already released on connector closing\n            return\n\n        self._acquired.discard(proto)\n        if conns := self._acquired_per_host.get(key):\n            conns.discard(proto)\n            if not conns:\n                del self._acquired_per_host[key]\n        self._release_waiter()\n\n    def _release(\n        self,\n        key: \"ConnectionKey\",\n        protocol: ResponseHandler,\n        *,\n        should_close: bool = False,\n    ) -> None:\n        if self._closed:\n            # acquired connection is already released on connector closing\n            return\n\n        self._release_acquired(key, protocol)\n\n        if self._force_close:\n            should_close = True\n\n        if should_close or protocol.should_close:\n            transport = protocol.transport\n            protocol.close()\n\n            if key.is_ssl and not self._cleanup_closed_disabled:\n                self._cleanup_closed_transports.append(transport)\n            return\n\n        self._conns[key].append((protocol, monotonic()))\n\n        if self._cleanup_handle is None:\n            self._cleanup_handle = helpers.weakref_handle(\n                self,\n                \"_cleanup\",\n                self._keepalive_timeout,\n                self._loop,\n                timeout_ceil_threshold=self._timeout_ceil_threshold,\n            )\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        raise NotImplementedError()\n\n\nclass _DNSCacheTable:\n    def __init__(self, ttl: Optional[float] = None) -> None:\n        self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[ResolveResult], int]] = {}\n        self._timestamps: Dict[Tuple[str, int], float] = {}\n        self._ttl = ttl\n\n    def __contains__(self, host: object) -> bool:\n        return host in self._addrs_rr\n\n    def add(self, key: Tuple[str, int], addrs: List[ResolveResult]) -> None:\n        self._addrs_rr[key] = (cycle(addrs), len(addrs))\n\n        if self._ttl is not None:\n            self._timestamps[key] = monotonic()\n\n    def remove(self, key: Tuple[str, int]) -> None:\n        self._addrs_rr.pop(key, None)\n\n        if self._ttl is not None:\n            self._timestamps.pop(key, None)\n\n    def clear(self) -> None:\n        self._addrs_rr.clear()\n        self._timestamps.clear()\n\n    def next_addrs(self, key: Tuple[str, int]) -> List[ResolveResult]:\n        loop, length = self._addrs_rr[key]\n        addrs = list(islice(loop, length))\n        # Consume one more element to shift internal state of `cycle`\n        next(loop)\n        return addrs\n\n    def expired(self, key: Tuple[str, int]) -> bool:\n        if self._ttl is None:\n            return False\n\n        return self._timestamps[key] + self._ttl < monotonic()\n\n\ndef _make_ssl_context(verified: bool) -> SSLContext:\n    \"\"\"Create SSL context.\n\n    This method is not async-friendly and should be called from a thread\n    because it will load certificates from disk and do other blocking I/O.\n    \"\"\"\n    if ssl is None:\n        # No ssl support\n        return None\n    if verified:\n        return ssl.create_default_context()\n    sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n    sslcontext.options |= ssl.OP_NO_SSLv2\n    sslcontext.options |= ssl.OP_NO_SSLv3\n    sslcontext.check_hostname = False\n    sslcontext.verify_mode = ssl.CERT_NONE\n    sslcontext.options |= ssl.OP_NO_COMPRESSION\n    sslcontext.set_default_verify_paths()\n    return sslcontext\n\n\n# The default SSLContext objects are created at import time\n# since they do blocking I/O to load certificates from disk,\n# and imports should always be done before the event loop starts\n# or in a thread.\n_SSL_CONTEXT_VERIFIED = _make_ssl_context(True)\n_SSL_CONTEXT_UNVERIFIED = _make_ssl_context(False)\n\n\nclass TCPConnector(BaseConnector):\n    \"\"\"TCP connector.\n\n    verify_ssl - Set to True to check ssl certifications.\n    fingerprint - Pass the binary sha256\n        digest of the expected certificate in DER format to verify\n        that the certificate the server presents matches. See also\n        https://en.wikipedia.org/wiki/HTTP_Public_Key_Pinning\n    resolver - Enable DNS lookups and use this\n        resolver\n    use_dns_cache - Use memory cache for DNS lookups.\n    ttl_dns_cache - Max seconds having cached a DNS entry, None forever.\n    family - socket address family\n    local_addr - local tuple of (host, port) to bind socket to\n\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    enable_cleanup_closed - Enables clean-up closed ssl transports.\n                            Disabled by default.\n    happy_eyeballs_delay - This is the \u201cConnection Attempt Delay\u201d\n                           as defined in RFC 8305. To disable\n                           the happy eyeballs algorithm, set to None.\n    interleave - \u201cFirst Address Family Count\u201d as defined in RFC 8305\n    loop - Optional event loop.\n    \"\"\"\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({\"tcp\"})\n\n    def __init__(\n        self,\n        *,\n        verify_ssl: bool = True,\n        fingerprint: Optional[bytes] = None,\n        use_dns_cache: bool = True,\n        ttl_dns_cache: Optional[int] = 10,\n        family: socket.AddressFamily = socket.AddressFamily.AF_UNSPEC,\n        ssl_context: Optional[SSLContext] = None,\n        ssl: Union[bool, Fingerprint, SSLContext] = True,\n        local_addr: Optional[Tuple[str, int]] = None,\n        resolver: Optional[AbstractResolver] = None,\n        keepalive_timeout: Union[None, float, object] = sentinel,\n        force_close: bool = False,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        enable_cleanup_closed: bool = False,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n        timeout_ceil_threshold: float = 5,\n        happy_eyeballs_delay: Optional[float] = 0.25,\n        interleave: Optional[int] = None,\n    ):\n        super().__init__(\n            keepalive_timeout=keepalive_timeout,\n            force_close=force_close,\n            limit=limit,\n            limit_per_host=limit_per_host,\n            enable_cleanup_closed=enable_cleanup_closed,\n            loop=loop,\n            timeout_ceil_threshold=timeout_ceil_threshold,\n        )\n\n        self._ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)\n        if resolver is None:\n            resolver = DefaultResolver(loop=self._loop)\n        self._resolver = resolver\n\n        self._use_dns_cache = use_dns_cache\n        self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache)\n        self._throttle_dns_futures: Dict[\n            Tuple[str, int], Set[\"asyncio.Future[None]\"]\n        ] = {}\n        self._family = family\n        self._local_addr_infos = aiohappyeyeballs.addr_to_addr_infos(local_addr)\n        self._happy_eyeballs_delay = happy_eyeballs_delay\n        self._interleave = interleave\n        self._resolve_host_tasks: Set[\"asyncio.Task[List[ResolveResult]]\"] = set()\n\n    def close(self) -> Awaitable[None]:\n        \"\"\"Close all ongoing DNS calls.\"\"\"\n        for fut in chain.from_iterable(self._throttle_dns_futures.values()):\n            fut.cancel()\n\n        for t in self._resolve_host_tasks:\n            t.cancel()\n\n        return super().close()\n\n    @property\n    def family(self) -> int:\n        \"\"\"Socket family like AF_INET.\"\"\"\n        return self._family\n\n    @property\n    def use_dns_cache(self) -> bool:\n        \"\"\"True if local DNS caching is enabled.\"\"\"\n        return self._use_dns_cache\n\n    def clear_dns_cache(\n        self, host: Optional[str] = None, port: Optional[int] = None\n    ) -> None:\n        \"\"\"Remove specified host/port or clear all dns local cache.\"\"\"\n        if host is not None and port is not None:\n            self._cached_hosts.remove((host, port))\n        elif host is not None or port is not None:\n            raise ValueError(\"either both host and port or none of them are allowed\")\n        else:\n            self._cached_hosts.clear()\n\n    async def _resolve_host(\n        self, host: str, port: int, traces: Optional[Sequence[\"Trace\"]] = None\n    ) -> List[ResolveResult]:\n        \"\"\"Resolve host and return list of addresses.\"\"\"\n        if is_ip_address(host):\n            return [\n                {\n                    \"hostname\": host,\n                    \"host\": host,\n                    \"port\": port,\n                    \"family\": self._family,\n                    \"proto\": 0,\n                    \"flags\": 0,\n                }\n            ]\n\n        if not self._use_dns_cache:\n\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_start(host)\n\n            res = await self._resolver.resolve(host, port, family=self._family)\n\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_end(host)\n\n            return res\n\n        key = (host, port)\n        if key in self._cached_hosts and not self._cached_hosts.expired(key):\n            # get result early, before any await (#4014)\n            result = self._cached_hosts.next_addrs(key)\n\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_cache_hit(host)\n            return result\n\n        futures: Set[\"asyncio.Future[None]\"]\n        #\n        # If multiple connectors are resolving the same host, we wait\n        # for the first one to resolve and then use the result for all of them.\n        # We use a throttle to ensure that we only resolve the host once\n        # and then use the result for all the waiters.\n        #\n        if key in self._throttle_dns_futures:\n            # get futures early, before any await (#4014)\n            futures = self._throttle_dns_futures[key]\n            future: asyncio.Future[None] = self._loop.create_future()\n            futures.add(future)\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_cache_hit(host)\n            try:\n                await future\n            finally:\n                futures.discard(future)\n            return self._cached_hosts.next_addrs(key)\n\n        # update dict early, before any await (#4014)\n        self._throttle_dns_futures[key] = futures = set()\n        # In this case we need to create a task to ensure that we can shield\n        # the task from cancellation as cancelling this lookup should not cancel\n        # the underlying lookup or else the cancel event will get broadcast to\n        # all the waiters across all connections.\n        #\n        coro = self._resolve_host_with_throttle(key, host, port, futures, traces)\n        loop = asyncio.get_running_loop()\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send immediately\n            resolved_host_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            resolved_host_task = loop.create_task(coro)\n\n        if not resolved_host_task.done():\n            self._resolve_host_tasks.add(resolved_host_task)\n            resolved_host_task.add_done_callback(self._resolve_host_tasks.discard)\n\n        try:\n            return await asyncio.shield(resolved_host_task)\n        except asyncio.CancelledError:\n\n            def drop_exception(fut: \"asyncio.Future[List[ResolveResult]]\") -> None:\n                with suppress(Exception, asyncio.CancelledError):\n                    fut.result()\n\n            resolved_host_task.add_done_callback(drop_exception)\n            raise\n\n    async def _resolve_host_with_throttle(\n        self,\n        key: Tuple[str, int],\n        host: str,\n        port: int,\n        futures: Set[\"asyncio.Future[None]\"],\n        traces: Optional[Sequence[\"Trace\"]],\n    ) -> List[ResolveResult]:\n        \"\"\"Resolve host and set result for all waiters.\n\n        This method must be run in a task and shielded from cancellation\n        to avoid cancelling the underlying lookup.\n        \"\"\"\n        if traces:\n            for trace in traces:\n                await trace.send_dns_cache_miss(host)\n        try:\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_start(host)\n\n            addrs = await self._resolver.resolve(host, port, family=self._family)\n            if traces:\n                for trace in traces:\n                    await trace.send_dns_resolvehost_end(host)\n\n            self._cached_hosts.add(key, addrs)\n            for fut in futures:\n                set_result(fut, None)\n        except BaseException as e:\n            # any DNS exception is set for the waiters to raise the same exception.\n            # This coro is always run in task that is shielded from cancellation so\n            # we should never be propagating cancellation here.\n            for fut in futures:\n                set_exception(fut, e)\n            raise\n        finally:\n            self._throttle_dns_futures.pop(key)\n\n        return self._cached_hosts.next_addrs(key)\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        \"\"\"Create connection.\n\n        Has same keyword arguments as BaseEventLoop.create_connection.\n        \"\"\"\n        if req.proxy:\n            _, proto = await self._create_proxy_connection(req, traces, timeout)\n        else:\n            _, proto = await self._create_direct_connection(req, traces, timeout)\n\n        return proto\n\n    def _get_ssl_context(self, req: ClientRequest) -> Optional[SSLContext]:\n        \"\"\"Logic to get the correct SSL context\n\n        0. if req.ssl is false, return None\n\n        1. if ssl_context is specified in req, use it\n        2. if _ssl_context is specified in self, use it\n        3. otherwise:\n            1. if verify_ssl is not specified in req, use self.ssl_context\n               (will generate a default context according to self.verify_ssl)\n            2. if verify_ssl is True in req, generate a default SSL context\n            3. if verify_ssl is False in req, generate a SSL context that\n               won't verify\n        \"\"\"\n        if not req.is_ssl():\n            return None\n\n        if ssl is None:  # pragma: no cover\n            raise RuntimeError(\"SSL is not supported.\")\n        sslcontext = req.ssl\n        if isinstance(sslcontext, ssl.SSLContext):\n            return sslcontext\n        if sslcontext is not True:\n            # not verified or fingerprinted\n            return _SSL_CONTEXT_UNVERIFIED\n        sslcontext = self._ssl\n        if isinstance(sslcontext, ssl.SSLContext):\n            return sslcontext\n        if sslcontext is not True:\n            # not verified or fingerprinted\n            return _SSL_CONTEXT_UNVERIFIED\n        return _SSL_CONTEXT_VERIFIED\n\n    def _get_fingerprint(self, req: ClientRequest) -> Optional[\"Fingerprint\"]:\n        ret = req.ssl\n        if isinstance(ret, Fingerprint):\n            return ret\n        ret = self._ssl\n        if isinstance(ret, Fingerprint):\n            return ret\n        return None\n\n    async def _wrap_create_connection(\n        self,\n        *args: Any,\n        addr_infos: List[aiohappyeyeballs.AddrInfoType],\n        req: ClientRequest,\n        timeout: \"ClientTimeout\",\n        client_error: Type[Exception] = ClientConnectorError,\n        **kwargs: Any,\n    ) -> Tuple[asyncio.Transport, ResponseHandler]:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                sock = await aiohappyeyeballs.start_connection(\n                    addr_infos=addr_infos,\n                    local_addr_infos=self._local_addr_infos,\n                    happy_eyeballs_delay=self._happy_eyeballs_delay,\n                    interleave=self._interleave,\n                    loop=self._loop,\n                )\n                return await self._loop.create_connection(*args, **kwargs, sock=sock)\n        except cert_errors as exc:\n            raise ClientConnectorCertificateError(req.connection_key, exc) from exc\n        except ssl_errors as exc:\n            raise ClientConnectorSSLError(req.connection_key, exc) from exc\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise client_error(req.connection_key, exc) from exc\n\n    async def _wrap_existing_connection(\n        self,\n        *args: Any,\n        req: ClientRequest,\n        timeout: \"ClientTimeout\",\n        client_error: Type[Exception] = ClientConnectorError,\n        **kwargs: Any,\n    ) -> Tuple[asyncio.Transport, ResponseHandler]:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                return await self._loop.create_connection(*args, **kwargs)\n        except cert_errors as exc:\n            raise ClientConnectorCertificateError(req.connection_key, exc) from exc\n        except ssl_errors as exc:\n            raise ClientConnectorSSLError(req.connection_key, exc) from exc\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise client_error(req.connection_key, exc) from exc\n\n    def _fail_on_no_start_tls(self, req: \"ClientRequest\") -> None:\n        \"\"\"Raise a :py:exc:`RuntimeError` on missing ``start_tls()``.\n\n        It is necessary for TLS-in-TLS so that it is possible to\n        send HTTPS queries through HTTPS proxies.\n\n        This doesn't affect regular HTTP requests, though.\n        \"\"\"\n        if not req.is_ssl():\n            return\n\n        proxy_url = req.proxy\n        assert proxy_url is not None\n        if proxy_url.scheme != \"https\":\n            return\n\n        self._check_loop_for_start_tls()\n\n    def _check_loop_for_start_tls(self) -> None:\n        try:\n            self._loop.start_tls\n        except AttributeError as attr_exc:\n            raise RuntimeError(\n                \"An HTTPS request is being sent through an HTTPS proxy. \"\n                \"This needs support for TLS in TLS but it is not implemented \"\n                \"in your runtime for the stdlib asyncio.\\n\\n\"\n                \"Please upgrade to Python 3.11 or higher. For more details, \"\n                \"please see:\\n\"\n                \"* https://bugs.python.org/issue37179\\n\"\n                \"* https://github.com/python/cpython/pull/28073\\n\"\n                \"* https://docs.aiohttp.org/en/stable/\"\n                \"client_advanced.html#proxy-support\\n\"\n                \"* https://github.com/aio-libs/aiohttp/discussions/6044\\n\",\n            ) from attr_exc\n\n    def _loop_supports_start_tls(self) -> bool:\n        try:\n            self._check_loop_for_start_tls()\n        except RuntimeError:\n            return False\n        else:\n            return True\n\n    def _warn_about_tls_in_tls(\n        self,\n        underlying_transport: asyncio.Transport,\n        req: ClientRequest,\n    ) -> None:\n        \"\"\"Issue a warning if the requested URL has HTTPS scheme.\"\"\"\n        if req.request_info.url.scheme != \"https\":\n            return\n\n        asyncio_supports_tls_in_tls = getattr(\n            underlying_transport,\n            \"_start_tls_compatible\",\n            False,\n        )\n\n        if asyncio_supports_tls_in_tls:\n            return\n\n        warnings.warn(\n            \"An HTTPS request is being sent through an HTTPS proxy. \"\n            \"This support for TLS in TLS is known to be disabled \"\n            \"in the stdlib asyncio (Python <3.11). This is why you'll probably see \"\n            \"an error in the log below.\\n\\n\"\n            \"It is possible to enable it via monkeypatching. \"\n            \"For more details, see:\\n\"\n            \"* https://bugs.python.org/issue37179\\n\"\n            \"* https://github.com/python/cpython/pull/28073\\n\\n\"\n            \"You can temporarily patch this as follows:\\n\"\n            \"* https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support\\n\"\n            \"* https://github.com/aio-libs/aiohttp/discussions/6044\\n\",\n            RuntimeWarning,\n            source=self,\n            # Why `4`? At least 3 of the calls in the stack originate\n            # from the methods in this class.\n            stacklevel=3,\n        )\n\n    async def _start_tls_connection(\n        self,\n        underlying_transport: asyncio.Transport,\n        req: ClientRequest,\n        timeout: \"ClientTimeout\",\n        client_error: Type[Exception] = ClientConnectorError,\n    ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:\n        \"\"\"Wrap the raw TCP transport with TLS.\"\"\"\n        tls_proto = self._factory()  # Create a brand new proto for TLS\n        sslcontext = self._get_ssl_context(req)\n        if TYPE_CHECKING:\n            # _start_tls_connection is unreachable in the current code path\n            # if sslcontext is None.\n            assert sslcontext is not None\n\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                try:\n                    tls_transport = await self._loop.start_tls(\n                        underlying_transport,\n                        tls_proto,\n                        sslcontext,\n                        server_hostname=req.server_hostname or req.host,\n                        ssl_handshake_timeout=timeout.total,\n                    )\n                except BaseException:\n                    # We need to close the underlying transport since\n                    # `start_tls()` probably failed before it had a\n                    # chance to do this:\n                    underlying_transport.close()\n                    raise\n                if isinstance(tls_transport, asyncio.Transport):\n                    fingerprint = self._get_fingerprint(req)\n                    if fingerprint:\n                        try:\n                            fingerprint.check(tls_transport)\n                        except ServerFingerprintMismatch:\n                            tls_transport.close()\n                            if not self._cleanup_closed_disabled:\n                                self._cleanup_closed_transports.append(tls_transport)\n                            raise\n        except cert_errors as exc:\n            raise ClientConnectorCertificateError(req.connection_key, exc) from exc\n        except ssl_errors as exc:\n            raise ClientConnectorSSLError(req.connection_key, exc) from exc\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise client_error(req.connection_key, exc) from exc\n        except TypeError as type_err:\n            # Example cause looks like this:\n            # TypeError: transport <asyncio.sslproto._SSLProtocolTransport\n            # object at 0x7f760615e460> is not supported by start_tls()\n\n            raise ClientConnectionError(\n                \"Cannot initialize a TLS-in-TLS connection to host \"\n                f\"{req.host!s}:{req.port:d} through an underlying connection \"\n                f\"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} \"\n                f\"[{type_err!s}]\"\n            ) from type_err\n        else:\n            if tls_transport is None:\n                msg = \"Failed to start TLS (possibly caused by closing transport)\"\n                raise client_error(req.connection_key, OSError(msg))\n            tls_proto.connection_made(\n                tls_transport\n            )  # Kick the state machine of the new TLS protocol\n\n        return tls_transport, tls_proto\n\n    def _convert_hosts_to_addr_infos(\n        self, hosts: List[ResolveResult]\n    ) -> List[aiohappyeyeballs.AddrInfoType]:\n        \"\"\"Converts the list of hosts to a list of addr_infos.\n\n        The list of hosts is the result of a DNS lookup. The list of\n        addr_infos is the result of a call to `socket.getaddrinfo()`.\n        \"\"\"\n        addr_infos: List[aiohappyeyeballs.AddrInfoType] = []\n        for hinfo in hosts:\n            host = hinfo[\"host\"]\n            is_ipv6 = \":\" in host\n            family = socket.AF_INET6 if is_ipv6 else socket.AF_INET\n            if self._family and self._family != family:\n                continue\n            addr = (host, hinfo[\"port\"], 0, 0) if is_ipv6 else (host, hinfo[\"port\"])\n            addr_infos.append(\n                (family, socket.SOCK_STREAM, socket.IPPROTO_TCP, \"\", addr)\n            )\n        return addr_infos\n\n    async def _create_direct_connection(\n        self,\n        req: ClientRequest,\n        traces: List[\"Trace\"],\n        timeout: \"ClientTimeout\",\n        *,\n        client_error: Type[Exception] = ClientConnectorError,\n    ) -> Tuple[asyncio.Transport, ResponseHandler]:\n        sslcontext = self._get_ssl_context(req)\n        fingerprint = self._get_fingerprint(req)\n\n        host = req.url.raw_host\n        assert host is not None\n        # Replace multiple trailing dots with a single one.\n        # A trailing dot is only present for fully-qualified domain names.\n        # See https://github.com/aio-libs/aiohttp/pull/7364.\n        if host.endswith(\"..\"):\n            host = host.rstrip(\".\") + \".\"\n        port = req.port\n        assert port is not None\n        try:\n            # Cancelling this lookup should not cancel the underlying lookup\n            #  or else the cancel event will get broadcast to all the waiters\n            #  across all connections.\n            hosts = await self._resolve_host(host, port, traces=traces)\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            # in case of proxy it is not ClientProxyConnectionError\n            # it is problem of resolving proxy ip itself\n            raise ClientConnectorDNSError(req.connection_key, exc) from exc\n\n        last_exc: Optional[Exception] = None\n        addr_infos = self._convert_hosts_to_addr_infos(hosts)\n        while addr_infos:\n            # Strip trailing dots, certificates contain FQDN without dots.\n            # See https://github.com/aio-libs/aiohttp/issues/3636\n            server_hostname = (\n                (req.server_hostname or host).rstrip(\".\") if sslcontext else None\n            )\n\n            try:\n                transp, proto = await self._wrap_create_connection(\n                    self._factory,\n                    timeout=timeout,\n                    ssl=sslcontext,\n                    addr_infos=addr_infos,\n                    server_hostname=server_hostname,\n                    req=req,\n                    client_error=client_error,\n                )\n            except (ClientConnectorError, asyncio.TimeoutError) as exc:\n                last_exc = exc\n                aiohappyeyeballs.pop_addr_infos_interleave(addr_infos, self._interleave)\n                continue\n\n            if req.is_ssl() and fingerprint:\n                try:\n                    fingerprint.check(transp)\n                except ServerFingerprintMismatch as exc:\n                    transp.close()\n                    if not self._cleanup_closed_disabled:\n                        self._cleanup_closed_transports.append(transp)\n                    last_exc = exc\n                    # Remove the bad peer from the list of addr_infos\n                    sock: socket.socket = transp.get_extra_info(\"socket\")\n                    bad_peer = sock.getpeername()\n                    aiohappyeyeballs.remove_addr_infos(addr_infos, bad_peer)\n                    continue\n\n            return transp, proto\n        else:\n            assert last_exc is not None\n            raise last_exc\n\n    async def _create_proxy_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:\n        self._fail_on_no_start_tls(req)\n        runtime_has_start_tls = self._loop_supports_start_tls()\n\n        headers: Dict[str, str] = {}\n        if req.proxy_headers is not None:\n            headers = req.proxy_headers  # type: ignore[assignment]\n        headers[hdrs.HOST] = req.headers[hdrs.HOST]\n\n        url = req.proxy\n        assert url is not None\n        proxy_req = ClientRequest(\n            hdrs.METH_GET,\n            url,\n            headers=headers,\n            auth=req.proxy_auth,\n            loop=self._loop,\n            ssl=req.ssl,\n        )\n\n        # create connection to proxy server\n        transport, proto = await self._create_direct_connection(\n            proxy_req, [], timeout, client_error=ClientProxyConnectionError\n        )\n\n        auth = proxy_req.headers.pop(hdrs.AUTHORIZATION, None)\n        if auth is not None:\n            if not req.is_ssl():\n                req.headers[hdrs.PROXY_AUTHORIZATION] = auth\n            else:\n                proxy_req.headers[hdrs.PROXY_AUTHORIZATION] = auth\n\n        if req.is_ssl():\n            if runtime_has_start_tls:\n                self._warn_about_tls_in_tls(transport, req)\n\n            # For HTTPS requests over HTTP proxy\n            # we must notify proxy to tunnel connection\n            # so we send CONNECT command:\n            #   CONNECT www.python.org:443 HTTP/1.1\n            #   Host: www.python.org\n            #\n            # next we must do TLS handshake and so on\n            # to do this we must wrap raw socket into secure one\n            # asyncio handles this perfectly\n            proxy_req.method = hdrs.METH_CONNECT\n            proxy_req.url = req.url\n            key = req.connection_key._replace(\n                proxy=None, proxy_auth=None, proxy_headers_hash=None\n            )\n            conn = Connection(self, key, proto, self._loop)\n            proxy_resp = await proxy_req.send(conn)\n            try:\n                protocol = conn._protocol\n                assert protocol is not None\n\n                # read_until_eof=True will ensure the connection isn't closed\n                # once the response is received and processed allowing\n                # START_TLS to work on the connection below.\n                protocol.set_response_params(\n                    read_until_eof=runtime_has_start_tls,\n                    timeout_ceil_threshold=self._timeout_ceil_threshold,\n                )\n                resp = await proxy_resp.start(conn)\n            except BaseException:\n                proxy_resp.close()\n                conn.close()\n                raise\n            else:\n                conn._protocol = None\n                try:\n                    if resp.status != 200:\n                        message = resp.reason\n                        if message is None:\n                            message = HTTPStatus(resp.status).phrase\n                        raise ClientHttpProxyError(\n                            proxy_resp.request_info,\n                            resp.history,\n                            status=resp.status,\n                            message=message,\n                            headers=resp.headers,\n                        )\n                    if not runtime_has_start_tls:\n                        rawsock = transport.get_extra_info(\"socket\", default=None)\n                        if rawsock is None:\n                            raise RuntimeError(\n                                \"Transport does not expose socket instance\"\n                            )\n                        # Duplicate the socket, so now we can close proxy transport\n                        rawsock = rawsock.dup()\n                except BaseException:\n                    # It shouldn't be closed in `finally` because it's fed to\n                    # `loop.start_tls()` and the docs say not to touch it after\n                    # passing there.\n                    transport.close()\n                    raise\n                finally:\n                    if not runtime_has_start_tls:\n                        transport.close()\n\n                if not runtime_has_start_tls:\n                    # HTTP proxy with support for upgrade to HTTPS\n                    sslcontext = self._get_ssl_context(req)\n                    return await self._wrap_existing_connection(\n                        self._factory,\n                        timeout=timeout,\n                        ssl=sslcontext,\n                        sock=rawsock,\n                        server_hostname=req.host,\n                        req=req,\n                    )\n\n                return await self._start_tls_connection(\n                    # Access the old transport for the last time before it's\n                    # closed and forgotten forever:\n                    transport,\n                    req=req,\n                    timeout=timeout,\n                )\n            finally:\n                proxy_resp.close()\n\n        return transport, proto\n\n\nclass UnixConnector(BaseConnector):\n    \"\"\"Unix socket connector.\n\n    path - Unix socket path.\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    loop - Optional event loop.\n    \"\"\"\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({\"unix\"})\n\n    def __init__(\n        self,\n        path: str,\n        force_close: bool = False,\n        keepalive_timeout: Union[object, float, None] = sentinel,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n    ) -> None:\n        super().__init__(\n            force_close=force_close,\n            keepalive_timeout=keepalive_timeout,\n            limit=limit,\n            limit_per_host=limit_per_host,\n            loop=loop,\n        )\n        self._path = path\n\n    @property\n    def path(self) -> str:\n        \"\"\"Path to unix socket.\"\"\"\n        return self._path\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                _, proto = await self._loop.create_unix_connection(\n                    self._factory, self._path\n                )\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc\n\n        return proto\n\n\nclass NamedPipeConnector(BaseConnector):\n    \"\"\"Named pipe connector.\n\n    Only supported by the proactor event loop.\n    See also: https://docs.python.org/3/library/asyncio-eventloop.html\n\n    path - Windows named pipe path.\n    keepalive_timeout - (optional) Keep-alive timeout.\n    force_close - Set to True to force close and do reconnect\n        after each request (and between redirects).\n    limit - The total number of simultaneous connections.\n    limit_per_host - Number of simultaneous connections to one host.\n    loop - Optional event loop.\n    \"\"\"\n\n    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({\"npipe\"})\n\n    def __init__(\n        self,\n        path: str,\n        force_close: bool = False,\n        keepalive_timeout: Union[object, float, None] = sentinel,\n        limit: int = 100,\n        limit_per_host: int = 0,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n    ) -> None:\n        super().__init__(\n            force_close=force_close,\n            keepalive_timeout=keepalive_timeout,\n            limit=limit,\n            limit_per_host=limit_per_host,\n            loop=loop,\n        )\n        if not isinstance(\n            self._loop, asyncio.ProactorEventLoop  # type: ignore[attr-defined]\n        ):\n            raise RuntimeError(\n                \"Named Pipes only available in proactor loop under windows\"\n            )\n        self._path = path\n\n    @property\n    def path(self) -> str:\n        \"\"\"Path to the named pipe.\"\"\"\n        return self._path\n\n    async def _create_connection(\n        self, req: ClientRequest, traces: List[\"Trace\"], timeout: \"ClientTimeout\"\n    ) -> ResponseHandler:\n        try:\n            async with ceil_timeout(\n                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold\n            ):\n                _, proto = await self._loop.create_pipe_connection(  # type: ignore[attr-defined]\n                    self._factory, self._path\n                )\n                # the drain is required so that the connection_made is called\n                # and transport is set otherwise it is not set before the\n                # `assert conn.transport is not None`\n                # in client.py's _request method\n                await asyncio.sleep(0)\n                # other option is to manually set transport like\n                # `proto.transport = trans`\n        except OSError as exc:\n            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):\n                raise\n            raise ClientConnectorError(req.connection_key, exc) from exc\n\n        return cast(ResponseHandler, proto)\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `Connection.release` method includes redundant `should_close` argument when calling connector's `_release`

**Description:**
When releasing a connection, the `Connection.release()` method unnecessarily passes the `should_close` parameter to the connector's `_release` method. This redundant argument causes issues where connector implementations expecting only `key` and `protocol` parameters fail or behave unexpectedly.

**Example Code:**
```python
connector = Connector()
key = 'unique_key'
protocol = Protocol()

connection = Connection(connector, key, protocol, loop)
connection.release()
```

**Expected Behavior:**
The `connector._release` method should be called with only `key` and `protocol`:
```python
connector._release(key, protocol)
```

**Actual Behavior:**
The `connector._release` method is called with an additional `should_close` argument:
```python
connector._release(key, protocol, should_close=protocol.should_close)
```
This extra argument leads to assertion failures or unexpected behavior in connector implementations that do not handle the `should_close` parameter.
[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### aiohttp/connector.py
import asyncio
import functools
import random
import socket
import sys
import traceback
import warnings
from collections import OrderedDict, defaultdict, deque
from contextlib import suppress
from http import HTTPStatus
from itertools import chain, cycle, islice
from time import monotonic
from types import TracebackType
from typing import (
    TYPE_CHECKING,
    Any,
    Awaitable,
    Callable,
    DefaultDict,
    Deque,
    Dict,
    Iterator,
    List,
    Literal,
    Optional,
    Sequence,
    Set,
    Tuple,
    Type,
    Union,
    cast,
)

import aiohappyeyeballs

from . import hdrs, helpers
from .abc import AbstractResolver, ResolveResult
from .client_exceptions import (
    ClientConnectionError,
    ClientConnectorCertificateError,
    ClientConnectorDNSError,
    ClientConnectorError,
    ClientConnectorSSLError,
    ClientHttpProxyError,
    ClientProxyConnectionError,
    ServerFingerprintMismatch,
    UnixClientConnectorError,
    cert_errors,
    ssl_errors,
)
from .client_proto import ResponseHandler
from .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params
from .helpers import (
    ceil_timeout,
    is_ip_address,
    noop,
    sentinel,
    set_exception,
    set_result,
)
from .resolver import DefaultResolver

try:
    import ssl

    SSLContext = ssl.SSLContext
except ImportError:  # pragma: no cover
    ssl = None  # type: ignore[assignment]
    SSLContext = object  # type: ignore[misc,assignment]


EMPTY_SCHEMA_SET = frozenset({""})
HTTP_SCHEMA_SET = frozenset({"http", "https"})
WS_SCHEMA_SET = frozenset({"ws", "wss"})

HTTP_AND_EMPTY_SCHEMA_SET = HTTP_SCHEMA_SET | EMPTY_SCHEMA_SET
HIGH_LEVEL_SCHEMA_SET = HTTP_AND_EMPTY_SCHEMA_SET | WS_SCHEMA_SET


__all__ = ("BaseConnector", "TCPConnector", "UnixConnector", "NamedPipeConnector")


if TYPE_CHECKING:
    from .client import ClientTimeout
    from .client_reqrep import ConnectionKey
    from .tracing import Trace


class _DeprecationWaiter:
    __slots__ = ("_awaitable", "_awaited")

    def __init__(self, awaitable: Awaitable[Any]) -> None:
        self._awaitable = awaitable
        self._awaited = False

    def __await__(self) -> Any:
        self._awaited = True
        return self._awaitable.__await__()

    def __del__(self) -> None:
        if not self._awaited:
            warnings.warn(
                "Connector.close() is a coroutine, "
                "please use await connector.close()",
                DeprecationWarning,
            )


class Connection:

    _source_traceback = None

    def __init__(
        self,
        connector: "BaseConnector",
        key: "ConnectionKey",
        protocol: ResponseHandler,
        loop: asyncio.AbstractEventLoop,
    ) -> None:
        self._key = key
        self._connector = connector
        self._loop = loop
        self._protocol: Optional[ResponseHandler] = protocol
        self._callbacks: List[Callable[[], None]] = []

        if loop.get_debug():
            self._source_traceback = traceback.extract_stack(sys._getframe(1))

    def __repr__(self) -> str:
        return f"Connection<{self._key}>"

    def __del__(self, _warnings: Any = warnings) -> None:
        if self._protocol is not None:
            kwargs = {"source": self}
            _warnings.warn(f"Unclosed connection {self!r}", ResourceWarning, **kwargs)
            if self._loop.is_closed():
                return

            self._connector._release(self._key, self._protocol, should_close=True)

            context = {"client_connection": self, "message": "Unclosed connection"}
            if self._source_traceback is not None:
                context["source_traceback"] = self._source_traceback
            self._loop.call_exception_handler(context)

    def __bool__(self) -> Literal[True]:
        """Force subclasses to not be falsy, to make checks simpler."""
        return True

    @property
    def loop(self) -> asyncio.AbstractEventLoop:
        warnings.warn(
            "connector.loop property is deprecated", DeprecationWarning, stacklevel=2
        )
        return self._loop

    @property
    def transport(self) -> Optional[asyncio.Transport]:
        if self._protocol is None:
            return None
        return self._protocol.transport

    @property
    def protocol(self) -> Optional[ResponseHandler]:
        return self._protocol

    def add_callback(self, callback: Callable[[], None]) -> None:
        if callback is not None:
            self._callbacks.append(callback)

    def _notify_release(self) -> None:
        callbacks, self._callbacks = self._callbacks[:], []

        for cb in callbacks:
            with suppress(Exception):
                cb()

    def close(self) -> None:
        self._notify_release()

        if self._protocol is not None:
            self._connector._release(self._key, self._protocol, should_close=True)
            self._protocol = None

    def release(self) -> None:
        self._notify_release()

        if self._protocol is not None:
            self._connector._release(
                self._key, self._protocol, should_close=self._protocol.should_close
            )
            self._protocol = None

    @property
    def closed(self) -> bool:
        return self._protocol is None or not self._protocol.is_connected()


class _TransportPlaceholder:
    """placeholder for BaseConnector.connect function"""

    __slots__ = ()

    def close(self) -> None:
        """Close the placeholder transport."""


class BaseConnector:
    """Base connector class.

    keepalive_timeout - (optional) Keep-alive timeout.
    force_close - Set to True to force close and do reconnect
        after each request (and between redirects).
    limit - The total number of simultaneous connections.
    limit_per_host - Number of simultaneous connections to one host.
    enable_cleanup_closed - Enables clean-up closed ssl transports.
                            Disabled by default.
    timeout_ceil_threshold - Trigger ceiling of timeout values when
                             it's above timeout_ceil_threshold.
    loop - Optional event loop.
    """

    _closed = True  # prevent AttributeError in __del__ if ctor was failed
    _source_traceback = None

    # abort transport after 2 seconds (cleanup broken connections)
    _cleanup_closed_period = 2.0

    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET

    def __init__(
        self,
        *,
        keepalive_timeout: Union[object, None, float] = sentinel,
        force_close: bool = False,
        limit: int = 100,
        limit_per_host: int = 0,
        enable_cleanup_closed: bool = False,
        loop: Optional[asyncio.AbstractEventLoop] = None,
        timeout_ceil_threshold: float = 5,
    ) -> None:

        if force_close:
            if keepalive_timeout is not None and keepalive_timeout is not sentinel:
                raise ValueError(
                    "keepalive_timeout cannot be set if force_close is True"
                )
        else:
            if keepalive_timeout is sentinel:
                keepalive_timeout = 15.0

        loop = loop or asyncio.get_running_loop()
        self._timeout_ceil_threshold = timeout_ceil_threshold

        self._closed = False
        if loop.get_debug():
            self._source_traceback = traceback.extract_stack(sys._getframe(1))

        # Connection pool of reusable connections.
        # We use a deque to store connections because it has O(1) popleft()
        # and O(1) append() operations to implement a FIFO queue.
        self._conns: DefaultDict[
            ConnectionKey, Deque[Tuple[ResponseHandler, float]]
        ] = defaultdict(deque)
        self._limit = limit
        self._limit_per_host = limit_per_host
        self._acquired: Set[ResponseHandler] = set()
        self._acquired_per_host: DefaultDict[ConnectionKey, Set[ResponseHandler]] = (
            defaultdict(set)
        )
        self._keepalive_timeout = cast(float, keepalive_timeout)
        self._force_close = force_close

        # {host_key: FIFO list of waiters}
        # The FIFO is implemented with an OrderedDict with None keys because
        # python does not have an ordered set.
        self._waiters: DefaultDict[
            ConnectionKey, OrderedDict[asyncio.Future[None], None]
        ] = defaultdict(OrderedDict)

        self._loop = loop
        self._factory = functools.partial(ResponseHandler, loop=loop)

        # start keep-alive connection cleanup task
        self._cleanup_handle: Optional[asyncio.TimerHandle] = None

        # start cleanup closed transports task
        self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None
        self._cleanup_closed_disabled = not enable_cleanup_closed
        self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = []
        self._cleanup_closed()

    def __del__(self, _warnings: Any = warnings) -> None:
        if self._closed:
            return
        if not self._conns:
            return

        conns = [repr(c) for c in self._conns.values()]

        self._close()

        kwargs = {"source": self}
        _warnings.warn(f"Unclosed connector {self!r}", ResourceWarning, **kwargs)
        context = {
            "connector": self,
            "connections": conns,
            "message": "Unclosed connector",
        }
        if self._source_traceback is not None:
            context["source_traceback"] = self._source_traceback
        self._loop.call_exception_handler(context)

    def __enter__(self) -> "BaseConnector":
        warnings.warn(
            '"with Connector():" is deprecated, '
            'use "async with Connector():" instead',
            DeprecationWarning,
        )
        return self

    def __exit__(self, *exc: Any) -> None:
        self._close()

    async def __aenter__(self) -> "BaseConnector":
        return self

    async def __aexit__(
        self,
        exc_type: Optional[Type[BaseException]] = None,
        exc_value: Optional[BaseException] = None,
        exc_traceback: Optional[TracebackType] = None,
    ) -> None:
        await self.close()

    @property
    def force_close(self) -> bool:
        """Ultimately close connection on releasing if True."""
        return self._force_close

    @property
    def limit(self) -> int:
        """The total number for simultaneous connections.

        If limit is 0 the connector has no limit.
        The default limit size is 100.
        """
        return self._limit

    @property
    def limit_per_host(self) -> int:
        """The limit for simultaneous connections to the same endpoint.

        Endpoints are the same if they are have equal
        (host, port, is_ssl) triple.
        """
        return self._limit_per_host

    def _cleanup(self) -> None:
        """Cleanup unused transports."""
        if self._cleanup_handle:
            self._cleanup_handle.cancel()
            # _cleanup_handle should be unset, otherwise _release() will not
            # recreate it ever!
            self._cleanup_handle = None

        now = monotonic()
        timeout = self._keepalive_timeout

        if self._conns:
            connections = defaultdict(deque)
            deadline = now - timeout
            for key, conns in self._conns.items():
                alive: Deque[Tuple[ResponseHandler, float]] = deque()
                for proto, use_time in conns:
                    if proto.is_connected() and use_time - deadline >= 0:
                        alive.append((proto, use_time))
                        continue
                    transport = proto.transport
                    proto.close()
                    if not self._cleanup_closed_disabled and key.is_ssl:
                        self._cleanup_closed_transports.append(transport)

                if alive:
                    connections[key] = alive

            self._conns = connections

        if self._conns:
            self._cleanup_handle = helpers.weakref_handle(
                self,
                "_cleanup",
                timeout,
                self._loop,
                timeout_ceil_threshold=self._timeout_ceil_threshold,
            )

    def _cleanup_closed(self) -> None:
        """Double confirmation for transport close.

        Some broken ssl servers may leave socket open without proper close.
        """
        if self._cleanup_closed_handle:
            self._cleanup_closed_handle.cancel()

        for transport in self._cleanup_closed_transports:
            if transport is not None:
                transport.abort()

        self._cleanup_closed_transports = []

        if not self._cleanup_closed_disabled:
            self._cleanup_closed_handle = helpers.weakref_handle(
                self,
                "_cleanup_closed",
                self._cleanup_closed_period,
                self._loop,
                timeout_ceil_threshold=self._timeout_ceil_threshold,
            )

    def close(self) -> Awaitable[None]:
        """Close all opened transports."""
        self._close()
        return _DeprecationWaiter(noop())

    def _close(self) -> None:
        if self._closed:
            return

        self._closed = True

        try:
            if self._loop.is_closed():
                return

            # cancel cleanup task
            if self._cleanup_handle:
                self._cleanup_handle.cancel()

            # cancel cleanup close task
            if self._cleanup_closed_handle:
                self._cleanup_closed_handle.cancel()

            for data in self._conns.values():
                for proto, t0 in data:
                    proto.close()

            for proto in self._acquired:
                proto.close()

            for transport in self._cleanup_closed_transports:
                if transport is not None:
                    transport.abort()

        finally:
            self._conns.clear()
            self._acquired.clear()
            for keyed_waiters in self._waiters.values():
                for keyed_waiter in keyed_waiters:
                    keyed_waiter.cancel()
            self._waiters.clear()
            self._cleanup_handle = None
            self._cleanup_closed_transports.clear()
            self._cleanup_closed_handle = None

    @property
    def closed(self) -> bool:
        """Is connector closed.

        A readonly property.
        """
        return self._closed

    def _available_connections(self, key: "ConnectionKey") -> int:
        """
        Return number of available connections.

        The limit, limit_per_host and the connection key are taken into account.

        If it returns less than 1 means that there are no connections
        available.
        """
        # check total available connections
        # If there are no limits, this will always return 1
        total_remain = 1

        if self._limit and (total_remain := self._limit - len(self._acquired)) <= 0:
            return total_remain

        # check limit per host
        if host_remain := self._limit_per_host:
            if acquired := self._acquired_per_host.get(key):
                host_remain -= len(acquired)
            if total_remain > host_remain:
                return host_remain

        return total_remain

    async def connect(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> Connection:
        """Get from pool or create new connection."""
        key = req.connection_key
        if (conn := await self._get(key, traces)) is not None:
            # If we do not have to wait and we can get a connection from the pool
            # we can avoid the timeout ceil logic and directly return the connection
            return conn

        async with ceil_timeout(timeout.connect, timeout.ceil_threshold):
            if self._available_connections(key) <= 0:
                await self._wait_for_available_connection(key, traces)
                if (conn := await self._get(key, traces)) is not None:
                    return conn

            placeholder = cast(ResponseHandler, _TransportPlaceholder())
            self._acquired.add(placeholder)
            self._acquired_per_host[key].add(placeholder)

            try:
                # Traces are done inside the try block to ensure that the
                # that the placeholder is still cleaned up if an exception
                # is raised.
                if traces:
                    for trace in traces:
                        await trace.send_connection_create_start()
                proto = await self._create_connection(req, traces, timeout)
                if traces:
                    for trace in traces:
                        await trace.send_connection_create_end()
            except BaseException:
                self._release_acquired(key, placeholder)
                raise
            else:
                if self._closed:
                    proto.close()
                    raise ClientConnectionError("Connector is closed.")

        # The connection was successfully created, drop the placeholder
        # and add the real connection to the acquired set. There should
        # be no awaits after the proto is added to the acquired set
        # to ensure that the connection is not left in the acquired set
        # on cancellation.
        acquired_per_host = self._acquired_per_host[key]
        self._acquired.remove(placeholder)
        acquired_per_host.remove(placeholder)
        self._acquired.add(proto)
        acquired_per_host.add(proto)
        return Connection(self, key, proto, self._loop)

    async def _wait_for_available_connection(
        self, key: "ConnectionKey", traces: List["Trace"]
    ) -> None:
        """Wait for an available connection slot."""
        # We loop here because there is a race between
        # the connection limit check and the connection
        # being acquired. If the connection is acquired
        # between the check and the await statement, we
        # need to loop again to check if the connection
        # slot is still available.
        attempts = 0
        while True:
            fut: asyncio.Future[None] = self._loop.create_future()
            keyed_waiters = self._waiters[key]
            keyed_waiters[fut] = None
            if attempts:
                # If we have waited before, we need to move the waiter
                # to the front of the queue as otherwise we might get
                # starved and hit the timeout.
                keyed_waiters.move_to_end(fut, last=False)

            try:
                # Traces happen in the try block to ensure that the
                # the waiter is still cleaned up if an exception is raised.
                if traces:
                    for trace in traces:
                        await trace.send_connection_queued_start()
                await fut
                if traces:
                    for trace in traces:
                        await trace.send_connection_queued_end()
            finally:
                # pop the waiter from the queue if its still
                # there and not already removed by _release_waiter
                keyed_waiters.pop(fut, None)
                if not self._waiters.get(key, True):
                    del self._waiters[key]

            if self._available_connections(key) > 0:
                break
            attempts += 1

    async def _get(
        self, key: "ConnectionKey", traces: List["Trace"]
    ) -> Optional[Connection]:
        """Get next reusable connection for the key or None.

        The connection will be marked as acquired.
        """
        if (conns := self._conns.get(key)) is None:
            return None

        t1 = monotonic()
        while conns:
            proto, t0 = conns.popleft()
            # We will we reuse the connection if its connected and
            # the keepalive timeout has not been exceeded
            if proto.is_connected() and t1 - t0 <= self._keepalive_timeout:
                if not conns:
                    # The very last connection was reclaimed: drop the key
                    del self._conns[key]
                self._acquired.add(proto)
                self._acquired_per_host[key].add(proto)
                if traces:
                    for trace in traces:
                        try:
                            await trace.send_connection_reuseconn()
                        except BaseException:
                            self._release_acquired(key, proto)
                            raise
                return Connection(self, key, proto, self._loop)

            # Connection cannot be reused, close it
            transport = proto.transport
            proto.close()
            # only for SSL transports
            if not self._cleanup_closed_disabled and key.is_ssl:
                self._cleanup_closed_transports.append(transport)

        # No more connections: drop the key
        del self._conns[key]
        return None

    def _release_waiter(self) -> None:
        """
        Iterates over all waiters until one to be released is found.

        The one to be released is not finished and
        belongs to a host that has available connections.
        """
        if not self._waiters:
            return

        # Having the dict keys ordered this avoids to iterate
        # at the same order at each call.
        queues = list(self._waiters)
        random.shuffle(queues)

        for key in queues:
            if self._available_connections(key) < 1:
                continue

            waiters = self._waiters[key]
            while waiters:
                waiter, _ = waiters.popitem(last=False)
                if not waiter.done():
                    waiter.set_result(None)
                    return

    def _release_acquired(self, key: "ConnectionKey", proto: ResponseHandler) -> None:
        """Release acquired connection."""
        if self._closed:
            # acquired connection is already released on connector closing
            return

        self._acquired.discard(proto)
        if conns := self._acquired_per_host.get(key):
            conns.discard(proto)
            if not conns:
                del self._acquired_per_host[key]
        self._release_waiter()

    def _release(
        self,
        key: "ConnectionKey",
        protocol: ResponseHandler,
        *,
        should_close: bool = False,
    ) -> None:
        if self._closed:
            # acquired connection is already released on connector closing
            return

        self._release_acquired(key, protocol)

        if self._force_close:
            should_close = True

        if should_close or protocol.should_close:
            transport = protocol.transport
            protocol.close()

            if key.is_ssl and not self._cleanup_closed_disabled:
                self._cleanup_closed_transports.append(transport)
            return

        self._conns[key].append((protocol, monotonic()))

        if self._cleanup_handle is None:
            self._cleanup_handle = helpers.weakref_handle(
                self,
                "_cleanup",
                self._keepalive_timeout,
                self._loop,
                timeout_ceil_threshold=self._timeout_ceil_threshold,
            )

    async def _create_connection(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> ResponseHandler:
        raise NotImplementedError()


class _DNSCacheTable:
    def __init__(self, ttl: Optional[float] = None) -> None:
        self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[ResolveResult], int]] = {}
        self._timestamps: Dict[Tuple[str, int], float] = {}
        self._ttl = ttl

    def __contains__(self, host: object) -> bool:
        return host in self._addrs_rr

    def add(self, key: Tuple[str, int], addrs: List[ResolveResult]) -> None:
        self._addrs_rr[key] = (cycle(addrs), len(addrs))

        if self._ttl is not None:
            self._timestamps[key] = monotonic()

    def remove(self, key: Tuple[str, int]) -> None:
        self._addrs_rr.pop(key, None)

        if self._ttl is not None:
            self._timestamps.pop(key, None)

    def clear(self) -> None:
        self._addrs_rr.clear()
        self._timestamps.clear()

    def next_addrs(self, key: Tuple[str, int]) -> List[ResolveResult]:
        loop, length = self._addrs_rr[key]
        addrs = list(islice(loop, length))
        # Consume one more element to shift internal state of `cycle`
        next(loop)
        return addrs

    def expired(self, key: Tuple[str, int]) -> bool:
        if self._ttl is None:
            return False

        return self._timestamps[key] + self._ttl < monotonic()


def _make_ssl_context(verified: bool) -> SSLContext:
    """Create SSL context.

    This method is not async-friendly and should be called from a thread
    because it will load certificates from disk and do other blocking I/O.
    """
    if ssl is None:
        # No ssl support
        return None
    if verified:
        return ssl.create_default_context()
    sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    sslcontext.options |= ssl.OP_NO_SSLv2
    sslcontext.options |= ssl.OP_NO_SSLv3
    sslcontext.check_hostname = False
    sslcontext.verify_mode = ssl.CERT_NONE
    sslcontext.options |= ssl.OP_NO_COMPRESSION
    sslcontext.set_default_verify_paths()
    return sslcontext


# The default SSLContext objects are created at import time
# since they do blocking I/O to load certificates from disk,
# and imports should always be done before the event loop starts
# or in a thread.
_SSL_CONTEXT_VERIFIED = _make_ssl_context(True)
_SSL_CONTEXT_UNVERIFIED = _make_ssl_context(False)


class TCPConnector(BaseConnector):
    """TCP connector.

    verify_ssl - Set to True to check ssl certifications.
    fingerprint - Pass the binary sha256
        digest of the expected certificate in DER format to verify
        that the certificate the server presents matches. See also
        https://en.wikipedia.org/wiki/HTTP_Public_Key_Pinning
    resolver - Enable DNS lookups and use this
        resolver
    use_dns_cache - Use memory cache for DNS lookups.
    ttl_dns_cache - Max seconds having cached a DNS entry, None forever.
    family - socket address family
    local_addr - local tuple of (host, port) to bind socket to

    keepalive_timeout - (optional) Keep-alive timeout.
    force_close - Set to True to force close and do reconnect
        after each request (and between redirects).
    limit - The total number of simultaneous connections.
    limit_per_host - Number of simultaneous connections to one host.
    enable_cleanup_closed - Enables clean-up closed ssl transports.
                            Disabled by default.
    happy_eyeballs_delay - This is the “Connection Attempt Delay”
                           as defined in RFC 8305. To disable
                           the happy eyeballs algorithm, set to None.
    interleave - “First Address Family Count” as defined in RFC 8305
    loop - Optional event loop.
    """

    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"tcp"})

    def __init__(
        self,
        *,
        verify_ssl: bool = True,
        fingerprint: Optional[bytes] = None,
        use_dns_cache: bool = True,
        ttl_dns_cache: Optional[int] = 10,
        family: socket.AddressFamily = socket.AddressFamily.AF_UNSPEC,
        ssl_context: Optional[SSLContext] = None,
        ssl: Union[bool, Fingerprint, SSLContext] = True,
        local_addr: Optional[Tuple[str, int]] = None,
        resolver: Optional[AbstractResolver] = None,
        keepalive_timeout: Union[None, float, object] = sentinel,
        force_close: bool = False,
        limit: int = 100,
        limit_per_host: int = 0,
        enable_cleanup_closed: bool = False,
        loop: Optional[asyncio.AbstractEventLoop] = None,
        timeout_ceil_threshold: float = 5,
        happy_eyeballs_delay: Optional[float] = 0.25,
        interleave: Optional[int] = None,
    ):
        super().__init__(
            keepalive_timeout=keepalive_timeout,
            force_close=force_close,
            limit=limit,
            limit_per_host=limit_per_host,
            enable_cleanup_closed=enable_cleanup_closed,
            loop=loop,
            timeout_ceil_threshold=timeout_ceil_threshold,
        )

        self._ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)
        if resolver is None:
            resolver = DefaultResolver(loop=self._loop)
        self._resolver = resolver

        self._use_dns_cache = use_dns_cache
        self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache)
        self._throttle_dns_futures: Dict[
            Tuple[str, int], Set["asyncio.Future[None]"]
        ] = {}
        self._family = family
        self._local_addr_infos = aiohappyeyeballs.addr_to_addr_infos(local_addr)
        self._happy_eyeballs_delay = happy_eyeballs_delay
        self._interleave = interleave
        self._resolve_host_tasks: Set["asyncio.Task[List[ResolveResult]]"] = set()

    def close(self) -> Awaitable[None]:
        """Close all ongoing DNS calls."""
        for fut in chain.from_iterable(self._throttle_dns_futures.values()):
            fut.cancel()

        for t in self._resolve_host_tasks:
            t.cancel()

        return super().close()

    @property
    def family(self) -> int:
        """Socket family like AF_INET."""
        return self._family

    @property
    def use_dns_cache(self) -> bool:
        """True if local DNS caching is enabled."""
        return self._use_dns_cache

    def clear_dns_cache(
        self, host: Optional[str] = None, port: Optional[int] = None
    ) -> None:
        """Remove specified host/port or clear all dns local cache."""
        if host is not None and port is not None:
            self._cached_hosts.remove((host, port))
        elif host is not None or port is not None:
            raise ValueError("either both host and port or none of them are allowed")
        else:
            self._cached_hosts.clear()

    async def _resolve_host(
        self, host: str, port: int, traces: Optional[Sequence["Trace"]] = None
    ) -> List[ResolveResult]:
        """Resolve host and return list of addresses."""
        if is_ip_address(host):
            return [
                {
                    "hostname": host,
                    "host": host,
                    "port": port,
                    "family": self._family,
                    "proto": 0,
                    "flags": 0,
                }
            ]

        if not self._use_dns_cache:

            if traces:
                for trace in traces:
                    await trace.send_dns_resolvehost_start(host)

            res = await self._resolver.resolve(host, port, family=self._family)

            if traces:
                for trace in traces:
                    await trace.send_dns_resolvehost_end(host)

            return res

        key = (host, port)
        if key in self._cached_hosts and not self._cached_hosts.expired(key):
            # get result early, before any await (#4014)
            result = self._cached_hosts.next_addrs(key)

            if traces:
                for trace in traces:
                    await trace.send_dns_cache_hit(host)
            return result

        futures: Set["asyncio.Future[None]"]
        #
        # If multiple connectors are resolving the same host, we wait
        # for the first one to resolve and then use the result for all of them.
        # We use a throttle to ensure that we only resolve the host once
        # and then use the result for all the waiters.
        #
        if key in self._throttle_dns_futures:
            # get futures early, before any await (#4014)
            futures = self._throttle_dns_futures[key]
            future: asyncio.Future[None] = self._loop.create_future()
            futures.add(future)
            if traces:
                for trace in traces:
                    await trace.send_dns_cache_hit(host)
            try:
                await future
            finally:
                futures.discard(future)
            return self._cached_hosts.next_addrs(key)

        # update dict early, before any await (#4014)
        self._throttle_dns_futures[key] = futures = set()
        # In this case we need to create a task to ensure that we can shield
        # the task from cancellation as cancelling this lookup should not cancel
        # the underlying lookup or else the cancel event will get broadcast to
        # all the waiters across all connections.
        #
        coro = self._resolve_host_with_throttle(key, host, port, futures, traces)
        loop = asyncio.get_running_loop()
        if sys.version_info >= (3, 12):
            # Optimization for Python 3.12, try to send immediately
            resolved_host_task = asyncio.Task(coro, loop=loop, eager_start=True)
        else:
            resolved_host_task = loop.create_task(coro)

        if not resolved_host_task.done():
            self._resolve_host_tasks.add(resolved_host_task)
            resolved_host_task.add_done_callback(self._resolve_host_tasks.discard)

        try:
            return await asyncio.shield(resolved_host_task)
        except asyncio.CancelledError:

            def drop_exception(fut: "asyncio.Future[List[ResolveResult]]") -> None:
                with suppress(Exception, asyncio.CancelledError):
                    fut.result()

            resolved_host_task.add_done_callback(drop_exception)
            raise

    async def _resolve_host_with_throttle(
        self,
        key: Tuple[str, int],
        host: str,
        port: int,
        futures: Set["asyncio.Future[None]"],
        traces: Optional[Sequence["Trace"]],
    ) -> List[ResolveResult]:
        """Resolve host and set result for all waiters.

        This method must be run in a task and shielded from cancellation
        to avoid cancelling the underlying lookup.
        """
        if traces:
            for trace in traces:
                await trace.send_dns_cache_miss(host)
        try:
            if traces:
                for trace in traces:
                    await trace.send_dns_resolvehost_start(host)

            addrs = await self._resolver.resolve(host, port, family=self._family)
            if traces:
                for trace in traces:
                    await trace.send_dns_resolvehost_end(host)

            self._cached_hosts.add(key, addrs)
            for fut in futures:
                set_result(fut, None)
        except BaseException as e:
            # any DNS exception is set for the waiters to raise the same exception.
            # This coro is always run in task that is shielded from cancellation so
            # we should never be propagating cancellation here.
            for fut in futures:
                set_exception(fut, e)
            raise
        finally:
            self._throttle_dns_futures.pop(key)

        return self._cached_hosts.next_addrs(key)

    async def _create_connection(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> ResponseHandler:
        """Create connection.

        Has same keyword arguments as BaseEventLoop.create_connection.
        """
        if req.proxy:
            _, proto = await self._create_proxy_connection(req, traces, timeout)
        else:
            _, proto = await self._create_direct_connection(req, traces, timeout)

        return proto

    def _get_ssl_context(self, req: ClientRequest) -> Optional[SSLContext]:
        """Logic to get the correct SSL context

        0. if req.ssl is false, return None

        1. if ssl_context is specified in req, use it
        2. if _ssl_context is specified in self, use it
        3. otherwise:
            1. if verify_ssl is not specified in req, use self.ssl_context
               (will generate a default context according to self.verify_ssl)
            2. if verify_ssl is True in req, generate a default SSL context
            3. if verify_ssl is False in req, generate a SSL context that
               won't verify
        """
        if not req.is_ssl():
            return None

        if ssl is None:  # pragma: no cover
            raise RuntimeError("SSL is not supported.")
        sslcontext = req.ssl
        if isinstance(sslcontext, ssl.SSLContext):
            return sslcontext
        if sslcontext is not True:
            # not verified or fingerprinted
            return _SSL_CONTEXT_UNVERIFIED
        sslcontext = self._ssl
        if isinstance(sslcontext, ssl.SSLContext):
            return sslcontext
        if sslcontext is not True:
            # not verified or fingerprinted
            return _SSL_CONTEXT_UNVERIFIED
        return _SSL_CONTEXT_VERIFIED

    def _get_fingerprint(self, req: ClientRequest) -> Optional["Fingerprint"]:
        ret = req.ssl
        if isinstance(ret, Fingerprint):
            return ret
        ret = self._ssl
        if isinstance(ret, Fingerprint):
            return ret
        return None

    async def _wrap_create_connection(
        self,
        *args: Any,
        addr_infos: List[aiohappyeyeballs.AddrInfoType],
        req: ClientRequest,
        timeout: "ClientTimeout",
        client_error: Type[Exception] = ClientConnectorError,
        **kwargs: Any,
    ) -> Tuple[asyncio.Transport, ResponseHandler]:
        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                sock = await aiohappyeyeballs.start_connection(
                    addr_infos=addr_infos,
                    local_addr_infos=self._local_addr_infos,
                    happy_eyeballs_delay=self._happy_eyeballs_delay,
                    interleave=self._interleave,
                    loop=self._loop,
                )
                return await self._loop.create_connection(*args, **kwargs, sock=sock)
        except cert_errors as exc:
            raise ClientConnectorCertificateError(req.connection_key, exc) from exc
        except ssl_errors as exc:
            raise ClientConnectorSSLError(req.connection_key, exc) from exc
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            raise client_error(req.connection_key, exc) from exc

    async def _wrap_existing_connection(
        self,
        *args: Any,
        req: ClientRequest,
        timeout: "ClientTimeout",
        client_error: Type[Exception] = ClientConnectorError,
        **kwargs: Any,
    ) -> Tuple[asyncio.Transport, ResponseHandler]:
        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                return await self._loop.create_connection(*args, **kwargs)
        except cert_errors as exc:
            raise ClientConnectorCertificateError(req.connection_key, exc) from exc
        except ssl_errors as exc:
            raise ClientConnectorSSLError(req.connection_key, exc) from exc
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            raise client_error(req.connection_key, exc) from exc

    def _fail_on_no_start_tls(self, req: "ClientRequest") -> None:
        """Raise a :py:exc:`RuntimeError` on missing ``start_tls()``.

        It is necessary for TLS-in-TLS so that it is possible to
        send HTTPS queries through HTTPS proxies.

        This doesn't affect regular HTTP requests, though.
        """
        if not req.is_ssl():
            return

        proxy_url = req.proxy
        assert proxy_url is not None
        if proxy_url.scheme != "https":
            return

        self._check_loop_for_start_tls()

    def _check_loop_for_start_tls(self) -> None:
        try:
            self._loop.start_tls
        except AttributeError as attr_exc:
            raise RuntimeError(
                "An HTTPS request is being sent through an HTTPS proxy. "
                "This needs support for TLS in TLS but it is not implemented "
                "in your runtime for the stdlib asyncio.\n\n"
                "Please upgrade to Python 3.11 or higher. For more details, "
                "please see:\n"
                "* https://bugs.python.org/issue37179\n"
                "* https://github.com/python/cpython/pull/28073\n"
                "* https://docs.aiohttp.org/en/stable/"
                "client_advanced.html#proxy-support\n"
                "* https://github.com/aio-libs/aiohttp/discussions/6044\n",
            ) from attr_exc

    def _loop_supports_start_tls(self) -> bool:
        try:
            self._check_loop_for_start_tls()
        except RuntimeError:
            return False
        else:
            return True

    def _warn_about_tls_in_tls(
        self,
        underlying_transport: asyncio.Transport,
        req: ClientRequest,
    ) -> None:
        """Issue a warning if the requested URL has HTTPS scheme."""
        if req.request_info.url.scheme != "https":
            return

        asyncio_supports_tls_in_tls = getattr(
            underlying_transport,
            "_start_tls_compatible",
            False,
        )

        if asyncio_supports_tls_in_tls:
            return

        warnings.warn(
            "An HTTPS request is being sent through an HTTPS proxy. "
            "This support for TLS in TLS is known to be disabled "
            "in the stdlib asyncio (Python <3.11). This is why you'll probably see "
            "an error in the log below.\n\n"
            "It is possible to enable it via monkeypatching. "
            "For more details, see:\n"
            "* https://bugs.python.org/issue37179\n"
            "* https://github.com/python/cpython/pull/28073\n\n"
            "You can temporarily patch this as follows:\n"
            "* https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support\n"
            "* https://github.com/aio-libs/aiohttp/discussions/6044\n",
            RuntimeWarning,
            source=self,
            # Why `4`? At least 3 of the calls in the stack originate
            # from the methods in this class.
            stacklevel=3,
        )

    async def _start_tls_connection(
        self,
        underlying_transport: asyncio.Transport,
        req: ClientRequest,
        timeout: "ClientTimeout",
        client_error: Type[Exception] = ClientConnectorError,
    ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
        """Wrap the raw TCP transport with TLS."""
        tls_proto = self._factory()  # Create a brand new proto for TLS
        sslcontext = self._get_ssl_context(req)
        if TYPE_CHECKING:
            # _start_tls_connection is unreachable in the current code path
            # if sslcontext is None.
            assert sslcontext is not None

        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                try:
                    tls_transport = await self._loop.start_tls(
                        underlying_transport,
                        tls_proto,
                        sslcontext,
                        server_hostname=req.server_hostname or req.host,
                        ssl_handshake_timeout=timeout.total,
                    )
                except BaseException:
                    # We need to close the underlying transport since
                    # `start_tls()` probably failed before it had a
                    # chance to do this:
                    underlying_transport.close()
                    raise
                if isinstance(tls_transport, asyncio.Transport):
                    fingerprint = self._get_fingerprint(req)
                    if fingerprint:
                        try:
                            fingerprint.check(tls_transport)
                        except ServerFingerprintMismatch:
                            tls_transport.close()
                            if not self._cleanup_closed_disabled:
                                self._cleanup_closed_transports.append(tls_transport)
                            raise
        except cert_errors as exc:
            raise ClientConnectorCertificateError(req.connection_key, exc) from exc
        except ssl_errors as exc:
            raise ClientConnectorSSLError(req.connection_key, exc) from exc
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            raise client_error(req.connection_key, exc) from exc
        except TypeError as type_err:
            # Example cause looks like this:
            # TypeError: transport <asyncio.sslproto._SSLProtocolTransport
            # object at 0x7f760615e460> is not supported by start_tls()

            raise ClientConnectionError(
                "Cannot initialize a TLS-in-TLS connection to host "
                f"{req.host!s}:{req.port:d} through an underlying connection "
                f"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} "
                f"[{type_err!s}]"
            ) from type_err
        else:
            if tls_transport is None:
                msg = "Failed to start TLS (possibly caused by closing transport)"
                raise client_error(req.connection_key, OSError(msg))
            tls_proto.connection_made(
                tls_transport
            )  # Kick the state machine of the new TLS protocol

        return tls_transport, tls_proto

    def _convert_hosts_to_addr_infos(
        self, hosts: List[ResolveResult]
    ) -> List[aiohappyeyeballs.AddrInfoType]:
        """Converts the list of hosts to a list of addr_infos.

        The list of hosts is the result of a DNS lookup. The list of
        addr_infos is the result of a call to `socket.getaddrinfo()`.
        """
        addr_infos: List[aiohappyeyeballs.AddrInfoType] = []
        for hinfo in hosts:
            host = hinfo["host"]
            is_ipv6 = ":" in host
            family = socket.AF_INET6 if is_ipv6 else socket.AF_INET
            if self._family and self._family != family:
                continue
            addr = (host, hinfo["port"], 0, 0) if is_ipv6 else (host, hinfo["port"])
            addr_infos.append(
                (family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", addr)
            )
        return addr_infos

    async def _create_direct_connection(
        self,
        req: ClientRequest,
        traces: List["Trace"],
        timeout: "ClientTimeout",
        *,
        client_error: Type[Exception] = ClientConnectorError,
    ) -> Tuple[asyncio.Transport, ResponseHandler]:
        sslcontext = self._get_ssl_context(req)
        fingerprint = self._get_fingerprint(req)

        host = req.url.raw_host
        assert host is not None
        # Replace multiple trailing dots with a single one.
        # A trailing dot is only present for fully-qualified domain names.
        # See https://github.com/aio-libs/aiohttp/pull/7364.
        if host.endswith(".."):
            host = host.rstrip(".") + "."
        port = req.port
        assert port is not None
        try:
            # Cancelling this lookup should not cancel the underlying lookup
            #  or else the cancel event will get broadcast to all the waiters
            #  across all connections.
            hosts = await self._resolve_host(host, port, traces=traces)
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            # in case of proxy it is not ClientProxyConnectionError
            # it is problem of resolving proxy ip itself
            raise ClientConnectorDNSError(req.connection_key, exc) from exc

        last_exc: Optional[Exception] = None
        addr_infos = self._convert_hosts_to_addr_infos(hosts)
        while addr_infos:
            # Strip trailing dots, certificates contain FQDN without dots.
            # See https://github.com/aio-libs/aiohttp/issues/3636
            server_hostname = (
                (req.server_hostname or host).rstrip(".") if sslcontext else None
            )

            try:
                transp, proto = await self._wrap_create_connection(
                    self._factory,
                    timeout=timeout,
                    ssl=sslcontext,
                    addr_infos=addr_infos,
                    server_hostname=server_hostname,
                    req=req,
                    client_error=client_error,
                )
            except (ClientConnectorError, asyncio.TimeoutError) as exc:
                last_exc = exc
                aiohappyeyeballs.pop_addr_infos_interleave(addr_infos, self._interleave)
                continue

            if req.is_ssl() and fingerprint:
                try:
                    fingerprint.check(transp)
                except ServerFingerprintMismatch as exc:
                    transp.close()
                    if not self._cleanup_closed_disabled:
                        self._cleanup_closed_transports.append(transp)
                    last_exc = exc
                    # Remove the bad peer from the list of addr_infos
                    sock: socket.socket = transp.get_extra_info("socket")
                    bad_peer = sock.getpeername()
                    aiohappyeyeballs.remove_addr_infos(addr_infos, bad_peer)
                    continue

            return transp, proto
        else:
            assert last_exc is not None
            raise last_exc

    async def _create_proxy_connection(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
        self._fail_on_no_start_tls(req)
        runtime_has_start_tls = self._loop_supports_start_tls()

        headers: Dict[str, str] = {}
        if req.proxy_headers is not None:
            headers = req.proxy_headers  # type: ignore[assignment]
        headers[hdrs.HOST] = req.headers[hdrs.HOST]

        url = req.proxy
        assert url is not None
        proxy_req = ClientRequest(
            hdrs.METH_GET,
            url,
            headers=headers,
            auth=req.proxy_auth,
            loop=self._loop,
            ssl=req.ssl,
        )

        # create connection to proxy server
        transport, proto = await self._create_direct_connection(
            proxy_req, [], timeout, client_error=ClientProxyConnectionError
        )

        auth = proxy_req.headers.pop(hdrs.AUTHORIZATION, None)
        if auth is not None:
            if not req.is_ssl():
                req.headers[hdrs.PROXY_AUTHORIZATION] = auth
            else:
                proxy_req.headers[hdrs.PROXY_AUTHORIZATION] = auth

        if req.is_ssl():
            if runtime_has_start_tls:
                self._warn_about_tls_in_tls(transport, req)

            # For HTTPS requests over HTTP proxy
            # we must notify proxy to tunnel connection
            # so we send CONNECT command:
            #   CONNECT www.python.org:443 HTTP/1.1
            #   Host: www.python.org
            #
            # next we must do TLS handshake and so on
            # to do this we must wrap raw socket into secure one
            # asyncio handles this perfectly
            proxy_req.method = hdrs.METH_CONNECT
            proxy_req.url = req.url
            key = req.connection_key._replace(
                proxy=None, proxy_auth=None, proxy_headers_hash=None
            )
            conn = Connection(self, key, proto, self._loop)
            proxy_resp = await proxy_req.send(conn)
            try:
                protocol = conn._protocol
                assert protocol is not None

                # read_until_eof=True will ensure the connection isn't closed
                # once the response is received and processed allowing
                # START_TLS to work on the connection below.
                protocol.set_response_params(
                    read_until_eof=runtime_has_start_tls,
                    timeout_ceil_threshold=self._timeout_ceil_threshold,
                )
                resp = await proxy_resp.start(conn)
            except BaseException:
                proxy_resp.close()
                conn.close()
                raise
            else:
                conn._protocol = None
                try:
                    if resp.status != 200:
                        message = resp.reason
                        if message is None:
                            message = HTTPStatus(resp.status).phrase
                        raise ClientHttpProxyError(
                            proxy_resp.request_info,
                            resp.history,
                            status=resp.status,
                            message=message,
                            headers=resp.headers,
                        )
                    if not runtime_has_start_tls:
                        rawsock = transport.get_extra_info("socket", default=None)
                        if rawsock is None:
                            raise RuntimeError(
                                "Transport does not expose socket instance"
                            )
                        # Duplicate the socket, so now we can close proxy transport
                        rawsock = rawsock.dup()
                except BaseException:
                    # It shouldn't be closed in `finally` because it's fed to
                    # `loop.start_tls()` and the docs say not to touch it after
                    # passing there.
                    transport.close()
                    raise
                finally:
                    if not runtime_has_start_tls:
                        transport.close()

                if not runtime_has_start_tls:
                    # HTTP proxy with support for upgrade to HTTPS
                    sslcontext = self._get_ssl_context(req)
                    return await self._wrap_existing_connection(
                        self._factory,
                        timeout=timeout,
                        ssl=sslcontext,
                        sock=rawsock,
                        server_hostname=req.host,
                        req=req,
                    )

                return await self._start_tls_connection(
                    # Access the old transport for the last time before it's
                    # closed and forgotten forever:
                    transport,
                    req=req,
                    timeout=timeout,
                )
            finally:
                proxy_resp.close()

        return transport, proto


class UnixConnector(BaseConnector):
    """Unix socket connector.

    path - Unix socket path.
    keepalive_timeout - (optional) Keep-alive timeout.
    force_close - Set to True to force close and do reconnect
        after each request (and between redirects).
    limit - The total number of simultaneous connections.
    limit_per_host - Number of simultaneous connections to one host.
    loop - Optional event loop.
    """

    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"unix"})

    def __init__(
        self,
        path: str,
        force_close: bool = False,
        keepalive_timeout: Union[object, float, None] = sentinel,
        limit: int = 100,
        limit_per_host: int = 0,
        loop: Optional[asyncio.AbstractEventLoop] = None,
    ) -> None:
        super().__init__(
            force_close=force_close,
            keepalive_timeout=keepalive_timeout,
            limit=limit,
            limit_per_host=limit_per_host,
            loop=loop,
        )
        self._path = path

    @property
    def path(self) -> str:
        """Path to unix socket."""
        return self._path

    async def _create_connection(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> ResponseHandler:
        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                _, proto = await self._loop.create_unix_connection(
                    self._factory, self._path
                )
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc

        return proto


class NamedPipeConnector(BaseConnector):
    """Named pipe connector.

    Only supported by the proactor event loop.
    See also: https://docs.python.org/3/library/asyncio-eventloop.html

    path - Windows named pipe path.
    keepalive_timeout - (optional) Keep-alive timeout.
    force_close - Set to True to force close and do reconnect
        after each request (and between redirects).
    limit - The total number of simultaneous connections.
    limit_per_host - Number of simultaneous connections to one host.
    loop - Optional event loop.
    """

    allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"npipe"})

    def __init__(
        self,
        path: str,
        force_close: bool = False,
        keepalive_timeout: Union[object, float, None] = sentinel,
        limit: int = 100,
        limit_per_host: int = 0,
        loop: Optional[asyncio.AbstractEventLoop] = None,
    ) -> None:
        super().__init__(
            force_close=force_close,
            keepalive_timeout=keepalive_timeout,
            limit=limit,
            limit_per_host=limit_per_host,
            loop=loop,
        )
        if not isinstance(
            self._loop, asyncio.ProactorEventLoop  # type: ignore[attr-defined]
        ):
            raise RuntimeError(
                "Named Pipes only available in proactor loop under windows"
            )
        self._path = path

    @property
    def path(self) -> str:
        """Path to the named pipe."""
        return self._path

    async def _create_connection(
        self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
    ) -> ResponseHandler:
        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                _, proto = await self._loop.create_pipe_connection(  # type: ignore[attr-defined]
                    self._factory, self._path
                )
                # the drain is required so that the connection_made is called
                # and transport is set otherwise it is not set before the
                # `assert conn.transport is not None`
                # in client.py's _request method
                await asyncio.sleep(0)
                # other option is to manually set transport like
                # `proto.transport = trans`
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            raise ClientConnectorError(req.connection_key, exc) from exc

        return cast(ResponseHandler, proto)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user