{
    "file_diffs": [
        {
            "old_file_content": "",
            "new_file_content": "Added ``writer_limit`` to the :py:class:`~aiohttp.web.WebSocketResponse` to be able to adjust the limit before the writer forces the buffer to be drained -- by :user:`bdraco`.\n",
            "header": {
                "file": {
                    "path": "CHANGES/9572.feature.rst"
                },
                "misc_line": "new file mode 100644"
            },
            "index_line": {
                "old_commit_hash": "00000000",
                "new_commit_hash": "9e677881",
                "mode": ""
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "/dev/null"
            },
            "plus_file": {
                "path": "b/CHANGES/9572.feature.rst"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 0,
                            "length": 0
                        },
                        "new_range": {
                            "start": 1,
                            "length": null
                        },
                        "section": ""
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "Added ``writer_limit`` to the :py:class:`~aiohttp.web.WebSocketResponse` to be able to adjust the limit before the writer forces the buffer to be drained -- by :user:`bdraco`.",
                                "type": "added"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import asyncio\nimport base64\nimport binascii\nimport dataclasses\nimport hashlib\nimport json\nimport sys\nfrom typing import Any, Final, Iterable, Optional, Tuple\n\nfrom multidict import CIMultiDict\n\nfrom . import hdrs\nfrom .abc import AbstractStreamWriter\nfrom .helpers import calculate_timeout_when, set_exception, set_result\nfrom .http import (\n    WS_CLOSED_MESSAGE,\n    WS_CLOSING_MESSAGE,\n    WS_KEY,\n    WebSocketError,\n    WebSocketReader,\n    WebSocketWriter,\n    WSCloseCode,\n    WSMessage,\n    WSMsgType,\n    ws_ext_gen,\n    ws_ext_parse,\n)\nfrom .http_websocket import WSMessageError\nfrom .log import ws_logger\nfrom .streams import EofStream, FlowControlDataQueue\nfrom .typedefs import JSONDecoder, JSONEncoder\nfrom .web_exceptions import HTTPBadRequest, HTTPException\nfrom .web_request import BaseRequest\nfrom .web_response import StreamResponse\n\nif sys.version_info >= (3, 11):\n    import asyncio as async_timeout\nelse:\n    import async_timeout\n\n__all__ = (\n    \"WebSocketResponse\",\n    \"WebSocketReady\",\n    \"WSMsgType\",\n)\n\nTHRESHOLD_CONNLOST_ACCESS: Final[int] = 5\n\n\n@dataclasses.dataclass(frozen=True)\nclass WebSocketReady:\n    ok: bool\n    protocol: Optional[str]\n\n    def __bool__(self) -> bool:\n        return self.ok\n\n\nclass WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol, transport, compress=compress, notakeover=notakeover\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)\n",
            "new_file_content": "import asyncio\nimport base64\nimport binascii\nimport dataclasses\nimport hashlib\nimport json\nimport sys\nfrom typing import Any, Final, Iterable, Optional, Tuple\n\nfrom multidict import CIMultiDict\n\nfrom . import hdrs\nfrom ._websocket.writer import DEFAULT_LIMIT\nfrom .abc import AbstractStreamWriter\nfrom .helpers import calculate_timeout_when, set_exception, set_result\nfrom .http import (\n    WS_CLOSED_MESSAGE,\n    WS_CLOSING_MESSAGE,\n    WS_KEY,\n    WebSocketError,\n    WebSocketReader,\n    WebSocketWriter,\n    WSCloseCode,\n    WSMessage,\n    WSMsgType,\n    ws_ext_gen,\n    ws_ext_parse,\n)\nfrom .http_websocket import WSMessageError\nfrom .log import ws_logger\nfrom .streams import EofStream, FlowControlDataQueue\nfrom .typedefs import JSONDecoder, JSONEncoder\nfrom .web_exceptions import HTTPBadRequest, HTTPException\nfrom .web_request import BaseRequest\nfrom .web_response import StreamResponse\n\nif sys.version_info >= (3, 11):\n    import asyncio as async_timeout\nelse:\n    import async_timeout\n\n__all__ = (\n    \"WebSocketResponse\",\n    \"WebSocketReady\",\n    \"WSMsgType\",\n)\n\nTHRESHOLD_CONNLOST_ACCESS: Final[int] = 5\n\n\n@dataclasses.dataclass(frozen=True)\nclass WebSocketReady:\n    ok: bool\n    protocol: Optional[str]\n\n    def __bool__(self) -> bool:\n        return self.ok\n\n\nclass WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n        \"_writer_limit\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n        writer_limit: int = DEFAULT_LIMIT,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n        self._writer_limit = writer_limit\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol,\n            transport,\n            compress=compress,\n            notakeover=notakeover,\n            limit=self._writer_limit,\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)\n",
            "header": {
                "file": {
                    "path": "aiohttp/web_ws.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "9fa78dd9",
                "new_commit_hash": "007e309d",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/aiohttp/web_ws.py"
            },
            "plus_file": {
                "path": "b/aiohttp/web_ws.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 10,
                            "length": 6
                        },
                        "new_range": {
                            "start": 10,
                            "length": 7
                        },
                        "section": "from typing import Any, Final, Iterable, Optional, Tuple"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "from multidict import CIMultiDict",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from . import hdrs",
                                "type": "context"
                            },
                            {
                                "content": "from ._websocket.writer import DEFAULT_LIMIT",
                                "type": "added"
                            },
                            {
                                "content": "from .abc import AbstractStreamWriter",
                                "type": "context"
                            },
                            {
                                "content": "from .helpers import calculate_timeout_when, set_exception, set_result",
                                "type": "context"
                            },
                            {
                                "content": "from .http import (",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "statement",
                            "name": "",
                            "content": "from ._websocket.writer import DEFAULT_LIMIT",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 13,
                            "end_lineno": 13,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 82,
                            "length": 6
                        },
                        "new_range": {
                            "start": 83,
                            "length": 7
                        },
                        "section": "class WebSocketResponse(StreamResponse):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        \"_compress\",",
                                "type": "context"
                            },
                            {
                                "content": "        \"_max_msg_size\",",
                                "type": "context"
                            },
                            {
                                "content": "        \"_ping_task\",",
                                "type": "context"
                            },
                            {
                                "content": "        \"_writer_limit\",",
                                "type": "added"
                            },
                            {
                                "content": "    )",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def __init__(",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "class",
                            "name": "WebSocketResponse",
                            "content": "class WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n        \"_writer_limit\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n        writer_limit: int = DEFAULT_LIMIT,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n        self._writer_limit = writer_limit\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol,\n            transport,\n            compress=compress,\n            notakeover=notakeover,\n            limit=self._writer_limit,\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 60,
                            "end_lineno": 645,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 95,
                            "length": 6
                        },
                        "new_range": {
                            "start": 97,
                            "length": 7
                        },
                        "section": "class WebSocketResponse(StreamResponse):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        protocols: Iterable[str] = (),",
                                "type": "context"
                            },
                            {
                                "content": "        compress: bool = True,",
                                "type": "context"
                            },
                            {
                                "content": "        max_msg_size: int = 4 * 1024 * 1024,",
                                "type": "context"
                            },
                            {
                                "content": "        writer_limit: int = DEFAULT_LIMIT,",
                                "type": "added"
                            },
                            {
                                "content": "    ) -> None:",
                                "type": "context"
                            },
                            {
                                "content": "        super().__init__(status=101)",
                                "type": "context"
                            },
                            {
                                "content": "        self._length_check = False",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "class",
                            "name": "WebSocketResponse",
                            "content": "class WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n        \"_writer_limit\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n        writer_limit: int = DEFAULT_LIMIT,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n        self._writer_limit = writer_limit\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol,\n            transport,\n            compress=compress,\n            notakeover=notakeover,\n            limit=self._writer_limit,\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 60,
                            "end_lineno": 645,
                            "parent": null
                        },
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "method",
                            "name": "WebSocketResponse.__init__",
                            "content": "class WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n        \"_writer_limit\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n        writer_limit: int = DEFAULT_LIMIT,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n        self._writer_limit = writer_limit\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol,\n            transport,\n            compress=compress,\n            notakeover=notakeover,\n            limit=self._writer_limit,\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 89,
                            "end_lineno": 129,
                            "parent": {
                                "file_name": "aiohttp/web_ws.py",
                                "type": "class",
                                "name": "WebSocketResponse",
                                "content": "class WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n        \"_writer_limit\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n        writer_limit: int = DEFAULT_LIMIT,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n        self._writer_limit = writer_limit\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol,\n            transport,\n            compress=compress,\n            notakeover=notakeover,\n            limit=self._writer_limit,\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 60,
                                "end_lineno": 645,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 123,
                            "length": 6
                        },
                        "new_range": {
                            "start": 126,
                            "length": 7
                        },
                        "section": "class WebSocketResponse(StreamResponse):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self._compress = compress",
                                "type": "context"
                            },
                            {
                                "content": "        self._max_msg_size = max_msg_size",
                                "type": "context"
                            },
                            {
                                "content": "        self._ping_task: Optional[asyncio.Task[None]] = None",
                                "type": "context"
                            },
                            {
                                "content": "        self._writer_limit = writer_limit",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def _cancel_heartbeat(self) -> None:",
                                "type": "context"
                            },
                            {
                                "content": "        self._cancel_pong_response_cb()",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "class",
                            "name": "WebSocketResponse",
                            "content": "class WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n        \"_writer_limit\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n        writer_limit: int = DEFAULT_LIMIT,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n        self._writer_limit = writer_limit\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol,\n            transport,\n            compress=compress,\n            notakeover=notakeover,\n            limit=self._writer_limit,\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 60,
                            "end_lineno": 645,
                            "parent": null
                        },
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "method",
                            "name": "WebSocketResponse.__init__",
                            "content": "class WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n        \"_writer_limit\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n        writer_limit: int = DEFAULT_LIMIT,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n        self._writer_limit = writer_limit\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol,\n            transport,\n            compress=compress,\n            notakeover=notakeover,\n            limit=self._writer_limit,\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 89,
                            "end_lineno": 129,
                            "parent": {
                                "file_name": "aiohttp/web_ws.py",
                                "type": "class",
                                "name": "WebSocketResponse",
                                "content": "class WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n        \"_writer_limit\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n        writer_limit: int = DEFAULT_LIMIT,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n        self._writer_limit = writer_limit\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol,\n            transport,\n            compress=compress,\n            notakeover=notakeover,\n            limit=self._writer_limit,\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 60,
                                "end_lineno": 645,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 331,
                            "length": 7
                        },
                        "new_range": {
                            "start": 335,
                            "length": 11
                        },
                        "section": "class WebSocketResponse(StreamResponse):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        transport = request._protocol.transport",
                                "type": "context"
                            },
                            {
                                "content": "        assert transport is not None",
                                "type": "context"
                            },
                            {
                                "content": "        writer = WebSocketWriter(",
                                "type": "context"
                            },
                            {
                                "content": "            request._protocol, transport, compress=compress, notakeover=notakeover",
                                "type": "deleted"
                            },
                            {
                                "content": "            request._protocol,",
                                "type": "added"
                            },
                            {
                                "content": "            transport,",
                                "type": "added"
                            },
                            {
                                "content": "            compress=compress,",
                                "type": "added"
                            },
                            {
                                "content": "            notakeover=notakeover,",
                                "type": "added"
                            },
                            {
                                "content": "            limit=self._writer_limit,",
                                "type": "added"
                            },
                            {
                                "content": "        )",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        return protocol, writer",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "class",
                            "name": "WebSocketResponse",
                            "content": "class WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol, transport, compress=compress, notakeover=notakeover\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 59,
                            "end_lineno": 637,
                            "parent": null
                        },
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "method",
                            "name": "WebSocketResponse._pre_start",
                            "content": "class WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol, transport, compress=compress, notakeover=notakeover\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 322,
                            "end_lineno": 337,
                            "parent": {
                                "file_name": "aiohttp/web_ws.py",
                                "type": "class",
                                "name": "WebSocketResponse",
                                "content": "class WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don’t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol, transport, compress=compress, notakeover=notakeover\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 59,
                                "end_lineno": 637,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": ".. currentmodule:: aiohttp.web\n\n.. _aiohttp-web-reference:\n\nServer Reference\n================\n\n.. _aiohttp-web-request:\n\n\nRequest and Base Request\n------------------------\n\nThe Request object contains all the information about an incoming HTTP request.\n\n:class:`BaseRequest` is used for :ref:`Low-Level\nServers<aiohttp-web-lowlevel>` (which have no applications, routers,\nsignals and middlewares). :class:`Request` has an :attr:`Request.app`\nand :attr:`Request.match_info` attributes.\n\nA :class:`BaseRequest` / :class:`Request` are :obj:`dict` like objects,\nallowing them to be used for :ref:`sharing\ndata<aiohttp-web-data-sharing>` among :ref:`aiohttp-web-middlewares`\nand :ref:`aiohttp-web-signals` handlers.\n\n.. class:: BaseRequest\n\n   .. attribute:: version\n\n      *HTTP version* of request, Read-only property.\n\n      Returns :class:`aiohttp.protocol.HttpVersion` instance.\n\n   .. attribute:: method\n\n      *HTTP method*, read-only property.\n\n      The value is upper-cased :class:`str` like ``\"GET\"``,\n      ``\"POST\"``, ``\"PUT\"`` etc.\n\n   .. attribute:: url\n\n      A :class:`~yarl.URL` instance with absolute URL to resource\n      (*scheme*, *host* and *port* are included).\n\n      .. note::\n\n         In case of malformed request (e.g. without ``\"HOST\"`` HTTP\n         header) the absolute url may be unavailable.\n\n   .. attribute:: rel_url\n\n      A :class:`~yarl.URL` instance with relative URL to resource\n      (contains *path*, *query* and *fragment* parts only, *scheme*,\n      *host* and *port* are excluded).\n\n      The property is equal to ``.url.relative()`` but is always present.\n\n      .. seealso::\n\n         A note from :attr:`url`.\n\n   .. attribute:: scheme\n\n      A string representing the scheme of the request.\n\n      The scheme is ``'https'`` if transport for request handling is\n      *SSL*, ``'http'`` otherwise.\n\n      The value could be overridden by :meth:`~BaseRequest.clone`.\n\n      Read-only :class:`str` property.\n\n      .. versionchanged:: 2.3\n\n         *Forwarded* and *X-Forwarded-Proto* are not used anymore.\n\n         Call ``.clone(scheme=new_scheme)`` for setting up the value\n         explicitly.\n\n      .. seealso:: :ref:`aiohttp-web-forwarded-support`\n\n   .. attribute:: secure\n\n      Shorthand for ``request.url.scheme == 'https'``\n\n      Read-only :class:`bool` property.\n\n      .. seealso:: :attr:`scheme`\n\n   .. attribute:: forwarded\n\n      A tuple containing all parsed Forwarded header(s).\n\n      Makes an effort to parse Forwarded headers as specified by :rfc:`7239`:\n\n      - It adds one (immutable) dictionary per Forwarded ``field-value``, i.e.\n        per proxy. The element corresponds to the data in the Forwarded\n        ``field-value`` added by the first proxy encountered by the client.\n        Each subsequent item corresponds to those added by later proxies.\n      - It checks that every value has valid syntax in general as specified\n        in :rfc:`7239#section-4`: either a ``token`` or a ``quoted-string``.\n      - It un-escapes ``quoted-pairs``.\n      - It does NOT validate 'by' and 'for' contents as specified in\n        :rfc:`7239#section-6`.\n      - It does NOT validate ``host`` contents (Host ABNF).\n      - It does NOT validate ``proto`` contents for valid URI scheme names.\n\n      Returns a tuple containing one or more ``MappingProxy`` objects\n\n      .. seealso:: :attr:`scheme`\n\n      .. seealso:: :attr:`host`\n\n   .. attribute:: host\n\n      Host name of the request, resolved in this order:\n\n      - Overridden value by :meth:`~BaseRequest.clone` call.\n      - *Host* HTTP header\n      - :func:`socket.getfqdn`\n\n      Read-only :class:`str` property.\n\n      .. versionchanged:: 2.3\n\n         *Forwarded* and *X-Forwarded-Host* are not used anymore.\n\n         Call ``.clone(host=new_host)`` for setting up the value\n         explicitly.\n\n      .. seealso:: :ref:`aiohttp-web-forwarded-support`\n\n   .. attribute:: remote\n\n      Originating IP address of a client initiated HTTP request.\n\n      The IP is resolved through the following headers, in this order:\n\n      - Overridden value by :meth:`~BaseRequest.clone` call.\n      - Peer name of opened socket.\n\n      Read-only :class:`str` property.\n\n      Call ``.clone(remote=new_remote)`` for setting up the value\n      explicitly.\n\n      .. versionadded:: 2.3\n\n      .. seealso:: :ref:`aiohttp-web-forwarded-support`\n\n   .. attribute:: client_max_size\n\n      The maximum size of the request body.\n\n      The value could be overridden by :meth:`~BaseRequest.clone`.\n\n      Read-only :class:`int` property.\n\n   .. attribute:: path_qs\n\n      The URL including PATH_INFO and the query string. e.g.,\n      ``/app/blog?id=10``\n\n      Read-only :class:`str` property.\n\n   .. attribute:: path\n\n      The URL including *PATH INFO* without the host or scheme. e.g.,\n      ``/app/blog``. The path is URL-decoded. For raw path info see\n      :attr:`raw_path`.\n\n      Read-only :class:`str` property.\n\n   .. attribute:: raw_path\n\n      The URL including raw *PATH INFO* without the host or scheme.\n      Warning, the path may be URL-encoded and may contain invalid URL\n      characters, e.g.\n      ``/my%2Fpath%7Cwith%21some%25strange%24characters``.\n\n      For URL-decoded version please take a look on :attr:`path`.\n\n      Read-only :class:`str` property.\n\n   .. attribute:: query\n\n      A multidict with all the variables in the query string.\n\n      Read-only :class:`~multidict.MultiDictProxy` lazy property.\n\n   .. attribute:: query_string\n\n      The query string in the URL, e.g., ``id=10``\n\n      Read-only :class:`str` property.\n\n   .. attribute:: headers\n\n      A case-insensitive multidict proxy with all headers.\n\n      Read-only :class:`~multidict.CIMultiDictProxy` property.\n\n   .. attribute:: raw_headers\n\n      HTTP headers of response as unconverted bytes, a sequence of\n      ``(key, value)`` pairs.\n\n   .. attribute:: keep_alive\n\n      ``True`` if keep-alive connection enabled by HTTP client and\n      protocol version supports it, otherwise ``False``.\n\n      Read-only :class:`bool` property.\n\n   .. attribute:: transport\n\n      A :ref:`transport<asyncio-transport>` used to process request.\n      Read-only property.\n\n      The property can be used, for example, for getting IP address of\n      client's peer::\n\n         peername = request.transport.get_extra_info('peername')\n         if peername is not None:\n             host, port = peername\n\n   .. attribute:: cookies\n\n      A read-only dictionary-like object containing the request's cookies.\n\n      Read-only :class:`~types.MappingProxyType` property.\n\n   .. attribute:: content\n\n      A :class:`~aiohttp.StreamReader` instance,\n      input stream for reading request's *BODY*.\n\n      Read-only property.\n\n   .. attribute:: body_exists\n\n      Return ``True`` if request has *HTTP BODY*, ``False`` otherwise.\n\n      Read-only :class:`bool` property.\n\n      .. versionadded:: 2.3\n\n   .. attribute:: can_read_body\n\n      Return ``True`` if request's *HTTP BODY* can be read, ``False`` otherwise.\n\n      Read-only :class:`bool` property.\n\n      .. versionadded:: 2.3\n\n   .. attribute:: content_type\n\n      Read-only property with *content* part of *Content-Type* header.\n\n      Returns :class:`str` like ``'text/html'``\n\n      .. note::\n\n         Returns value is ``'application/octet-stream'`` if no\n         Content-Type header present in HTTP headers according to\n         :rfc:`2616`\n\n   .. attribute:: charset\n\n      Read-only property that specifies the *encoding* for the request's BODY.\n\n      The value is parsed from the *Content-Type* HTTP header.\n\n      Returns :class:`str` like ``'utf-8'`` or ``None`` if\n      *Content-Type* has no charset information.\n\n   .. attribute:: content_length\n\n      Read-only property that returns length of the request's BODY.\n\n      The value is parsed from the *Content-Length* HTTP header.\n\n      Returns :class:`int` or ``None`` if *Content-Length* is absent.\n\n   .. attribute:: http_range\n\n      Read-only property that returns information about *Range* HTTP header.\n\n      Returns a :class:`slice` where ``.start`` is *left inclusive\n      bound*, ``.stop`` is *right exclusive bound* and ``.step`` is\n      ``1``.\n\n      The property might be used in two manners:\n\n      1. Attribute-access style (example assumes that both left and\n         right borders are set, the real logic for case of open bounds\n         is more complex)::\n\n            rng = request.http_range\n            with open(filename, 'rb') as f:\n                f.seek(rng.start)\n                return f.read(rng.stop-rng.start)\n\n      2. Slice-style::\n\n            return buffer[request.http_range]\n\n   .. attribute:: if_modified_since\n\n      Read-only property that returns the date specified in the\n      *If-Modified-Since* header.\n\n      Returns :class:`datetime.datetime` or ``None`` if\n      *If-Modified-Since* header is absent or is not a valid\n      HTTP date.\n\n   .. attribute:: if_unmodified_since\n\n      Read-only property that returns the date specified in the\n      *If-Unmodified-Since* header.\n\n      Returns :class:`datetime.datetime` or ``None`` if\n      *If-Unmodified-Since* header is absent or is not a valid\n      HTTP date.\n\n      .. versionadded:: 3.1\n\n   .. attribute:: if_match\n\n      Read-only property that returns :class:`~aiohttp.ETag` objects specified\n      in the *If-Match* header.\n\n      Returns :class:`tuple` of :class:`~aiohttp.ETag` or ``None`` if\n      *If-Match* header is absent.\n\n      .. versionadded:: 3.8\n\n   .. attribute:: if_none_match\n\n      Read-only property that returns :class:`~aiohttp.ETag` objects specified\n      *If-None-Match* header.\n\n      Returns :class:`tuple` of :class:`~aiohttp.ETag` or ``None`` if\n      *If-None-Match* header is absent.\n\n      .. versionadded:: 3.8\n\n   .. attribute:: if_range\n\n      Read-only property that returns the date specified in the\n      *If-Range* header.\n\n      Returns :class:`datetime.datetime` or ``None`` if\n      *If-Range* header is absent or is not a valid\n      HTTP date.\n\n      .. versionadded:: 3.1\n\n   .. method:: clone(*, method=..., rel_url=..., headers=...)\n\n      Clone itself with replacement some attributes.\n\n      Creates and returns a new instance of Request object. If no parameters\n      are given, an exact copy is returned. If a parameter is not passed, it\n      will reuse the one from the current request object.\n\n      :param str method: http method\n\n      :param rel_url: url to use, :class:`str` or :class:`~yarl.URL`\n\n      :param headers: :class:`~multidict.CIMultiDict` or compatible\n                      headers container.\n\n      :return: a cloned :class:`Request` instance.\n\n   .. method:: get_extra_info(name, default=None)\n\n      Reads extra information from the protocol's transport.\n      If no value associated with ``name`` is found, ``default`` is returned.\n\n      See :meth:`asyncio.BaseTransport.get_extra_info`\n\n      :param str name: The key to look up in the transport extra information.\n\n      :param default: Default value to be used when no value for ``name`` is\n                      found (default is ``None``).\n\n      .. versionadded:: 3.7\n\n   .. method:: read()\n      :async:\n\n      Read request body, returns :class:`bytes` object with body content.\n\n      .. note::\n\n         The method **does** store read data internally, subsequent\n         :meth:`~aiohttp.web.BaseRequest.read` call will return the same value.\n\n   .. method:: text()\n      :async:\n\n      Read request body, decode it using :attr:`charset` encoding or\n      ``UTF-8`` if no encoding was specified in *MIME-type*.\n\n      Returns :class:`str` with body content.\n\n      .. note::\n\n         The method **does** store read data internally, subsequent\n         :meth:`~aiohttp.web.BaseRequest.text` call will return the same value.\n\n   .. method:: json(*, loads=json.loads, \\\n                    content_type='application/json')\n      :async:\n\n      Read request body decoded as *json*. If request's content-type does not\n      match `content_type` parameter, :exc:`aiohttp.web.HTTPBadRequest` get raised.\n      To disable content type check pass ``None`` value.\n\n      :param collections.abc.Callable loads: any :term:`callable` that accepts\n                              :class:`str` and returns :class:`dict`\n                              with parsed JSON (:func:`json.loads` by\n                              default).\n      :param str content_type: expected value of Content-Type header or ``None``\n                              ('application/json' by default)\n\n      .. note::\n\n         The method **does** store read data internally, subsequent\n         :meth:`~aiohttp.web.BaseRequest.json` call will return the same value.\n\n\n   .. method:: multipart()\n      :async:\n\n      Returns :class:`aiohttp.MultipartReader` which processes\n      incoming *multipart* request.\n\n      The method is just a boilerplate :ref:`coroutine <coroutine>`\n      implemented as::\n\n         async def multipart(self, *, reader=aiohttp.multipart.MultipartReader):\n             return reader(self.headers, self._payload)\n\n      This method is a coroutine for consistency with the else reader methods.\n\n      .. warning::\n\n         The method **does not** store read data internally. That means once\n         you exhausts multipart reader, you cannot get the request payload one\n         more time.\n\n      .. seealso:: :ref:`aiohttp-multipart`\n\n      .. versionchanged:: 3.4\n\n         Dropped *reader* parameter.\n\n   .. method:: post()\n      :async:\n\n      A :ref:`coroutine <coroutine>` that reads POST parameters from\n      request body.\n\n      Returns :class:`~multidict.MultiDictProxy` instance filled\n      with parsed data.\n\n      If :attr:`method` is not *POST*, *PUT*, *PATCH*, *TRACE* or *DELETE* or\n      :attr:`content_type` is not empty or\n      *application/x-www-form-urlencoded* or *multipart/form-data*\n      returns empty multidict.\n\n      .. note::\n\n         The method **does** store read data internally, subsequent\n         :meth:`~aiohttp.web.BaseRequest.post` call will return the same value.\n\n   .. method:: release()\n      :async:\n\n      Release request.\n\n      Eat unread part of HTTP BODY if present.\n\n      .. note::\n\n          User code may never call :meth:`~aiohttp.web.BaseRequest.release`, all\n          required work will be processed by :mod:`aiohttp.web`\n          internal machinery.\n\n.. class:: Request\n\n   A request used for receiving request's information by *web handler*.\n\n   Every :ref:`handler<aiohttp-web-handler>` accepts a request\n   instance as the first positional parameter.\n\n   The class in derived from :class:`BaseRequest`, shares all parent's\n   attributes and methods but has a couple of additional properties:\n\n   .. attribute:: match_info\n\n      Read-only property with :class:`~aiohttp.abc.AbstractMatchInfo`\n      instance for result of route resolving.\n\n      .. note::\n\n         Exact type of property depends on used router.  If\n         ``app.router`` is :class:`UrlDispatcher` the property contains\n         :class:`UrlMappingMatchInfo` instance.\n\n   .. attribute:: app\n\n      An :class:`Application` instance used to call :ref:`request handler\n      <aiohttp-web-handler>`, Read-only property.\n\n   .. attribute:: config_dict\n\n      A :class:`aiohttp.ChainMapProxy` instance for mapping all properties\n      from the current application returned by :attr:`app` property\n      and all its parents.\n\n      .. seealso:: :ref:`aiohttp-web-data-sharing-app-config`\n\n      .. versionadded:: 3.2\n\n   .. note::\n\n      You should never create the :class:`Request` instance manually\n      -- :mod:`aiohttp.web` does it for you. But\n      :meth:`~BaseRequest.clone` may be used for cloning *modified*\n      request copy with changed *path*, *method* etc.\n\n\n\n\n.. _aiohttp-web-response:\n\n\nResponse classes\n----------------\n\nFor now, :mod:`aiohttp.web` has three classes for the *HTTP response*:\n:class:`StreamResponse`, :class:`Response` and :class:`FileResponse`.\n\nUsually you need to use the second one. :class:`StreamResponse` is\nintended for streaming data, while :class:`Response` contains *HTTP\nBODY* as an attribute and sends own content as single piece with the\ncorrect *Content-Length HTTP header*.\n\nFor sake of design decisions :class:`Response` is derived from\n:class:`StreamResponse` parent class.\n\nThe response supports *keep-alive* handling out-of-the-box if\n*request* supports it.\n\nYou can disable *keep-alive* by :meth:`~StreamResponse.force_close` though.\n\nThe common case for sending an answer from\n:ref:`web-handler<aiohttp-web-handler>` is returning a\n:class:`Response` instance::\n\n   async def handler(request):\n       return Response(text=\"All right!\")\n\nResponse classes are :obj:`dict` like objects,\nallowing them to be used for :ref:`sharing\ndata<aiohttp-web-data-sharing>` among :ref:`aiohttp-web-middlewares`\nand :ref:`aiohttp-web-signals` handlers::\n\n   resp['key'] = value\n\n.. versionadded:: 3.0\n\n   Dict-like interface support.\n\n\n.. class:: StreamResponse(*, status=200, reason=None)\n\n   The base class for the *HTTP response* handling.\n\n   Contains methods for setting *HTTP response headers*, *cookies*,\n   *response status code*, writing *HTTP response BODY* and so on.\n\n   The most important thing you should know about *response* --- it\n   is *Finite State Machine*.\n\n   That means you can do any manipulations with *headers*, *cookies*\n   and *status code* only before :meth:`prepare` coroutine is called.\n\n   Once you call :meth:`prepare` any change of\n   the *HTTP header* part will raise :exc:`RuntimeError` exception.\n\n   Any :meth:`write` call after :meth:`write_eof` is also forbidden.\n\n   :param int status: HTTP status code, ``200`` by default.\n\n   :param str reason: HTTP reason. If param is ``None`` reason will be\n                      calculated basing on *status*\n                      parameter. Otherwise pass :class:`str` with\n                      arbitrary *status* explanation..\n\n   .. attribute:: prepared\n\n      Read-only :class:`bool` property, ``True`` if :meth:`prepare` has\n      been called, ``False`` otherwise.\n\n   .. attribute:: task\n\n      A task that serves HTTP request handling.\n\n      May be useful for graceful shutdown of long-running requests\n      (streaming, long polling or web-socket).\n\n   .. attribute:: status\n\n      Read-only property for *HTTP response status code*, :class:`int`.\n\n      ``200`` (OK) by default.\n\n   .. attribute:: reason\n\n      Read-only property for *HTTP response reason*, :class:`str`.\n\n   .. method:: set_status(status, reason=None)\n\n      Set :attr:`status` and :attr:`reason`.\n\n      *reason* value is auto calculated if not specified (``None``).\n\n   .. attribute:: keep_alive\n\n      Read-only property, copy of :attr:`aiohttp.web.BaseRequest.keep_alive` by default.\n\n      Can be switched to ``False`` by :meth:`force_close` call.\n\n   .. method:: force_close\n\n      Disable :attr:`keep_alive` for connection. There are no ways to\n      enable it back.\n\n   .. attribute:: compression\n\n      Read-only :class:`bool` property, ``True`` if compression is enabled.\n\n      ``False`` by default.\n\n      .. seealso:: :meth:`enable_compression`\n\n   .. method:: enable_compression(force=None, strategy=zlib.Z_DEFAULT_STRATEGY)\n\n      Enable compression.\n\n      When *force* is unset compression encoding is selected based on\n      the request's *Accept-Encoding* header.\n\n      *Accept-Encoding* is not checked if *force* is set to a\n      :class:`ContentCoding`.\n\n      *strategy* accepts a :mod:`zlib` compression strategy.\n      See :func:`zlib.compressobj` for possible values.\n\n      .. seealso:: :attr:`compression`\n\n   .. attribute:: chunked\n\n      Read-only property, indicates if chunked encoding is on.\n\n      Can be enabled by :meth:`enable_chunked_encoding` call.\n\n      .. seealso:: :attr:`enable_chunked_encoding`\n\n   .. method:: enable_chunked_encoding()\n\n      Enables :attr:`chunked` encoding for response. There are no ways to\n      disable it back. With enabled :attr:`chunked` encoding each :meth:`write`\n      operation encoded in separate chunk.\n\n      .. warning:: chunked encoding can be enabled for ``HTTP/1.1`` only.\n\n                   Setting up both :attr:`content_length` and chunked\n                   encoding is mutually exclusive.\n\n      .. seealso:: :attr:`chunked`\n\n   .. attribute:: headers\n\n      :class:`~multidict.CIMultiDict` instance\n      for *outgoing* *HTTP headers*.\n\n   .. attribute:: cookies\n\n      An instance of :class:`http.cookies.SimpleCookie` for *outgoing* cookies.\n\n      .. warning::\n\n         Direct setting up *Set-Cookie* header may be overwritten by\n         explicit calls to cookie manipulation.\n\n         We are encourage using of :attr:`cookies` and\n         :meth:`set_cookie`, :meth:`del_cookie` for cookie\n         manipulations.\n\n   .. method:: set_cookie(name, value, *, path='/', expires=None, \\\n                          domain=None, max_age=None, \\\n                          secure=None, httponly=None, samesite=None)\n\n      Convenient way for setting :attr:`cookies`, allows to specify\n      some additional properties like *max_age* in a single call.\n\n      :param str name: cookie name\n\n      :param str value: cookie value (will be converted to\n                        :class:`str` if value has another type).\n\n      :param expires: expiration date (optional)\n\n      :param str domain: cookie domain (optional)\n\n      :param int max_age: defines the lifetime of the cookie, in\n                          seconds.  The delta-seconds value is a\n                          decimal non- negative integer.  After\n                          delta-seconds seconds elapse, the client\n                          should discard the cookie.  A value of zero\n                          means the cookie should be discarded\n                          immediately.  (optional)\n\n      :param str path: specifies the subset of URLs to\n                       which this cookie applies. (optional, ``'/'`` by default)\n\n      :param bool secure: attribute (with no value) directs\n                          the user agent to use only (unspecified)\n                          secure means to contact the origin server\n                          whenever it sends back this cookie.\n                          The user agent (possibly under the user's\n                          control) may determine what level of\n                          security it considers appropriate for\n                          \"secure\" cookies.  The *secure* should be\n                          considered security advice from the server\n                          to the user agent, indicating that it is in\n                          the session's interest to protect the cookie\n                          contents. (optional)\n\n      :param bool httponly: ``True`` if the cookie HTTP only (optional)\n\n      :param str samesite: Asserts that a cookie must not be sent with\n         cross-origin requests, providing some protection\n         against cross-site request forgery attacks.\n         Generally the value should be one of: ``None``,\n         ``Lax`` or ``Strict``. (optional)\n\n            .. versionadded:: 3.7\n\n   .. method:: del_cookie(name, *, path='/', domain=None)\n\n      Deletes cookie.\n\n      :param str name: cookie name\n\n      :param str domain: optional cookie domain\n\n      :param str path: optional cookie path, ``'/'`` by default\n\n   .. attribute:: content_length\n\n      *Content-Length* for outgoing response.\n\n   .. attribute:: content_type\n\n      *Content* part of *Content-Type* for outgoing response.\n\n   .. attribute:: charset\n\n      *Charset* aka *encoding* part of *Content-Type* for outgoing response.\n\n      The value converted to lower-case on attribute assigning.\n\n   .. attribute:: last_modified\n\n      *Last-Modified* header for outgoing response.\n\n      This property accepts raw :class:`str` values,\n      :class:`datetime.datetime` objects, Unix timestamps specified\n      as an :class:`int` or a :class:`float` object, and the\n      value ``None`` to unset the header.\n\n   .. attribute:: etag\n\n      *ETag* header for outgoing response.\n\n      This property accepts raw :class:`str` values, :class:`~aiohttp.ETag`\n      objects and the value ``None`` to unset the header.\n\n      In case of :class:`str` input, etag is considered as strong by default.\n\n      **Do not** use double quotes ``\"`` in the etag value,\n      they will be added automatically.\n\n      .. versionadded:: 3.8\n\n   .. method:: prepare(request)\n      :async:\n\n      :param aiohttp.web.Request request: HTTP request object, that the\n                                          response answers.\n\n      Send *HTTP header*. You should not change any header data after\n      calling this method.\n\n      The coroutine calls :attr:`~aiohttp.web.Application.on_response_prepare`\n      signal handlers after default headers have been computed and directly\n      before headers are sent.\n\n   .. method:: write(data)\n      :async:\n\n      Send byte-ish data as the part of *response BODY*::\n\n          await resp.write(data)\n\n      :meth:`prepare` must be invoked before the call.\n\n      Raises :exc:`TypeError` if data is not :class:`bytes`,\n      :class:`bytearray` or :class:`memoryview` instance.\n\n      Raises :exc:`RuntimeError` if :meth:`prepare` has not been called.\n\n      Raises :exc:`RuntimeError` if :meth:`write_eof` has been called.\n\n   .. method:: write_eof()\n      :async:\n\n      A :ref:`coroutine<coroutine>` *may* be called as a mark of the\n      *HTTP response* processing finish.\n\n      *Internal machinery* will call this method at the end of\n      the request processing if needed.\n\n      After :meth:`write_eof` call any manipulations with the *response*\n      object are forbidden.\n\n\n.. class:: Response(*, body=None, status=200, reason=None, text=None, \\\n                    headers=None, content_type=None, charset=None, \\\n                    zlib_executor_size=sentinel, zlib_executor=None)\n\n   The most usable response class, inherited from :class:`StreamResponse`.\n\n   Accepts *body* argument for setting the *HTTP response BODY*.\n\n   The actual :attr:`body` sending happens in overridden\n   :meth:`~StreamResponse.write_eof`.\n\n   :param bytes body: response's BODY\n\n   :param int status: HTTP status code, 200 OK by default.\n\n   :param collections.abc.Mapping headers: HTTP headers that should be added to\n                           response's ones.\n\n   :param str text: response's BODY\n\n   :param str content_type: response's content type. ``'text/plain'``\n                       if *text* is passed also,\n                       ``'application/octet-stream'`` otherwise.\n\n   :param str charset: response's charset. ``'utf-8'`` if *text* is\n                       passed also, ``None`` otherwise.\n\n   :param int zlib_executor_size: length in bytes which will trigger zlib compression\n                            of body to happen in an executor\n\n      .. versionadded:: 3.5\n\n   :param int zlib_executor: executor to use for zlib compression\n\n      .. versionadded:: 3.5\n\n\n   .. attribute:: body\n\n      Read-write attribute for storing response's content aka BODY,\n      :class:`bytes`.\n\n      Assigning :class:`str` to :attr:`body` will make the :attr:`body`\n      type of :class:`aiohttp.payload.StringPayload`, which tries to encode\n      the given data based on *Content-Type* HTTP header, while defaulting\n      to ``UTF-8``.\n\n   .. attribute:: text\n\n      Read-write attribute for storing response's\n      :attr:`~aiohttp.StreamResponse.body`, represented as :class:`str`.\n\n\n.. class:: FileResponse(*, path, chunk_size=256*1024, status=200, reason=None, headers=None)\n\n   The response class used to send files, inherited from :class:`StreamResponse`.\n\n   Supports the ``Content-Range`` and ``If-Range`` HTTP Headers in requests.\n\n   The actual :attr:`body` sending happens in overridden :meth:`~StreamResponse.prepare`.\n\n   :param path: Path to file. Accepts both :class:`str` and :class:`pathlib.Path`.\n   :param int chunk_size: Chunk size in bytes which will be passed into\n                          :meth:`io.RawIOBase.read` in the event that the\n                          ``sendfile`` system call is not supported.\n\n   :param int status: HTTP status code, ``200`` by default.\n\n   :param str reason: HTTP reason. If param is ``None`` reason will be\n                      calculated basing on *status*\n                      parameter. Otherwise pass :class:`str` with\n                      arbitrary *status* explanation..\n\n   :param collections.abc.Mapping headers: HTTP headers that should be added to\n                           response's ones. The ``Content-Type`` response header\n                           will be overridden if provided.\n\n\n.. class:: WebSocketResponse(*, timeout=10.0, receive_timeout=None, \\\n                             autoclose=True, autoping=True, heartbeat=None, \\\n                             protocols=(), compress=True, max_msg_size=4194304)\n\n   Class for handling server-side websockets, inherited from\n   :class:`StreamResponse`.\n\n   After starting (by :meth:`prepare` call) the response you\n   cannot use :meth:`~StreamResponse.write` method but should to\n   communicate with websocket client by :meth:`send_str`,\n   :meth:`receive` and others.\n\n   To enable back-pressure from slow websocket clients treat methods\n   :meth:`ping`, :meth:`pong`, :meth:`send_str`,\n   :meth:`send_bytes`, :meth:`send_json`, :meth:`send_frame` as coroutines.\n   By default write buffer size is set to 64k.\n\n   :param bool autoping: Automatically send\n                         :const:`~aiohttp.WSMsgType.PONG` on\n                         :const:`~aiohttp.WSMsgType.PING`\n                         message from client, and handle\n                         :const:`~aiohttp.WSMsgType.PONG`\n                         responses from client.\n                         Note that server does not send\n                         :const:`~aiohttp.WSMsgType.PING`\n                         requests, you need to do this explicitly\n                         using :meth:`ping` method.\n\n   :param float heartbeat: Send `ping` message every `heartbeat`\n                           seconds and wait `pong` response, close\n                           connection if `pong` response is not\n                           received. The timer is reset on any data reception.\n\n   :param float receive_timeout: Timeout value for `receive`\n                                 operations.  Default value is None\n                                 (no timeout for receive operation)\n\n   :param bool compress: Enable per-message deflate extension support.\n                          False for disabled, default value is True.\n\n   :param int max_msg_size: maximum size of read websocket message, 4\n                            MB by default. To disable the size limit use ``0``.\n\n      .. versionadded:: 3.3\n\n   :param bool autoclose: Close connection when the client sends\n                           a :const:`~aiohttp.WSMsgType.CLOSE` message,\n                           ``True`` by default. If set to ``False``,\n                           the connection is not closed and the\n                           caller is responsible for calling\n                           ``request.transport.close()`` to avoid\n                           leaking resources.\n\n\n   The class supports ``async for`` statement for iterating over\n   incoming messages::\n\n      ws = web.WebSocketResponse()\n      await ws.prepare(request)\n\n          async for msg in ws:\n              print(msg.data)\n\n\n   .. method:: prepare(request)\n      :async:\n\n      Starts websocket. After the call you can use websocket methods.\n\n      :param aiohttp.web.Request request: HTTP request object, that the\n                                          response answers.\n\n\n      :raises HTTPException: if websocket handshake has failed.\n\n   .. method:: can_prepare(request)\n\n      Performs checks for *request* data to figure out if websocket\n      can be started on the request.\n\n      If :meth:`can_prepare` call is success then :meth:`prepare` will\n      success too.\n\n      :param aiohttp.web.Request request: HTTP request object, that the\n                                          response answers.\n\n      :return: :class:`WebSocketReady` instance.\n\n               :attr:`WebSocketReady.ok` is\n               ``True`` on success, :attr:`WebSocketReady.protocol` is\n               websocket subprotocol which is passed by client and\n               accepted by server (one of *protocols* sequence from\n               :class:`WebSocketResponse` ctor).\n               :attr:`WebSocketReady.protocol` may be ``None`` if\n               client and server subprotocols are not overlapping.\n\n      .. note:: The method never raises exception.\n\n   .. attribute:: closed\n\n      Read-only property, ``True`` if connection has been closed or in process\n      of closing.\n      :const:`~aiohttp.WSMsgType.CLOSE` message has been received from peer.\n\n   .. attribute:: close_code\n\n      Read-only property, close code from peer. It is set to ``None`` on\n      opened connection.\n\n   .. attribute:: ws_protocol\n\n      Websocket *subprotocol* chosen after :meth:`start` call.\n\n      May be ``None`` if server and client protocols are\n      not overlapping.\n\n   .. method:: get_extra_info(name, default=None)\n\n      Reads optional extra information from the writer's transport.\n      If no value associated with ``name`` is found, ``default`` is returned.\n\n      See :meth:`asyncio.BaseTransport.get_extra_info`\n\n      :param str name: The key to look up in the transport extra information.\n\n      :param default: Default value to be used when no value for ``name`` is\n                      found (default is ``None``).\n\n   .. method:: exception()\n\n      Returns last occurred exception or None.\n\n   .. method:: ping(message=b'')\n      :async:\n\n      Send :const:`~aiohttp.WSMsgType.PING` to peer.\n\n      :param message: optional payload of *ping* message,\n                      :class:`str` (converted to *UTF-8* encoded bytes)\n                      or :class:`bytes`.\n\n      :raise RuntimeError: if connections is not started or closing.\n\n      .. versionchanged:: 3.0\n\n         The method is converted into :term:`coroutine`\n\n   .. method:: pong(message=b'')\n      :async:\n\n      Send *unsolicited* :const:`~aiohttp.WSMsgType.PONG` to peer.\n\n      :param message: optional payload of *pong* message,\n                      :class:`str` (converted to *UTF-8* encoded bytes)\n                      or :class:`bytes`.\n\n      :raise RuntimeError: if connections is not started or closing.\n\n      .. versionchanged:: 3.0\n\n         The method is converted into :term:`coroutine`\n\n   .. method:: send_str(data, compress=None)\n      :async:\n\n      Send *data* to peer as :const:`~aiohttp.WSMsgType.TEXT` message.\n\n      :param str data: data to send.\n\n      :param int compress: sets specific level of compression for\n                           single message,\n                           ``None`` for not overriding per-socket setting.\n\n      :raise RuntimeError: if connection is not started or closing\n\n      :raise TypeError: if data is not :class:`str`\n\n      .. versionchanged:: 3.0\n\n         The method is converted into :term:`coroutine`,\n         *compress* parameter added.\n\n   .. method:: send_bytes(data, compress=None)\n      :async:\n\n      Send *data* to peer as :const:`~aiohttp.WSMsgType.BINARY` message.\n\n      :param data: data to send.\n\n      :param int compress: sets specific level of compression for\n                           single message,\n                           ``None`` for not overriding per-socket setting.\n\n      :raise RuntimeError: if connection is not started or closing\n\n      :raise TypeError: if data is not :class:`bytes`,\n                        :class:`bytearray` or :class:`memoryview`.\n\n      .. versionchanged:: 3.0\n\n         The method is converted into :term:`coroutine`,\n         *compress* parameter added.\n\n   .. method:: send_json(data, compress=None, *, dumps=json.dumps)\n      :async:\n\n      Send *data* to peer as JSON string.\n\n      :param data: data to send.\n\n      :param int compress: sets specific level of compression for\n                           single message,\n                           ``None`` for not overriding per-socket setting.\n\n      :param collections.abc.Callable dumps: any :term:`callable` that accepts an object and\n                             returns a JSON string\n                             (:func:`json.dumps` by default).\n\n      :raise RuntimeError: if connection is not started or closing\n\n      :raise ValueError: if data is not serializable object\n\n      :raise TypeError: if value returned by ``dumps`` param is not :class:`str`\n\n      .. versionchanged:: 3.0\n\n         The method is converted into :term:`coroutine`,\n         *compress* parameter added.\n\n   .. method:: send_frame(message, opcode, compress=None)\n      :async:\n\n      Send a :const:`~aiohttp.WSMsgType` message *message* to peer.\n\n      This method is low-level and should be used with caution as it\n      only accepts bytes which must conform to the correct message type\n      for *message*.\n\n      It is recommended to use the :meth:`send_str`, :meth:`send_bytes`\n      or :meth:`send_json` methods instead of this method.\n\n      The primary use case for this method is to send bytes that are\n      have already been encoded without having to decode and\n      re-encode them.\n\n      :param bytes message: message to send.\n\n      :param ~aiohttp.WSMsgType opcode: opcode of the message.\n\n      :param int compress: sets specific level of compression for\n                           single message,\n                           ``None`` for not overriding per-socket setting.\n\n      .. versionadded:: 3.11\n\n   .. method:: close(*, code=WSCloseCode.OK, message=b'', drain=True)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that initiates closing\n      handshake by sending :const:`~aiohttp.WSMsgType.CLOSE` message.\n\n      It is safe to call `close()` from different task.\n\n      :param int code: closing code. See also :class:`~aiohttp.WSCloseCode`.\n\n      :param message: optional payload of *close* message,\n                      :class:`str` (converted to *UTF-8* encoded bytes)\n                      or :class:`bytes`.\n\n      :param bool drain: drain outgoing buffer before closing connection.\n\n      :raise RuntimeError: if connection is not started\n\n   .. method:: receive(timeout=None)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that waits upcoming *data*\n      message from peer and returns it.\n\n      The coroutine implicitly handles\n      :const:`~aiohttp.WSMsgType.PING`,\n      :const:`~aiohttp.WSMsgType.PONG` and\n      :const:`~aiohttp.WSMsgType.CLOSE` without returning the\n      message.\n\n      It process *ping-pong game* and performs *closing handshake* internally.\n\n      .. note::\n\n         Can only be called by the request handling task.\n\n      :param timeout: timeout for `receive` operation.\n\n         timeout value overrides response`s receive_timeout attribute.\n\n      :return: :class:`~aiohttp.WSMessage`\n\n      :raise RuntimeError: if connection is not started\n\n   .. method:: receive_str(*, timeout=None)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that calls :meth:`receive` but\n      also asserts the message type is :const:`~aiohttp.WSMsgType.TEXT`.\n\n      .. note::\n\n         Can only be called by the request handling task.\n\n      :param timeout: timeout for `receive` operation.\n\n         timeout value overrides response`s receive_timeout attribute.\n\n      :return str: peer's message content.\n\n      :raise TypeError: if message is :const:`~aiohttp.WSMsgType.BINARY`.\n\n   .. method:: receive_bytes(*, timeout=None)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that calls :meth:`receive` but\n      also asserts the message type is\n      :const:`~aiohttp.WSMsgType.BINARY`.\n\n      .. note::\n\n         Can only be called by the request handling task.\n\n      :param timeout: timeout for `receive` operation.\n\n         timeout value overrides response`s receive_timeout attribute.\n\n      :return bytes: peer's message content.\n\n      :raise TypeError: if message is :const:`~aiohttp.WSMsgType.TEXT`.\n\n   .. method:: receive_json(*, loads=json.loads, timeout=None)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that calls :meth:`receive_str` and loads the\n      JSON string to a Python dict.\n\n      .. note::\n\n         Can only be called by the request handling task.\n\n      :param collections.abc.Callable loads: any :term:`callable` that accepts\n                              :class:`str` and returns :class:`dict`\n                              with parsed JSON (:func:`json.loads` by\n                              default).\n\n      :param timeout: timeout for `receive` operation.\n\n         timeout value overrides response`s receive_timeout attribute.\n\n      :return dict: loaded JSON content\n\n      :raise TypeError: if message is :const:`~aiohttp.WSMsgType.BINARY`.\n      :raise ValueError: if message is not valid JSON.\n\n\n.. seealso:: :ref:`WebSockets handling<aiohttp-web-websockets>`\n\n\n.. class:: WebSocketReady\n\n   A named tuple for returning result from\n   :meth:`WebSocketResponse.can_prepare`.\n\n   Has :class:`bool` check implemented, e.g.::\n\n       if not await ws.can_prepare(...):\n           cannot_start_websocket()\n\n   .. attribute:: ok\n\n      ``True`` if websocket connection can be established, ``False``\n      otherwise.\n\n\n   .. attribute:: protocol\n\n      :class:`str` represented selected websocket sub-protocol.\n\n   .. seealso:: :meth:`WebSocketResponse.can_prepare`\n\n\n.. function:: json_response([data], *, text=None, body=None, \\\n                            status=200, reason=None, headers=None, \\\n                            content_type='application/json', \\\n                            dumps=json.dumps)\n\nReturn :class:`Response` with predefined ``'application/json'``\ncontent type and *data* encoded by ``dumps`` parameter\n(:func:`json.dumps` by default).\n\n\n.. _aiohttp-web-app-and-router:\n\nApplication and Router\n----------------------\n\n\n.. class:: Application(*, logger=<default>, middlewares=(), \\\n                       handler_args=None, client_max_size=1024**2, \\\n                       debug=...)\n\n   Application is a synonym for web-server.\n\n   To get a fully working example, you have to make an *application*, register\n   supported urls in the *router* and pass it to :func:`aiohttp.web.run_app`\n   or :class:`aiohttp.web.AppRunner`.\n\n   *Application* contains a *router* instance and a list of callbacks that\n   will be called during application finishing.\n\n   This class is a :obj:`dict`-like object, so you can use it for\n   :ref:`sharing data<aiohttp-web-data-sharing>` globally by storing arbitrary\n   properties for later access from a :ref:`handler<aiohttp-web-handler>` via the\n   :attr:`Request.app` property::\n\n       app = Application()\n       database = AppKey(\"database\", AsyncEngine)\n       app[database] = await create_async_engine(db_url)\n\n       async def handler(request):\n           async with request.app[database].begin() as conn:\n               await conn.execute(\"DELETE * FROM table\")\n\n   Although it` is a :obj:`dict`-like object, it can't be duplicated like one\n   using :meth:`~aiohttp.web.Application.copy`.\n\n   The class inherits :class:`dict`.\n\n   :param logger: :class:`logging.Logger` instance for storing application logs.\n\n                  By default the value is ``logging.getLogger(\"aiohttp.web\")``\n\n   :param middlewares: :class:`list` of middleware factories, see\n                       :ref:`aiohttp-web-middlewares` for details.\n\n   :param handler_args: dict-like object that overrides keyword arguments of\n                        :class:`AppRunner` constructor.\n\n   :param client_max_size: client's maximum size in a request, in\n                           bytes.  If a POST request exceeds this\n                           value, it raises an\n                           `HTTPRequestEntityTooLarge` exception.\n\n   :param debug: Switches debug mode.\n\n      .. deprecated:: 3.5\n\n         The argument does nothing starting from 4.0,\n         use asyncio :ref:`asyncio-debug-mode` instead.\n\n\n   .. attribute:: router\n\n      Read-only property that returns *router instance*.\n\n   .. attribute:: logger\n\n      :class:`logging.Logger` instance for storing application logs.\n\n   .. attribute:: debug\n\n      Boolean value indicating whether the debug mode is turned on or off.\n\n      .. deprecated:: 3.5\n\n         Use asyncio :ref:`asyncio-debug-mode` instead.\n\n   .. attribute:: on_response_prepare\n\n      A :class:`~aiosignal.Signal` that is fired near the end\n      of :meth:`StreamResponse.prepare` with parameters *request* and\n      *response*. It can be used, for example, to add custom headers to each\n      response, or to modify the default headers computed by the application,\n      directly before sending the headers to the client.\n\n      Signal handlers should have the following signature::\n\n          async def on_prepare(request, response):\n              pass\n\n      .. note::\n\n         The headers are written immediately after these callbacks are run.\n         Therefore, if you modify the content of the response, you may need to\n         adjust the `Content-Length` header or similar to match. Aiohttp will\n         not make any updates to the headers from this point.\n\n   .. attribute:: on_startup\n\n      A :class:`~aiosignal.Signal` that is fired on application start-up.\n\n      Subscribers may use the signal to run background tasks in the event\n      loop along with the application's request handler just after the\n      application start-up.\n\n      Signal handlers should have the following signature::\n\n          async def on_startup(app):\n              pass\n\n      .. seealso:: :ref:`aiohttp-web-signals` and :ref:`aiohttp-web-cleanup-ctx`.\n\n   .. attribute:: on_shutdown\n\n      A :class:`~aiosignal.Signal` that is fired on application shutdown.\n\n      Subscribers may use the signal for gracefully closing long running\n      connections, e.g. websockets and data streaming.\n\n      Signal handlers should have the following signature::\n\n          async def on_shutdown(app):\n              pass\n\n      It's up to end user to figure out which :term:`web-handler`\\s\n      are still alive and how to finish them properly.\n\n      We suggest keeping a list of long running handlers in\n      :class:`Application` dictionary.\n\n      .. seealso:: :ref:`aiohttp-web-graceful-shutdown` and :attr:`on_cleanup`.\n\n   .. attribute:: on_cleanup\n\n      A :class:`~aiosignal.Signal` that is fired on application cleanup.\n\n      Subscribers may use the signal for gracefully closing\n      connections to database server etc.\n\n      Signal handlers should have the following signature::\n\n          async def on_cleanup(app):\n              pass\n\n      .. seealso:: :ref:`aiohttp-web-signals` and :attr:`on_shutdown`.\n\n   .. attribute:: cleanup_ctx\n\n      A list of *context generators* for *startup*/*cleanup* handling.\n\n      Signal handlers should have the following signature::\n\n          async def context(app):\n              # do startup stuff\n              yield\n              # do cleanup\n\n      .. versionadded:: 3.1\n\n      .. seealso:: :ref:`aiohttp-web-cleanup-ctx`.\n\n   .. method:: add_subapp(prefix, subapp)\n\n      Register nested sub-application under given path *prefix*.\n\n      In resolving process if request's path starts with *prefix* then\n      further resolving is passed to *subapp*.\n\n      :param str prefix: path's prefix for the resource.\n\n      :param Application subapp: nested application attached under *prefix*.\n\n      :returns: a :class:`PrefixedSubAppResource` instance.\n\n   .. method:: add_domain(domain, subapp)\n\n      Register nested sub-application that serves\n      the domain name or domain name mask.\n\n      In resolving process if request.headers['host']\n      matches the pattern *domain* then\n      further resolving is passed to *subapp*.\n\n      :param str domain: domain or mask of domain for the resource.\n\n      :param Application subapp: nested application.\n\n      :returns: a :class:`~aiohttp.web.MatchedSubAppResource` instance.\n\n   .. method:: add_routes(routes_table)\n\n      Register route definitions from *routes_table*.\n\n      The table is a :class:`list` of :class:`RouteDef` items or\n      :class:`RouteTableDef`.\n\n      :returns: :class:`list` of registered :class:`AbstractRoute` instances.\n\n      The method is a shortcut for\n      ``app.router.add_routes(routes_table)``, see also\n      :meth:`UrlDispatcher.add_routes`.\n\n      .. versionadded:: 3.1\n\n      .. versionchanged:: 3.7\n\n         Return value updated from ``None`` to :class:`list` of\n         :class:`AbstractRoute` instances.\n\n   .. method:: startup()\n      :async:\n\n      A :ref:`coroutine<coroutine>` that will be called along with the\n      application's request handler.\n\n      The purpose of the method is calling :attr:`on_startup` signal\n      handlers.\n\n   .. method:: shutdown()\n      :async:\n\n      A :ref:`coroutine<coroutine>` that should be called on\n      server stopping but before :meth:`cleanup`.\n\n      The purpose of the method is calling :attr:`on_shutdown` signal\n      handlers.\n\n   .. method:: cleanup()\n      :async:\n\n      A :ref:`coroutine<coroutine>` that should be called on\n      server stopping but after :meth:`shutdown`.\n\n      The purpose of the method is calling :attr:`on_cleanup` signal\n      handlers.\n\n   .. note::\n\n      Application object has :attr:`router` attribute but has no\n      ``add_route()`` method. The reason is: we want to support\n      different router implementations (even maybe not url-matching\n      based but traversal ones).\n\n      For sake of that fact we have very trivial ABC for\n      :class:`~aiohttp.abc.AbstractRouter`: it should have only\n      :meth:`aiohttp.abc.AbstractRouter.resolve` coroutine.\n\n      No methods for adding routes or route reversing (getting URL by\n      route name). All those are router implementation details (but,\n      sure, you need to deal with that methods after choosing the\n      router for your application).\n\n\n.. class:: AppKey(name, t)\n\n   This class should be used for the keys in :class:`Application`. They\n   provide a type-safe alternative to `str` keys when checking your code\n   with a type checker (e.g. mypy). They also avoid name clashes with keys\n   from different libraries etc.\n\n   :param name: A name to help with debugging. This should be the same as\n                the variable name (much like how :class:`typing.TypeVar`\n                is used).\n\n   :param t: The type that should be used for the value in the dict (e.g.\n             `str`, `Iterator[int]` etc.)\n\n.. class:: Server\n\n   A protocol factory compatible with\n   :meth:`~asyncio.AbstractEventLoop.create_server`.\n\n   The class is responsible for creating HTTP protocol\n   objects that can handle HTTP connections.\n\n   .. attribute:: connections\n\n      List of all currently opened connections.\n\n   .. attribute:: requests_count\n\n      Amount of processed requests.\n\n   .. method:: Server.shutdown(timeout)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that should be called to close all opened\n      connections.\n\n\n.. class:: UrlDispatcher()\n\n   For dispatching URLs to :ref:`handlers<aiohttp-web-handler>`\n   :mod:`aiohttp.web` uses *routers*, which is any object that implements\n   :class:`~aiohttp.abc.AbstractRouter` interface.\n\n   This class is a straightforward url-matching router, implementing\n   :class:`collections.abc.Mapping` for access to *named routes*.\n\n   :class:`Application` uses this class as\n   :meth:`~aiohttp.web.Application.router` by default.\n\n   Before running an :class:`Application` you should fill *route\n   table* first by calling :meth:`add_route` and :meth:`add_static`.\n\n   :ref:`Handler<aiohttp-web-handler>` lookup is performed by iterating on\n   added *routes* in FIFO order. The first matching *route* will be used\n   to call the corresponding *handler*.\n\n   If during route creation you specify *name* parameter the result is a\n   *named route*.\n\n   A *named route* can be retrieved by a ``app.router[name]`` call, checking for\n   existence can be done with ``name in app.router`` etc.\n\n   .. seealso:: :ref:`Route classes <aiohttp-web-route>`\n\n   .. method:: add_resource(path, *, name=None)\n\n      Append a :term:`resource` to the end of route table.\n\n      *path* may be either *constant* string like ``'/a/b/c'`` or\n      *variable rule* like ``'/a/{var}'`` (see\n      :ref:`handling variable paths <aiohttp-web-variable-handler>`)\n\n      :param str path: resource path spec.\n\n      :param str name: optional resource name.\n\n      :return: created resource instance (:class:`PlainResource` or\n               :class:`DynamicResource`).\n\n   .. method:: add_route(method, path, handler, *, \\\n                         name=None, expect_handler=None)\n\n      Append :ref:`handler<aiohttp-web-handler>` to the end of route table.\n\n      *path* may be either *constant* string like ``'/a/b/c'`` or\n       *variable rule* like ``'/a/{var}'`` (see\n       :ref:`handling variable paths <aiohttp-web-variable-handler>`)\n\n      Pay attention please: *handler* must be a coroutine.\n\n      :param str method: HTTP method for route. Should be one of\n                         ``'GET'``, ``'POST'``, ``'PUT'``,\n                         ``'DELETE'``, ``'PATCH'``, ``'HEAD'``,\n                         ``'OPTIONS'`` or ``'*'`` for any method.\n\n                         The parameter is case-insensitive, e.g. you\n                         can push ``'get'`` as well as ``'GET'``.\n\n      :param str path: route path. Should be started with slash (``'/'``).\n\n      :param collections.abc.Callable handler: route handler.\n\n      :param str name: optional route name.\n\n      :param collections.abc.Coroutine expect_handler: optional *expect* header handler.\n\n      :returns: new :class:`AbstractRoute` instance.\n\n   .. method:: add_routes(routes_table)\n\n      Register route definitions from *routes_table*.\n\n      The table is a :class:`list` of :class:`RouteDef` items or\n      :class:`RouteTableDef`.\n\n      :returns: :class:`list` of registered :class:`AbstractRoute` instances.\n\n      .. versionadded:: 2.3\n\n      .. versionchanged:: 3.7\n\n         Return value updated from ``None`` to :class:`list` of\n         :class:`AbstractRoute` instances.\n\n   .. method:: add_get(path, handler, *, name=None, allow_head=True, **kwargs)\n\n      Shortcut for adding a GET handler. Calls the :meth:`add_route` with \\\n      ``method`` equals to ``'GET'``.\n\n      If *allow_head* is ``True`` (default) the route for method HEAD\n      is added with the same handler as for GET.\n\n      If *name* is provided the name for HEAD route is suffixed with\n      ``'-head'``. For example ``router.add_get(path, handler,\n      name='route')`` call adds two routes: first for GET with name\n      ``'route'`` and second for HEAD with name ``'route-head'``.\n\n   .. method:: add_post(path, handler, **kwargs)\n\n      Shortcut for adding a POST handler. Calls the :meth:`add_route` with \\\n\n\n      ``method`` equals to ``'POST'``.\n\n   .. method:: add_head(path, handler, **kwargs)\n\n      Shortcut for adding a HEAD handler. Calls the :meth:`add_route` with \\\n      ``method`` equals to ``'HEAD'``.\n\n   .. method:: add_put(path, handler, **kwargs)\n\n      Shortcut for adding a PUT handler. Calls the :meth:`add_route` with \\\n      ``method`` equals to ``'PUT'``.\n\n   .. method:: add_patch(path, handler, **kwargs)\n\n      Shortcut for adding a PATCH handler. Calls the :meth:`add_route` with \\\n      ``method`` equals to ``'PATCH'``.\n\n   .. method:: add_delete(path, handler, **kwargs)\n\n      Shortcut for adding a DELETE handler. Calls the :meth:`add_route` with \\\n      ``method`` equals to ``'DELETE'``.\n\n   .. method:: add_view(path, handler, **kwargs)\n\n      Shortcut for adding a class-based view handler. Calls the \\\n      :meth:`add_route` with ``method`` equals to ``'*'``.\n\n      .. versionadded:: 3.0\n\n   .. method:: add_static(prefix, path, *, name=None, expect_handler=None, \\\n                          chunk_size=256*1024, \\\n                          response_factory=StreamResponse, \\\n                          show_index=False, \\\n                          follow_symlinks=False, \\\n                          append_version=False)\n\n      Adds a router and a handler for returning static files.\n\n      Useful for serving static content like images, javascript and css files.\n\n      On platforms that support it, the handler will transfer files more\n      efficiently using the ``sendfile`` system call.\n\n      In some situations it might be necessary to avoid using the ``sendfile``\n      system call even if the platform supports it. This can be accomplished by\n      by setting environment variable ``AIOHTTP_NOSENDFILE=1``.\n\n      If a Brotli or gzip compressed version of the static content exists at\n      the requested path with the ``.br`` or ``.gz`` extension, it will be used\n      for the response. Brotli will be preferred over gzip if both files exist.\n\n      .. warning::\n\n         Use :meth:`add_static` for development only. In production,\n         static content should be processed by web servers like *nginx*\n         or *apache*. Such web servers will be able to provide significantly\n         better performance and security for static assets. Several past security\n         vulnerabilities in aiohttp only affected applications using\n         :meth:`add_static`.\n\n      :param str prefix: URL path prefix for handled static files\n\n      :param path: path to the folder in file system that contains\n                   handled static files, :class:`str` or :class:`pathlib.Path`.\n\n      :param str name: optional route name.\n\n      :param collections.abc.Coroutine expect_handler: optional *expect* header handler.\n\n      :param int chunk_size: size of single chunk for file\n                             downloading, 256Kb by default.\n\n                             Increasing *chunk_size* parameter to,\n                             say, 1Mb may increase file downloading\n                             speed but consumes more memory.\n\n      :param bool show_index: flag for allowing to show indexes of a directory,\n                              by default it's not allowed and HTTP/403 will\n                              be returned on directory access.\n\n      :param bool follow_symlinks: flag for allowing to follow symlinks that lead\n                              outside the static root directory, by default it's not allowed and\n                              HTTP/404 will be returned on access.  Enabling ``follow_symlinks``\n                              can be a security risk, and may lead to a directory transversal attack.\n                              You do NOT need this option to follow symlinks which point to somewhere\n                              else within the static directory, this option is only used to break out\n                              of the security sandbox. Enabling this option is highly discouraged,\n                              and only expected to be used for edge cases in a local development\n                              setting where remote users do not have access to the server.\n\n      :param bool append_version: flag for adding file version (hash)\n                              to the url query string, this value will\n                              be used as default when you call to\n                              :meth:`~aiohttp.web.AbstractRoute.url` and\n                              :meth:`~aiohttp.web.AbstractRoute.url_for` methods.\n\n\n      :returns: new :class:`~aiohttp.web.AbstractRoute` instance.\n\n   .. method:: resolve(request)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that returns\n      :class:`~aiohttp.abc.AbstractMatchInfo` for *request*.\n\n      The method never raises exception, but returns\n      :class:`~aiohttp.abc.AbstractMatchInfo` instance with:\n\n      1. :attr:`~aiohttp.abc.AbstractMatchInfo.http_exception` assigned to\n         :exc:`HTTPException` instance.\n      2. :meth:`~aiohttp.abc.AbstractMatchInfo.handler` which raises\n         :exc:`HTTPNotFound` or :exc:`HTTPMethodNotAllowed` on handler's\n         execution if there is no registered route for *request*.\n\n         *Middlewares* can process that exceptions to render\n         pretty-looking error page for example.\n\n      Used by internal machinery, end user unlikely need to call the method.\n\n      .. note:: The method uses :attr:`aiohttp.web.BaseRequest.raw_path` for pattern\n         matching against registered routes.\n\n   .. method:: resources()\n\n      The method returns a *view* for *all* registered resources.\n\n      The view is an object that allows to:\n\n      1. Get size of the router table::\n\n           len(app.router.resources())\n\n      2. Iterate over registered resources::\n\n           for resource in app.router.resources():\n               print(resource)\n\n      3. Make a check if the resources is registered in the router table::\n\n           route in app.router.resources()\n\n   .. method:: routes()\n\n      The method returns a *view* for *all* registered routes.\n\n   .. method:: named_resources()\n\n      Returns a :obj:`dict`-like :class:`types.MappingProxyType` *view* over\n      *all* named **resources**.\n\n      The view maps every named resource's **name** to the\n      :class:`AbstractResource` instance. It supports the usual\n      :obj:`dict`-like operations, except for any mutable operations\n      (i.e. it's **read-only**)::\n\n          len(app.router.named_resources())\n\n          for name, resource in app.router.named_resources().items():\n              print(name, resource)\n\n          \"name\" in app.router.named_resources()\n\n          app.router.named_resources()[\"name\"]\n\n\n.. _aiohttp-web-resource:\n\nResource\n^^^^^^^^\n\nDefault router :class:`UrlDispatcher` operates with :term:`resource`\\s.\n\nResource is an item in *routing table* which has a *path*, an optional\nunique *name* and at least one :term:`route`.\n\n:term:`web-handler` lookup is performed in the following way:\n\n1. The router splits the URL and checks the index from longest to shortest.\n   For example, '/one/two/three' will first check the index for\n   '/one/two/three', then '/one/two' and finally '/'.\n2. If the URL part is found in the index, the list of routes for\n   that URL part is iterated over. If a route matches to requested HTTP\n   method (or ``'*'`` wildcard) the route's handler is used as the chosen\n   :term:`web-handler`. The lookup is finished.\n3. If the route is not found in the index, the router tries to find\n   the route in the list of :class:`~aiohttp.web.MatchedSubAppResource`,\n   (current only created from :meth:`~aiohttp.web.Application.add_domain`),\n   and will iterate over the list of\n   :class:`~aiohttp.web.MatchedSubAppResource` in a linear fashion\n   until a match is found.\n4. If no *resource* / *route* pair was found, the *router*\n   returns the special :class:`~aiohttp.abc.AbstractMatchInfo`\n   instance with :attr:`aiohttp.abc.AbstractMatchInfo.http_exception` is not ``None``\n   but :exc:`HTTPException` with  either *HTTP 404 Not Found* or\n   *HTTP 405 Method Not Allowed* status code.\n   Registered :meth:`~aiohttp.abc.AbstractMatchInfo.handler` raises this exception on call.\n\nFixed paths are preferred over variable paths. For example,\nif you have two routes ``/a/b`` and ``/a/{name}``, then the first\nroute will always be preferred over the second one.\n\nIf there are multiple dynamic paths with the same fixed prefix,\nthey will be resolved in order of registration.\n\nFor example, if you have two dynamic routes that are prefixed\nwith the fixed ``/users`` path such as ``/users/{x}/{y}/z`` and\n``/users/{x}/y/z``, the first one will be preferred over the\nsecond one.\n\nUser should never instantiate resource classes but give it by\n:meth:`UrlDispatcher.add_resource` call.\n\nAfter that he may add a :term:`route` by calling :meth:`Resource.add_route`.\n\n:meth:`UrlDispatcher.add_route` is just shortcut for::\n\n   router.add_resource(path).add_route(method, handler)\n\nResource with a *name* is called *named resource*.\nThe main purpose of *named resource* is constructing URL by route name for\npassing it into *template engine* for example::\n\n   url = app.router['resource_name'].url_for().with_query({'a': 1, 'b': 2})\n\nResource classes hierarchy::\n\n   AbstractResource\n     Resource\n       PlainResource\n       DynamicResource\n     PrefixResource\n       StaticResource\n       PrefixedSubAppResource\n          MatchedSubAppResource\n\n\n.. class:: AbstractResource\n\n   A base class for all resources.\n\n   Inherited from :class:`collections.abc.Sized` and\n   :class:`collections.abc.Iterable`.\n\n   ``len(resource)`` returns amount of :term:`route`\\s belongs to the resource,\n   ``for route in resource`` allows to iterate over these routes.\n\n   .. attribute:: name\n\n      Read-only *name* of resource or ``None``.\n\n   .. attribute:: canonical\n\n      Read-only *canonical path* associate with the resource. For example\n      ``/path/to`` or ``/path/{to}``\n\n      .. versionadded:: 3.3\n\n   .. method:: resolve(request)\n      :async:\n\n      Resolve resource by finding appropriate :term:`web-handler` for\n      ``(method, path)`` combination.\n\n      :return: (*match_info*, *allowed_methods*) pair.\n\n               *allowed_methods* is a :class:`set` or HTTP methods accepted by\n               resource.\n\n               *match_info* is either :class:`UrlMappingMatchInfo` if\n               request is resolved or ``None`` if no :term:`route` is\n               found.\n\n   .. method:: get_info()\n\n      A resource description, e.g. ``{'path': '/path/to'}`` or\n      ``{'formatter': '/path/{to}', 'pattern':\n      re.compile(r'^/path/(?P<to>[a-zA-Z][_a-zA-Z0-9]+)$``\n\n   .. method:: url_for(*args, **kwargs)\n\n      Construct an URL for route with additional params.\n\n      *args* and **kwargs** depend on a parameters list accepted by\n      inherited resource class.\n\n      :return: :class:`~yarl.URL` -- resulting URL instance.\n\n\n.. class:: Resource\n\n   A base class for new-style resources, inherits :class:`AbstractResource`.\n\n\n   .. method:: add_route(method, handler, *, expect_handler=None)\n\n      Add a :term:`web-handler` to resource.\n\n      :param str method: HTTP method for route. Should be one of\n                         ``'GET'``, ``'POST'``, ``'PUT'``,\n                         ``'DELETE'``, ``'PATCH'``, ``'HEAD'``,\n                         ``'OPTIONS'`` or ``'*'`` for any method.\n\n                         The parameter is case-insensitive, e.g. you\n                         can push ``'get'`` as well as ``'GET'``.\n\n                         The method should be unique for resource.\n\n      :param collections.abc.Callable handler: route handler.\n\n      :param collections.abc.Coroutine expect_handler: optional *expect* header handler.\n\n      :returns: new :class:`ResourceRoute` instance.\n\n\n.. class:: PlainResource\n\n   A resource, inherited from :class:`Resource`.\n\n   The class corresponds to resources with plain-text matching,\n   ``'/path/to'`` for example.\n\n   .. attribute:: canonical\n\n      Read-only *canonical path* associate with the resource. Returns the path\n      used to create the PlainResource. For example ``/path/to``\n\n      .. versionadded:: 3.3\n\n   .. method:: url_for()\n\n      Returns a :class:`~yarl.URL` for the resource.\n\n\n.. class:: DynamicResource\n\n   A resource, inherited from :class:`Resource`.\n\n   The class corresponds to resources with\n   :ref:`variable <aiohttp-web-variable-handler>` matching,\n   e.g. ``'/path/{to}/{param}'`` etc.\n\n   .. attribute:: canonical\n\n      Read-only *canonical path* associate with the resource. Returns the\n      formatter obtained from the path used to create the DynamicResource.\n      For example, from a path ``/get/{num:^\\d+}``, it returns ``/get/{num}``\n\n      .. versionadded:: 3.3\n\n   .. method:: url_for(**params)\n\n      Returns a :class:`~yarl.URL` for the resource.\n\n      :param params: -- a variable substitutions for dynamic resource.\n\n         E.g. for ``'/path/{to}/{param}'`` pattern the method should\n         be called as ``resource.url_for(to='val1', param='val2')``\n\n\n.. class:: StaticResource\n\n   A resource, inherited from :class:`Resource`.\n\n   The class corresponds to resources for :ref:`static file serving\n   <aiohttp-web-static-file-handling>`.\n\n   .. attribute:: canonical\n\n      Read-only *canonical path* associate with the resource. Returns the prefix\n      used to create the StaticResource. For example ``/prefix``\n\n      .. versionadded:: 3.3\n\n   .. method:: url_for(filename, append_version=None)\n\n      Returns a :class:`~yarl.URL` for file path under resource prefix.\n\n      :param filename: -- a file name substitution for static file handler.\n\n         Accepts both :class:`str` and :class:`pathlib.Path`.\n\n         E.g. an URL for ``'/prefix/dir/file.txt'`` should\n         be generated as ``resource.url_for(filename='dir/file.txt')``\n\n      :param bool append_version: -- a flag for adding file version\n                                  (hash) to the url query string for\n                                  cache boosting\n\n         By default has value from a constructor (``False`` by default)\n         When set to ``True`` - ``v=FILE_HASH`` query string param will be added\n         When set to ``False`` has no impact\n\n         if file not found has no impact\n\n\n.. class:: PrefixedSubAppResource\n\n   A resource for serving nested applications. The class instance is\n   returned by :class:`~aiohttp.web.Application.add_subapp` call.\n\n   .. attribute:: canonical\n\n      Read-only *canonical path* associate with the resource. Returns the\n      prefix used to create the PrefixedSubAppResource.\n      For example ``/prefix``\n\n      .. versionadded:: 3.3\n\n   .. method:: url_for(**kwargs)\n\n      The call is not allowed, it raises :exc:`RuntimeError`.\n\n\n.. _aiohttp-web-route:\n\nRoute\n^^^^^\n\nRoute has *HTTP method* (wildcard ``'*'`` is an option),\n:term:`web-handler` and optional *expect handler*.\n\nEvery route belong to some resource.\n\nRoute classes hierarchy::\n\n   AbstractRoute\n     ResourceRoute\n     SystemRoute\n\n:class:`ResourceRoute` is the route used for resources,\n:class:`SystemRoute` serves URL resolving errors like *404 Not Found*\nand *405 Method Not Allowed*.\n\n.. class:: AbstractRoute\n\n   Base class for routes served by :class:`UrlDispatcher`.\n\n   .. attribute:: method\n\n      HTTP method handled by the route, e.g. *GET*, *POST* etc.\n\n   .. attribute:: handler\n\n      :ref:`handler<aiohttp-web-handler>` that processes the route.\n\n   .. attribute:: name\n\n      Name of the route, always equals to name of resource which owns the route.\n\n   .. attribute:: resource\n\n      Resource instance which holds the route, ``None`` for\n      :class:`SystemRoute`.\n\n   .. method:: url_for(*args, **kwargs)\n\n      Abstract method for constructing url handled by the route.\n\n      Actually it's a shortcut for ``route.resource.url_for(...)``.\n\n   .. method:: handle_expect_header(request)\n      :async:\n\n      ``100-continue`` handler.\n\n.. class:: ResourceRoute\n\n   The route class for handling different HTTP methods for :class:`Resource`.\n\n\n.. class:: SystemRoute\n\n   The route class for handling URL resolution errors like like *404 Not Found*\n   and *405 Method Not Allowed*.\n\n   .. attribute:: status\n\n      HTTP status code\n\n   .. attribute:: reason\n\n      HTTP status reason\n\n\n.. _aiohttp-web-route-def:\n\n\nRouteDef and StaticDef\n^^^^^^^^^^^^^^^^^^^^^^\n\nRoute definition, a description for not registered yet route.\n\nCould be used for filing route table by providing a list of route\ndefinitions (Django style).\n\nThe definition is created by functions like :func:`get` or\n:func:`post`, list of definitions could be added to router by\n:meth:`UrlDispatcher.add_routes` call::\n\n   from aiohttp import web\n\n   async def handle_get(request):\n       ...\n\n\n   async def handle_post(request):\n       ...\n\n   app.router.add_routes([web.get('/get', handle_get),\n                          web.post('/post', handle_post),\n\n.. class:: AbstractRouteDef\n\n   A base class for route definitions.\n\n   Inherited from :class:`abc.ABC`.\n\n   .. versionadded:: 3.1\n\n   .. method:: register(router)\n\n      Register itself into :class:`UrlDispatcher`.\n\n      Abstract method, should be overridden by subclasses.\n\n      :returns: :class:`list` of registered :class:`AbstractRoute` objects.\n\n      .. versionchanged:: 3.7\n\n         Return value updated from ``None`` to :class:`list` of\n         :class:`AbstractRoute` instances.\n\n\n.. class:: RouteDef\n\n   A definition of not registered yet route.\n\n   Implements :class:`AbstractRouteDef`.\n\n   .. versionadded:: 2.3\n\n   .. versionchanged:: 3.1\n\n      The class implements :class:`AbstractRouteDef` interface.\n\n   .. attribute:: method\n\n      HTTP method (``GET``, ``POST`` etc.)  (:class:`str`).\n\n   .. attribute:: path\n\n      Path to resource, e.g. ``/path/to``. Could contain ``{}``\n      brackets for :ref:`variable resources\n      <aiohttp-web-variable-handler>` (:class:`str`).\n\n   .. attribute:: handler\n\n      An async function to handle HTTP request.\n\n   .. attribute:: kwargs\n\n      A :class:`dict` of additional arguments.\n\n\n.. class:: StaticDef\n\n   A definition of static file resource.\n\n   Implements :class:`AbstractRouteDef`.\n\n   .. versionadded:: 3.1\n\n   .. attribute:: prefix\n\n      A prefix used for static file handling, e.g. ``/static``.\n\n   .. attribute:: path\n\n      File system directory to serve, :class:`str` or\n      :class:`pathlib.Path`\n      (e.g. ``'/home/web-service/path/to/static'``.\n\n   .. attribute:: kwargs\n\n      A :class:`dict` of additional arguments, see\n      :meth:`UrlDispatcher.add_static` for a list of supported\n      options.\n\n\n.. function:: get(path, handler, *, name=None, allow_head=True, \\\n              expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``GET`` requests. See\n   :meth:`UrlDispatcher.add_get` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: post(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``POST`` requests. See\n   :meth:`UrlDispatcher.add_post` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: head(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``HEAD`` requests. See\n   :meth:`UrlDispatcher.add_head` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: put(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``PUT`` requests. See\n   :meth:`UrlDispatcher.add_put` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: patch(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``PATCH`` requests. See\n   :meth:`UrlDispatcher.add_patch` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: delete(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``DELETE`` requests. See\n   :meth:`UrlDispatcher.add_delete` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: view(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``ANY`` requests. See\n   :meth:`UrlDispatcher.add_view` for information about parameters.\n\n   .. versionadded:: 3.0\n\n.. function:: static(prefix, path, *, name=None, expect_handler=None, \\\n                     chunk_size=256*1024, \\\n                     show_index=False, follow_symlinks=False, \\\n                     append_version=False)\n\n   Return :class:`StaticDef` for processing static files.\n\n   See :meth:`UrlDispatcher.add_static` for information\n   about supported parameters.\n\n   .. versionadded:: 3.1\n\n.. function:: route(method, path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing requests that decided by\n   ``method``. See :meth:`UrlDispatcher.add_route` for information\n   about parameters.\n\n   .. versionadded:: 2.3\n\n\n.. _aiohttp-web-route-table-def:\n\nRouteTableDef\n^^^^^^^^^^^^^\n\nA routes table definition used for describing routes by decorators\n(Flask style)::\n\n   from aiohttp import web\n\n   routes = web.RouteTableDef()\n\n   @routes.get('/get')\n   async def handle_get(request):\n       ...\n\n\n   @routes.post('/post')\n   async def handle_post(request):\n       ...\n\n   app.router.add_routes(routes)\n\n\n   @routes.view(\"/view\")\n   class MyView(web.View):\n       async def get(self):\n           ...\n\n       async def post(self):\n           ...\n\n.. class:: RouteTableDef()\n\n   A sequence of :class:`RouteDef` instances (implements\n   :class:`collections.abc.Sequence` protocol).\n\n   In addition to all standard :class:`list` methods the class\n   provides also methods like ``get()`` and ``post()`` for adding new\n   route definition.\n\n   .. versionadded:: 2.3\n\n   .. decoratormethod:: get(path, *, allow_head=True, \\\n                            name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``GET`` web-handler.\n\n      See :meth:`UrlDispatcher.add_get` for information about parameters.\n\n   .. decoratormethod:: post(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``POST`` web-handler.\n\n      See :meth:`UrlDispatcher.add_post` for information about parameters.\n\n   .. decoratormethod:: head(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``HEAD`` web-handler.\n\n      See :meth:`UrlDispatcher.add_head` for information about parameters.\n\n   .. decoratormethod:: put(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``PUT`` web-handler.\n\n      See :meth:`UrlDispatcher.add_put` for information about parameters.\n\n   .. decoratormethod:: patch(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``PATCH`` web-handler.\n\n      See :meth:`UrlDispatcher.add_patch` for information about parameters.\n\n   .. decoratormethod:: delete(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``DELETE`` web-handler.\n\n      See :meth:`UrlDispatcher.add_delete` for information about parameters.\n\n   .. decoratormethod:: view(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``ANY`` methods\n      against a class-based view.\n\n      See :meth:`UrlDispatcher.add_view` for information about parameters.\n\n      .. versionadded:: 3.0\n\n   .. method:: static(prefix, path, *, name=None, expect_handler=None, \\\n                      chunk_size=256*1024, \\\n                      show_index=False, follow_symlinks=False, \\\n                      append_version=False)\n\n\n      Add a new :class:`StaticDef` item for registering static files processor.\n\n      See :meth:`UrlDispatcher.add_static` for information about\n      supported parameters.\n\n      .. versionadded:: 3.1\n\n   .. decoratormethod:: route(method, path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering a web-handler\n      for arbitrary HTTP method.\n\n      See :meth:`UrlDispatcher.add_route` for information about parameters.\n\n\nMatchInfo\n^^^^^^^^^\n\nAfter route matching web application calls found handler if any.\n\nMatching result can be accessible from handler as\n:attr:`Request.match_info` attribute.\n\nIn general the result may be any object derived from\n:class:`~aiohttp.abc.AbstractMatchInfo` (:class:`UrlMappingMatchInfo` for default\n:class:`UrlDispatcher` router).\n\n.. class:: UrlMappingMatchInfo\n\n   Inherited from :class:`dict` and :class:`~aiohttp.abc.AbstractMatchInfo`. Dict\n   items are filled by matching info and is :term:`resource`\\-specific.\n\n   .. attribute:: expect_handler\n\n      A coroutine for handling ``100-continue``.\n\n   .. attribute:: handler\n\n      A coroutine for handling request.\n\n   .. attribute:: route\n\n      :class:`AbstractRoute` instance for url matching.\n\n\nView\n^^^^\n\n.. class:: View(request)\n\n   Inherited from :class:`~aiohttp.abc.AbstractView`.\n\n   Base class for class based views. Implementations should derive from\n   :class:`View` and override methods for handling HTTP verbs like\n   ``get()`` or ``post()``::\n\n       class MyView(View):\n\n           async def get(self):\n               resp = await get_response(self.request)\n               return resp\n\n           async def post(self):\n               resp = await post_response(self.request)\n               return resp\n\n       app.router.add_view('/view', MyView)\n\n   The view raises *405 Method Not allowed*\n   (:class:`HTTPMethodNotAllowed`) if requested web verb is not\n   supported.\n\n   :param request: instance of :class:`Request` that has initiated a view\n                   processing.\n\n\n   .. attribute:: request\n\n      Request sent to view's constructor, read-only property.\n\n\n   Overridable coroutine methods: ``connect()``, ``delete()``,\n   ``get()``, ``head()``, ``options()``, ``patch()``, ``post()``,\n   ``put()``, ``trace()``.\n\n.. seealso:: :ref:`aiohttp-web-class-based-views`\n\n\n.. _aiohttp-web-app-runners-reference:\n\nRunning Applications\n--------------------\n\nTo start web application there is ``AppRunner`` and site classes.\n\nRunner is a storage for running application, sites are for running\napplication on specific TCP or Unix socket, e.g.::\n\n    runner = web.AppRunner(app)\n    await runner.setup()\n    site = web.TCPSite(runner, 'localhost', 8080)\n    await site.start()\n    # wait for finish signal\n    await runner.cleanup()\n\n\n.. versionadded:: 3.0\n\n   :class:`AppRunner` / :class:`ServerRunner` and :class:`TCPSite` /\n   :class:`UnixSite` / :class:`SockSite` are added in aiohttp 3.0\n\n\n.. class:: BaseRunner\n\n   A base class for runners. Use :class:`AppRunner` for serving\n   :class:`Application`, :class:`ServerRunner` for low-level\n   :class:`Server`.\n\n   .. attribute:: server\n\n      Low-level web :class:`Server` for handling HTTP requests,\n      read-only attribute.\n\n   .. attribute:: addresses\n\n      A  :class:`list` of served sockets addresses.\n\n      See :meth:`socket.getsockname() <socket.socket.getsockname>` for items type.\n\n      .. versionadded:: 3.3\n\n   .. attribute:: sites\n\n      A read-only :class:`set` of served sites (:class:`TCPSite` /\n      :class:`UnixSite` / :class:`NamedPipeSite` / :class:`SockSite` instances).\n\n   .. method:: setup()\n      :async:\n\n      Initialize the server. Should be called before adding sites.\n\n   .. method:: cleanup()\n      :async:\n\n      Stop handling all registered sites and cleanup used resources.\n\n\n.. class:: AppRunner(app, *, handle_signals=False, **kwargs)\n\n   A runner for :class:`Application`. Used with conjunction with sites\n   to serve on specific port.\n\n   Inherited from :class:`BaseRunner`.\n\n   :param Application app: web application instance to serve.\n\n   :param bool handle_signals: add signal handlers for\n                               :data:`signal.SIGINT` and\n                               :data:`signal.SIGTERM` (``False`` by\n                               default). These handlers will raise\n                               :exc:`GracefulExit`.\n\n   :param kwargs: named parameters to pass into\n                  web protocol.\n\n   Supported *kwargs*:\n\n   :param bool tcp_keepalive: Enable TCP Keep-Alive. Default: ``True``.\n   :param int keepalive_timeout: Number of seconds before closing Keep-Alive\n        connection. Default: ``3630`` seconds (when deployed behind a reverse proxy\n        it's important for this value to be higher than the proxy's timeout. To avoid\n        race conditions we always want the proxy to close the connection).\n   :param logger: Custom logger object. Default:\n        :data:`aiohttp.log.server_logger`.\n   :param access_log: Custom logging object. Default:\n        :data:`aiohttp.log.access_logger`.\n   :param access_log_class: Class for `access_logger`. Default:\n        :data:`aiohttp.helpers.AccessLogger`.\n        Must to be a subclass of :class:`aiohttp.abc.AbstractAccessLogger`.\n   :param str access_log_format: Access log format string. Default:\n        :attr:`helpers.AccessLogger.LOG_FORMAT`.\n   :param int max_line_size: Optional maximum header line size. Default:\n        ``8190``.\n   :param int max_field_size: Optional maximum header field size. Default:\n        ``8190``.\n\n   :param float lingering_time: Maximum time during which the server\n        reads and ignores additional data coming from the client when\n        lingering close is on.  Use ``0`` to disable lingering on\n        server channel closing.\n   :param int read_bufsize: Size of the read buffer (:attr:`BaseRequest.content`).\n                            ``None`` by default,\n                            it means that the session global value is used.\n\n      .. versionadded:: 3.7\n   :param bool auto_decompress: Automatically decompress request body,\n      ``True`` by default.\n\n      .. versionadded:: 3.8\n\n\n\n   .. attribute:: app\n\n      Read-only attribute for accessing to :class:`Application` served\n      instance.\n\n   .. method:: setup()\n      :async:\n\n      Initialize application. Should be called before adding sites.\n\n      The method calls :attr:`Application.on_startup` registered signals.\n\n   .. method:: cleanup()\n      :async:\n\n      Stop handling all registered sites and cleanup used resources.\n\n      :attr:`Application.on_shutdown` and\n      :attr:`Application.on_cleanup` signals are called internally.\n\n\n.. class:: ServerRunner(web_server, *, handle_signals=False, **kwargs)\n\n   A runner for low-level :class:`Server`. Used with conjunction with sites\n   to serve on specific port.\n\n   Inherited from :class:`BaseRunner`.\n\n   :param Server web_server: low-level web server instance to serve.\n\n   :param bool handle_signals: add signal handlers for\n                               :data:`signal.SIGINT` and\n                               :data:`signal.SIGTERM` (``False`` by\n                               default). These handlers will raise\n                               :exc:`GracefulExit`.\n\n   :param kwargs: named parameters to pass into\n                  web protocol.\n\n   .. seealso::\n\n      :ref:`aiohttp-web-lowlevel` demonstrates low-level server usage\n\n.. class:: BaseSite\n\n   An abstract class for handled sites.\n\n   .. attribute:: name\n\n      An identifier for site, read-only :class:`str` property. Could\n      be a handled URL or UNIX socket path.\n\n   .. method:: start()\n      :async:\n\n      Start handling a site.\n\n   .. method:: stop()\n      :async:\n\n      Stop handling a site.\n\n\n.. class:: TCPSite(runner, host=None, port=None, *, \\\n                   shutdown_timeout=60.0, ssl_context=None, \\\n                   backlog=128, reuse_address=None, \\\n                   reuse_port=None)\n\n   Serve a runner on TCP socket.\n\n   :param runner: a runner to serve.\n\n   :param str host: HOST to listen on, all interfaces if ``None`` (default).\n\n   :param int port: PORT to listed on, ``8080`` if ``None`` (default).\n\n   :param float shutdown_timeout: a timeout used for both waiting on pending\n                                  tasks before application shutdown and for\n                                  closing opened connections on\n                                  :meth:`BaseSite.stop` call.\n\n   :param ssl_context: a :class:`ssl.SSLContext` instance for serving\n                       SSL/TLS secure server, ``None`` for plain HTTP\n                       server (default).\n\n   :param int backlog: a number of unaccepted connections that the\n                       system will allow before refusing new\n                       connections, see :meth:`socket.socket.listen` for details.\n\n                       ``128`` by default.\n\n   :param bool reuse_address: tells the kernel to reuse a local socket in\n                              TIME_WAIT state, without waiting for its\n                              natural timeout to expire. If not specified\n                              will automatically be set to True on UNIX.\n\n   :param bool reuse_port: tells the kernel to allow this endpoint to be\n                           bound to the same port as other existing\n                           endpoints are bound to, so long as they all set\n                           this flag when being created. This option is not\n                           supported on Windows.\n\n.. class:: UnixSite(runner, path, *, \\\n                   shutdown_timeout=60.0, ssl_context=None, \\\n                   backlog=128)\n\n   Serve a runner on UNIX socket.\n\n   :param runner: a runner to serve.\n\n   :param str path: PATH to UNIX socket to listen.\n\n   :param float shutdown_timeout: a timeout used for both waiting on pending\n                                  tasks before application shutdown and for\n                                  closing opened connections on\n                                  :meth:`BaseSite.stop` call.\n\n   :param ssl_context: a :class:`ssl.SSLContext` instance for serving\n                       SSL/TLS secure server, ``None`` for plain HTTP\n                       server (default).\n\n   :param int backlog: a number of unaccepted connections that the\n                       system will allow before refusing new\n                       connections, see :meth:`socket.socket.listen` for details.\n\n                       ``128`` by default.\n\n.. class:: NamedPipeSite(runner, path, *, shutdown_timeout=60.0)\n\n   Serve a runner on Named Pipe in Windows.\n\n   :param runner: a runner to serve.\n\n   :param str path: PATH of named pipe to listen.\n\n   :param float shutdown_timeout: a timeout used for both waiting on pending\n                                  tasks before application shutdown and for\n                                  closing opened connections on\n                                  :meth:`BaseSite.stop` call.\n\n.. class:: SockSite(runner, sock, *, \\\n                   shutdown_timeout=60.0, ssl_context=None, \\\n                   backlog=128)\n\n   Serve a runner on UNIX socket.\n\n   :param runner: a runner to serve.\n\n   :param sock: A :ref:`socket instance <socket-objects>` to listen to.\n\n   :param float shutdown_timeout: a timeout used for both waiting on pending\n                                  tasks before application shutdown and for\n                                  closing opened connections on\n                                  :meth:`BaseSite.stop` call.\n\n   :param ssl_context: a :class:`ssl.SSLContext` instance for serving\n                       SSL/TLS secure server, ``None`` for plain HTTP\n                       server (default).\n\n   :param int backlog: a number of unaccepted connections that the\n                       system will allow before refusing new\n                       connections, see :meth:`socket.socket.listen` for details.\n\n                       ``128`` by default.\n\n.. exception:: GracefulExit\n\n   Raised by signal handlers for :data:`signal.SIGINT` and :data:`signal.SIGTERM`\n   defined in :class:`AppRunner` and :class:`ServerRunner`\n   when ``handle_signals`` is set to ``True``.\n\n   Inherited from :exc:`SystemExit`,\n   which exits with error code ``1`` if not handled.\n\n\nUtilities\n---------\n\n.. class:: FileField\n\n   A :mod:`dataclass <dataclasses>` instance that is returned as\n   multidict value by :meth:`aiohttp.web.BaseRequest.post` if field is uploaded file.\n\n   .. attribute:: name\n\n      Field name\n\n   .. attribute:: filename\n\n      File name as specified by uploading (client) side.\n\n   .. attribute:: file\n\n      An :class:`io.IOBase` instance with content of uploaded file.\n\n   .. attribute:: content_type\n\n      *MIME type* of uploaded file, ``'text/plain'`` by default.\n\n   .. seealso:: :ref:`aiohttp-web-file-upload`\n\n\n.. function:: run_app(app, *, debug=False, host=None, port=None, \\\n                      path=None, sock=None, shutdown_timeout=60.0, \\\n                      keepalive_timeout=3630, ssl_context=None, \\\n                      print=print, backlog=128, \\\n                      access_log_class=aiohttp.helpers.AccessLogger, \\\n                      access_log_format=aiohttp.helpers.AccessLogger.LOG_FORMAT, \\\n                      access_log=aiohttp.log.access_logger, \\\n                      handle_signals=True, \\\n                      reuse_address=None, \\\n                      reuse_port=None, \\\n                      handler_cancellation=False)\n\n   A high-level function for running an application, serving it until\n   keyboard interrupt and performing a\n   :ref:`aiohttp-web-graceful-shutdown`.\n\n   This is a high-level function very similar to :func:`asyncio.run` and\n   should be used as the main entry point for an application. The\n   :class:`Application` object essentially becomes our `main()` function.\n   If additional tasks need to be run in parallel, see\n   :ref:`aiohttp-web-complex-applications`.\n\n   The server will listen on any host or Unix domain socket path you supply.\n   If no hosts or paths are supplied, or only a port is supplied, a TCP server\n   listening on 0.0.0.0 (all hosts) will be launched.\n\n   Distributing HTTP traffic to multiple hosts or paths on the same\n   application process provides no performance benefit as the requests are\n   handled on the same event loop. See :doc:`deployment` for ways of\n   distributing work for increased performance.\n\n   :param app: :class:`Application` instance to run or a *coroutine*\n               that returns an application.\n\n   :param bool debug: enable :ref:`asyncio debug mode <asyncio-debug-mode>` if ``True``.\n\n   :param str host: TCP/IP host or a sequence of hosts for HTTP server.\n                    Default is ``'0.0.0.0'`` if *port* has been specified\n                    or if *path* is not supplied.\n\n   :param int port: TCP/IP port for HTTP server. Default is ``8080`` for plain\n                    text HTTP and ``8443`` for HTTP via SSL (when\n                    *ssl_context* parameter is specified).\n\n   :param path: file system path for HTTP server Unix domain socket.\n                    A sequence of file system paths can be used to bind\n                    multiple domain sockets. Listening on Unix domain\n                    sockets is not supported by all operating systems,\n                    :class:`str`, :class:`pathlib.Path` or an iterable of these.\n\n   :param socket.socket sock: a preexisting socket object to accept connections on.\n                       A sequence of socket objects can be passed.\n\n   :param int shutdown_timeout: a delay to wait for graceful server\n                                shutdown before disconnecting all\n                                open client sockets hard way.\n\n                                This is used as a delay to wait for\n                                pending tasks to complete and then\n                                again to close any pending connections.\n\n                                A system with properly\n                                :ref:`aiohttp-web-graceful-shutdown`\n                                implemented never waits for the second\n                                timeout but closes a server in a few\n                                milliseconds.\n\n   :param float keepalive_timeout: a delay before a TCP connection is\n                                   closed after a HTTP request. The delay\n                                   allows for reuse of a TCP connection.\n\n                                   When deployed behind a reverse proxy\n                                   it's important for this value to be\n                                   higher than the proxy's timeout. To avoid\n                                   race conditions, we always want the proxy\n                                   to handle connection closing.\n\n      .. versionadded:: 3.8\n\n   :param ssl_context: :class:`ssl.SSLContext` for HTTPS server,\n                       ``None`` for HTTP connection.\n\n   :param print: a callable compatible with :func:`print`. May be used\n                 to override STDOUT output or suppress it. Passing `None`\n                 disables output.\n\n   :param int backlog: the number of unaccepted connections that the\n                       system will allow before refusing new\n                       connections (``128`` by default).\n\n   :param access_log_class: class for `access_logger`. Default:\n                            :data:`aiohttp.helpers.AccessLogger`.\n                            Must to be a subclass of :class:`aiohttp.abc.AbstractAccessLogger`.\n\n   :param access_log: :class:`logging.Logger` instance used for saving\n                      access logs. Use ``None`` for disabling logs for\n                      sake of speedup.\n\n   :param access_log_format: access log format, see\n                             :ref:`aiohttp-logging-access-log-format-spec`\n                             for details.\n\n   :param bool handle_signals: override signal TERM handling to gracefully\n                               exit the application.\n\n   :param bool reuse_address: tells the kernel to reuse a local socket in\n                              TIME_WAIT state, without waiting for its\n                              natural timeout to expire. If not specified\n                              will automatically be set to True on UNIX.\n\n   :param bool reuse_port: tells the kernel to allow this endpoint to be\n                           bound to the same port as other existing\n                           endpoints are bound to, so long as they all set\n                           this flag when being created. This option is not\n                           supported on Windows.\n\n   :param bool handler_cancellation: cancels the web handler task if the client\n                                     drops the connection. This is recommended\n                                     if familiar with asyncio behavior or\n                                     scalability is a concern.\n                                     :ref:`aiohttp-web-peer-disconnection`\n\n   .. versionadded:: 3.0\n\n      Support *access_log_class* parameter.\n\n      Support *reuse_address*, *reuse_port* parameter.\n\n   .. versionadded:: 3.1\n\n      Accept a coroutine as *app* parameter.\n\n   .. versionadded:: 3.9\n\n      Support handler_cancellation parameter (this was the default behavior\n      in aiohttp <3.7).\n\nConstants\n---------\n\n.. class:: ContentCoding\n\n   An :class:`enum.Enum` class of available Content Codings.\n\n   .. attribute:: deflate\n\n      *DEFLATE compression*\n\n   .. attribute:: gzip\n\n      *GZIP compression*\n\n   .. attribute:: identity\n\n      *no compression*\n\n\nMiddlewares\n-----------\n\n.. function:: normalize_path_middleware(*, \\\n                                        append_slash=True, \\\n                                        remove_slash=False, \\\n                                        merge_slashes=True, \\\n                                        redirect_class=HTTPPermanentRedirect)\n\n   Middleware factory which produces a middleware that normalizes\n   the path of a request. By normalizing it means:\n\n     - Add or remove a trailing slash to the path.\n     - Double slashes are replaced by one.\n\n   The middleware returns as soon as it finds a path that resolves\n   correctly. The order if both merge and append/remove are enabled is:\n\n     1. *merge_slashes*\n     2. *append_slash* or *remove_slash*\n     3. both *merge_slashes* and *append_slash* or *remove_slash*\n\n   If the path resolves with at least one of those conditions, it will\n   redirect to the new path.\n\n   Only one of *append_slash* and *remove_slash* can be enabled. If both are\n   ``True`` the factory will raise an ``AssertionError``\n\n   If *append_slash* is ``True`` the middleware will append a slash when\n   needed. If a resource is defined with trailing slash and the request\n   comes without it, it will append it automatically.\n\n   If *remove_slash* is ``True``, *append_slash* must be ``False``. When enabled\n   the middleware will remove trailing slashes and redirect if the resource is\n   defined.\n\n   If *merge_slashes* is ``True``, merge multiple consecutive slashes in the\n   path into one.\n\n   .. versionadded:: 3.4\n\n      Support for *remove_slash*\n",
            "new_file_content": ".. currentmodule:: aiohttp.web\n\n.. _aiohttp-web-reference:\n\nServer Reference\n================\n\n.. _aiohttp-web-request:\n\n\nRequest and Base Request\n------------------------\n\nThe Request object contains all the information about an incoming HTTP request.\n\n:class:`BaseRequest` is used for :ref:`Low-Level\nServers<aiohttp-web-lowlevel>` (which have no applications, routers,\nsignals and middlewares). :class:`Request` has an :attr:`Request.app`\nand :attr:`Request.match_info` attributes.\n\nA :class:`BaseRequest` / :class:`Request` are :obj:`dict` like objects,\nallowing them to be used for :ref:`sharing\ndata<aiohttp-web-data-sharing>` among :ref:`aiohttp-web-middlewares`\nand :ref:`aiohttp-web-signals` handlers.\n\n.. class:: BaseRequest\n\n   .. attribute:: version\n\n      *HTTP version* of request, Read-only property.\n\n      Returns :class:`aiohttp.protocol.HttpVersion` instance.\n\n   .. attribute:: method\n\n      *HTTP method*, read-only property.\n\n      The value is upper-cased :class:`str` like ``\"GET\"``,\n      ``\"POST\"``, ``\"PUT\"`` etc.\n\n   .. attribute:: url\n\n      A :class:`~yarl.URL` instance with absolute URL to resource\n      (*scheme*, *host* and *port* are included).\n\n      .. note::\n\n         In case of malformed request (e.g. without ``\"HOST\"`` HTTP\n         header) the absolute url may be unavailable.\n\n   .. attribute:: rel_url\n\n      A :class:`~yarl.URL` instance with relative URL to resource\n      (contains *path*, *query* and *fragment* parts only, *scheme*,\n      *host* and *port* are excluded).\n\n      The property is equal to ``.url.relative()`` but is always present.\n\n      .. seealso::\n\n         A note from :attr:`url`.\n\n   .. attribute:: scheme\n\n      A string representing the scheme of the request.\n\n      The scheme is ``'https'`` if transport for request handling is\n      *SSL*, ``'http'`` otherwise.\n\n      The value could be overridden by :meth:`~BaseRequest.clone`.\n\n      Read-only :class:`str` property.\n\n      .. versionchanged:: 2.3\n\n         *Forwarded* and *X-Forwarded-Proto* are not used anymore.\n\n         Call ``.clone(scheme=new_scheme)`` for setting up the value\n         explicitly.\n\n      .. seealso:: :ref:`aiohttp-web-forwarded-support`\n\n   .. attribute:: secure\n\n      Shorthand for ``request.url.scheme == 'https'``\n\n      Read-only :class:`bool` property.\n\n      .. seealso:: :attr:`scheme`\n\n   .. attribute:: forwarded\n\n      A tuple containing all parsed Forwarded header(s).\n\n      Makes an effort to parse Forwarded headers as specified by :rfc:`7239`:\n\n      - It adds one (immutable) dictionary per Forwarded ``field-value``, i.e.\n        per proxy. The element corresponds to the data in the Forwarded\n        ``field-value`` added by the first proxy encountered by the client.\n        Each subsequent item corresponds to those added by later proxies.\n      - It checks that every value has valid syntax in general as specified\n        in :rfc:`7239#section-4`: either a ``token`` or a ``quoted-string``.\n      - It un-escapes ``quoted-pairs``.\n      - It does NOT validate 'by' and 'for' contents as specified in\n        :rfc:`7239#section-6`.\n      - It does NOT validate ``host`` contents (Host ABNF).\n      - It does NOT validate ``proto`` contents for valid URI scheme names.\n\n      Returns a tuple containing one or more ``MappingProxy`` objects\n\n      .. seealso:: :attr:`scheme`\n\n      .. seealso:: :attr:`host`\n\n   .. attribute:: host\n\n      Host name of the request, resolved in this order:\n\n      - Overridden value by :meth:`~BaseRequest.clone` call.\n      - *Host* HTTP header\n      - :func:`socket.getfqdn`\n\n      Read-only :class:`str` property.\n\n      .. versionchanged:: 2.3\n\n         *Forwarded* and *X-Forwarded-Host* are not used anymore.\n\n         Call ``.clone(host=new_host)`` for setting up the value\n         explicitly.\n\n      .. seealso:: :ref:`aiohttp-web-forwarded-support`\n\n   .. attribute:: remote\n\n      Originating IP address of a client initiated HTTP request.\n\n      The IP is resolved through the following headers, in this order:\n\n      - Overridden value by :meth:`~BaseRequest.clone` call.\n      - Peer name of opened socket.\n\n      Read-only :class:`str` property.\n\n      Call ``.clone(remote=new_remote)`` for setting up the value\n      explicitly.\n\n      .. versionadded:: 2.3\n\n      .. seealso:: :ref:`aiohttp-web-forwarded-support`\n\n   .. attribute:: client_max_size\n\n      The maximum size of the request body.\n\n      The value could be overridden by :meth:`~BaseRequest.clone`.\n\n      Read-only :class:`int` property.\n\n   .. attribute:: path_qs\n\n      The URL including PATH_INFO and the query string. e.g.,\n      ``/app/blog?id=10``\n\n      Read-only :class:`str` property.\n\n   .. attribute:: path\n\n      The URL including *PATH INFO* without the host or scheme. e.g.,\n      ``/app/blog``. The path is URL-decoded. For raw path info see\n      :attr:`raw_path`.\n\n      Read-only :class:`str` property.\n\n   .. attribute:: raw_path\n\n      The URL including raw *PATH INFO* without the host or scheme.\n      Warning, the path may be URL-encoded and may contain invalid URL\n      characters, e.g.\n      ``/my%2Fpath%7Cwith%21some%25strange%24characters``.\n\n      For URL-decoded version please take a look on :attr:`path`.\n\n      Read-only :class:`str` property.\n\n   .. attribute:: query\n\n      A multidict with all the variables in the query string.\n\n      Read-only :class:`~multidict.MultiDictProxy` lazy property.\n\n   .. attribute:: query_string\n\n      The query string in the URL, e.g., ``id=10``\n\n      Read-only :class:`str` property.\n\n   .. attribute:: headers\n\n      A case-insensitive multidict proxy with all headers.\n\n      Read-only :class:`~multidict.CIMultiDictProxy` property.\n\n   .. attribute:: raw_headers\n\n      HTTP headers of response as unconverted bytes, a sequence of\n      ``(key, value)`` pairs.\n\n   .. attribute:: keep_alive\n\n      ``True`` if keep-alive connection enabled by HTTP client and\n      protocol version supports it, otherwise ``False``.\n\n      Read-only :class:`bool` property.\n\n   .. attribute:: transport\n\n      A :ref:`transport<asyncio-transport>` used to process request.\n      Read-only property.\n\n      The property can be used, for example, for getting IP address of\n      client's peer::\n\n         peername = request.transport.get_extra_info('peername')\n         if peername is not None:\n             host, port = peername\n\n   .. attribute:: cookies\n\n      A read-only dictionary-like object containing the request's cookies.\n\n      Read-only :class:`~types.MappingProxyType` property.\n\n   .. attribute:: content\n\n      A :class:`~aiohttp.StreamReader` instance,\n      input stream for reading request's *BODY*.\n\n      Read-only property.\n\n   .. attribute:: body_exists\n\n      Return ``True`` if request has *HTTP BODY*, ``False`` otherwise.\n\n      Read-only :class:`bool` property.\n\n      .. versionadded:: 2.3\n\n   .. attribute:: can_read_body\n\n      Return ``True`` if request's *HTTP BODY* can be read, ``False`` otherwise.\n\n      Read-only :class:`bool` property.\n\n      .. versionadded:: 2.3\n\n   .. attribute:: content_type\n\n      Read-only property with *content* part of *Content-Type* header.\n\n      Returns :class:`str` like ``'text/html'``\n\n      .. note::\n\n         Returns value is ``'application/octet-stream'`` if no\n         Content-Type header present in HTTP headers according to\n         :rfc:`2616`\n\n   .. attribute:: charset\n\n      Read-only property that specifies the *encoding* for the request's BODY.\n\n      The value is parsed from the *Content-Type* HTTP header.\n\n      Returns :class:`str` like ``'utf-8'`` or ``None`` if\n      *Content-Type* has no charset information.\n\n   .. attribute:: content_length\n\n      Read-only property that returns length of the request's BODY.\n\n      The value is parsed from the *Content-Length* HTTP header.\n\n      Returns :class:`int` or ``None`` if *Content-Length* is absent.\n\n   .. attribute:: http_range\n\n      Read-only property that returns information about *Range* HTTP header.\n\n      Returns a :class:`slice` where ``.start`` is *left inclusive\n      bound*, ``.stop`` is *right exclusive bound* and ``.step`` is\n      ``1``.\n\n      The property might be used in two manners:\n\n      1. Attribute-access style (example assumes that both left and\n         right borders are set, the real logic for case of open bounds\n         is more complex)::\n\n            rng = request.http_range\n            with open(filename, 'rb') as f:\n                f.seek(rng.start)\n                return f.read(rng.stop-rng.start)\n\n      2. Slice-style::\n\n            return buffer[request.http_range]\n\n   .. attribute:: if_modified_since\n\n      Read-only property that returns the date specified in the\n      *If-Modified-Since* header.\n\n      Returns :class:`datetime.datetime` or ``None`` if\n      *If-Modified-Since* header is absent or is not a valid\n      HTTP date.\n\n   .. attribute:: if_unmodified_since\n\n      Read-only property that returns the date specified in the\n      *If-Unmodified-Since* header.\n\n      Returns :class:`datetime.datetime` or ``None`` if\n      *If-Unmodified-Since* header is absent or is not a valid\n      HTTP date.\n\n      .. versionadded:: 3.1\n\n   .. attribute:: if_match\n\n      Read-only property that returns :class:`~aiohttp.ETag` objects specified\n      in the *If-Match* header.\n\n      Returns :class:`tuple` of :class:`~aiohttp.ETag` or ``None`` if\n      *If-Match* header is absent.\n\n      .. versionadded:: 3.8\n\n   .. attribute:: if_none_match\n\n      Read-only property that returns :class:`~aiohttp.ETag` objects specified\n      *If-None-Match* header.\n\n      Returns :class:`tuple` of :class:`~aiohttp.ETag` or ``None`` if\n      *If-None-Match* header is absent.\n\n      .. versionadded:: 3.8\n\n   .. attribute:: if_range\n\n      Read-only property that returns the date specified in the\n      *If-Range* header.\n\n      Returns :class:`datetime.datetime` or ``None`` if\n      *If-Range* header is absent or is not a valid\n      HTTP date.\n\n      .. versionadded:: 3.1\n\n   .. method:: clone(*, method=..., rel_url=..., headers=...)\n\n      Clone itself with replacement some attributes.\n\n      Creates and returns a new instance of Request object. If no parameters\n      are given, an exact copy is returned. If a parameter is not passed, it\n      will reuse the one from the current request object.\n\n      :param str method: http method\n\n      :param rel_url: url to use, :class:`str` or :class:`~yarl.URL`\n\n      :param headers: :class:`~multidict.CIMultiDict` or compatible\n                      headers container.\n\n      :return: a cloned :class:`Request` instance.\n\n   .. method:: get_extra_info(name, default=None)\n\n      Reads extra information from the protocol's transport.\n      If no value associated with ``name`` is found, ``default`` is returned.\n\n      See :meth:`asyncio.BaseTransport.get_extra_info`\n\n      :param str name: The key to look up in the transport extra information.\n\n      :param default: Default value to be used when no value for ``name`` is\n                      found (default is ``None``).\n\n      .. versionadded:: 3.7\n\n   .. method:: read()\n      :async:\n\n      Read request body, returns :class:`bytes` object with body content.\n\n      .. note::\n\n         The method **does** store read data internally, subsequent\n         :meth:`~aiohttp.web.BaseRequest.read` call will return the same value.\n\n   .. method:: text()\n      :async:\n\n      Read request body, decode it using :attr:`charset` encoding or\n      ``UTF-8`` if no encoding was specified in *MIME-type*.\n\n      Returns :class:`str` with body content.\n\n      .. note::\n\n         The method **does** store read data internally, subsequent\n         :meth:`~aiohttp.web.BaseRequest.text` call will return the same value.\n\n   .. method:: json(*, loads=json.loads, \\\n                    content_type='application/json')\n      :async:\n\n      Read request body decoded as *json*. If request's content-type does not\n      match `content_type` parameter, :exc:`aiohttp.web.HTTPBadRequest` get raised.\n      To disable content type check pass ``None`` value.\n\n      :param collections.abc.Callable loads: any :term:`callable` that accepts\n                              :class:`str` and returns :class:`dict`\n                              with parsed JSON (:func:`json.loads` by\n                              default).\n      :param str content_type: expected value of Content-Type header or ``None``\n                              ('application/json' by default)\n\n      .. note::\n\n         The method **does** store read data internally, subsequent\n         :meth:`~aiohttp.web.BaseRequest.json` call will return the same value.\n\n\n   .. method:: multipart()\n      :async:\n\n      Returns :class:`aiohttp.MultipartReader` which processes\n      incoming *multipart* request.\n\n      The method is just a boilerplate :ref:`coroutine <coroutine>`\n      implemented as::\n\n         async def multipart(self, *, reader=aiohttp.multipart.MultipartReader):\n             return reader(self.headers, self._payload)\n\n      This method is a coroutine for consistency with the else reader methods.\n\n      .. warning::\n\n         The method **does not** store read data internally. That means once\n         you exhausts multipart reader, you cannot get the request payload one\n         more time.\n\n      .. seealso:: :ref:`aiohttp-multipart`\n\n      .. versionchanged:: 3.4\n\n         Dropped *reader* parameter.\n\n   .. method:: post()\n      :async:\n\n      A :ref:`coroutine <coroutine>` that reads POST parameters from\n      request body.\n\n      Returns :class:`~multidict.MultiDictProxy` instance filled\n      with parsed data.\n\n      If :attr:`method` is not *POST*, *PUT*, *PATCH*, *TRACE* or *DELETE* or\n      :attr:`content_type` is not empty or\n      *application/x-www-form-urlencoded* or *multipart/form-data*\n      returns empty multidict.\n\n      .. note::\n\n         The method **does** store read data internally, subsequent\n         :meth:`~aiohttp.web.BaseRequest.post` call will return the same value.\n\n   .. method:: release()\n      :async:\n\n      Release request.\n\n      Eat unread part of HTTP BODY if present.\n\n      .. note::\n\n          User code may never call :meth:`~aiohttp.web.BaseRequest.release`, all\n          required work will be processed by :mod:`aiohttp.web`\n          internal machinery.\n\n.. class:: Request\n\n   A request used for receiving request's information by *web handler*.\n\n   Every :ref:`handler<aiohttp-web-handler>` accepts a request\n   instance as the first positional parameter.\n\n   The class in derived from :class:`BaseRequest`, shares all parent's\n   attributes and methods but has a couple of additional properties:\n\n   .. attribute:: match_info\n\n      Read-only property with :class:`~aiohttp.abc.AbstractMatchInfo`\n      instance for result of route resolving.\n\n      .. note::\n\n         Exact type of property depends on used router.  If\n         ``app.router`` is :class:`UrlDispatcher` the property contains\n         :class:`UrlMappingMatchInfo` instance.\n\n   .. attribute:: app\n\n      An :class:`Application` instance used to call :ref:`request handler\n      <aiohttp-web-handler>`, Read-only property.\n\n   .. attribute:: config_dict\n\n      A :class:`aiohttp.ChainMapProxy` instance for mapping all properties\n      from the current application returned by :attr:`app` property\n      and all its parents.\n\n      .. seealso:: :ref:`aiohttp-web-data-sharing-app-config`\n\n      .. versionadded:: 3.2\n\n   .. note::\n\n      You should never create the :class:`Request` instance manually\n      -- :mod:`aiohttp.web` does it for you. But\n      :meth:`~BaseRequest.clone` may be used for cloning *modified*\n      request copy with changed *path*, *method* etc.\n\n\n\n\n.. _aiohttp-web-response:\n\n\nResponse classes\n----------------\n\nFor now, :mod:`aiohttp.web` has three classes for the *HTTP response*:\n:class:`StreamResponse`, :class:`Response` and :class:`FileResponse`.\n\nUsually you need to use the second one. :class:`StreamResponse` is\nintended for streaming data, while :class:`Response` contains *HTTP\nBODY* as an attribute and sends own content as single piece with the\ncorrect *Content-Length HTTP header*.\n\nFor sake of design decisions :class:`Response` is derived from\n:class:`StreamResponse` parent class.\n\nThe response supports *keep-alive* handling out-of-the-box if\n*request* supports it.\n\nYou can disable *keep-alive* by :meth:`~StreamResponse.force_close` though.\n\nThe common case for sending an answer from\n:ref:`web-handler<aiohttp-web-handler>` is returning a\n:class:`Response` instance::\n\n   async def handler(request):\n       return Response(text=\"All right!\")\n\nResponse classes are :obj:`dict` like objects,\nallowing them to be used for :ref:`sharing\ndata<aiohttp-web-data-sharing>` among :ref:`aiohttp-web-middlewares`\nand :ref:`aiohttp-web-signals` handlers::\n\n   resp['key'] = value\n\n.. versionadded:: 3.0\n\n   Dict-like interface support.\n\n\n.. class:: StreamResponse(*, status=200, reason=None)\n\n   The base class for the *HTTP response* handling.\n\n   Contains methods for setting *HTTP response headers*, *cookies*,\n   *response status code*, writing *HTTP response BODY* and so on.\n\n   The most important thing you should know about *response* --- it\n   is *Finite State Machine*.\n\n   That means you can do any manipulations with *headers*, *cookies*\n   and *status code* only before :meth:`prepare` coroutine is called.\n\n   Once you call :meth:`prepare` any change of\n   the *HTTP header* part will raise :exc:`RuntimeError` exception.\n\n   Any :meth:`write` call after :meth:`write_eof` is also forbidden.\n\n   :param int status: HTTP status code, ``200`` by default.\n\n   :param str reason: HTTP reason. If param is ``None`` reason will be\n                      calculated basing on *status*\n                      parameter. Otherwise pass :class:`str` with\n                      arbitrary *status* explanation..\n\n   .. attribute:: prepared\n\n      Read-only :class:`bool` property, ``True`` if :meth:`prepare` has\n      been called, ``False`` otherwise.\n\n   .. attribute:: task\n\n      A task that serves HTTP request handling.\n\n      May be useful for graceful shutdown of long-running requests\n      (streaming, long polling or web-socket).\n\n   .. attribute:: status\n\n      Read-only property for *HTTP response status code*, :class:`int`.\n\n      ``200`` (OK) by default.\n\n   .. attribute:: reason\n\n      Read-only property for *HTTP response reason*, :class:`str`.\n\n   .. method:: set_status(status, reason=None)\n\n      Set :attr:`status` and :attr:`reason`.\n\n      *reason* value is auto calculated if not specified (``None``).\n\n   .. attribute:: keep_alive\n\n      Read-only property, copy of :attr:`aiohttp.web.BaseRequest.keep_alive` by default.\n\n      Can be switched to ``False`` by :meth:`force_close` call.\n\n   .. method:: force_close\n\n      Disable :attr:`keep_alive` for connection. There are no ways to\n      enable it back.\n\n   .. attribute:: compression\n\n      Read-only :class:`bool` property, ``True`` if compression is enabled.\n\n      ``False`` by default.\n\n      .. seealso:: :meth:`enable_compression`\n\n   .. method:: enable_compression(force=None, strategy=zlib.Z_DEFAULT_STRATEGY)\n\n      Enable compression.\n\n      When *force* is unset compression encoding is selected based on\n      the request's *Accept-Encoding* header.\n\n      *Accept-Encoding* is not checked if *force* is set to a\n      :class:`ContentCoding`.\n\n      *strategy* accepts a :mod:`zlib` compression strategy.\n      See :func:`zlib.compressobj` for possible values.\n\n      .. seealso:: :attr:`compression`\n\n   .. attribute:: chunked\n\n      Read-only property, indicates if chunked encoding is on.\n\n      Can be enabled by :meth:`enable_chunked_encoding` call.\n\n      .. seealso:: :attr:`enable_chunked_encoding`\n\n   .. method:: enable_chunked_encoding()\n\n      Enables :attr:`chunked` encoding for response. There are no ways to\n      disable it back. With enabled :attr:`chunked` encoding each :meth:`write`\n      operation encoded in separate chunk.\n\n      .. warning:: chunked encoding can be enabled for ``HTTP/1.1`` only.\n\n                   Setting up both :attr:`content_length` and chunked\n                   encoding is mutually exclusive.\n\n      .. seealso:: :attr:`chunked`\n\n   .. attribute:: headers\n\n      :class:`~multidict.CIMultiDict` instance\n      for *outgoing* *HTTP headers*.\n\n   .. attribute:: cookies\n\n      An instance of :class:`http.cookies.SimpleCookie` for *outgoing* cookies.\n\n      .. warning::\n\n         Direct setting up *Set-Cookie* header may be overwritten by\n         explicit calls to cookie manipulation.\n\n         We are encourage using of :attr:`cookies` and\n         :meth:`set_cookie`, :meth:`del_cookie` for cookie\n         manipulations.\n\n   .. method:: set_cookie(name, value, *, path='/', expires=None, \\\n                          domain=None, max_age=None, \\\n                          secure=None, httponly=None, samesite=None)\n\n      Convenient way for setting :attr:`cookies`, allows to specify\n      some additional properties like *max_age* in a single call.\n\n      :param str name: cookie name\n\n      :param str value: cookie value (will be converted to\n                        :class:`str` if value has another type).\n\n      :param expires: expiration date (optional)\n\n      :param str domain: cookie domain (optional)\n\n      :param int max_age: defines the lifetime of the cookie, in\n                          seconds.  The delta-seconds value is a\n                          decimal non- negative integer.  After\n                          delta-seconds seconds elapse, the client\n                          should discard the cookie.  A value of zero\n                          means the cookie should be discarded\n                          immediately.  (optional)\n\n      :param str path: specifies the subset of URLs to\n                       which this cookie applies. (optional, ``'/'`` by default)\n\n      :param bool secure: attribute (with no value) directs\n                          the user agent to use only (unspecified)\n                          secure means to contact the origin server\n                          whenever it sends back this cookie.\n                          The user agent (possibly under the user's\n                          control) may determine what level of\n                          security it considers appropriate for\n                          \"secure\" cookies.  The *secure* should be\n                          considered security advice from the server\n                          to the user agent, indicating that it is in\n                          the session's interest to protect the cookie\n                          contents. (optional)\n\n      :param bool httponly: ``True`` if the cookie HTTP only (optional)\n\n      :param str samesite: Asserts that a cookie must not be sent with\n         cross-origin requests, providing some protection\n         against cross-site request forgery attacks.\n         Generally the value should be one of: ``None``,\n         ``Lax`` or ``Strict``. (optional)\n\n            .. versionadded:: 3.7\n\n   .. method:: del_cookie(name, *, path='/', domain=None)\n\n      Deletes cookie.\n\n      :param str name: cookie name\n\n      :param str domain: optional cookie domain\n\n      :param str path: optional cookie path, ``'/'`` by default\n\n   .. attribute:: content_length\n\n      *Content-Length* for outgoing response.\n\n   .. attribute:: content_type\n\n      *Content* part of *Content-Type* for outgoing response.\n\n   .. attribute:: charset\n\n      *Charset* aka *encoding* part of *Content-Type* for outgoing response.\n\n      The value converted to lower-case on attribute assigning.\n\n   .. attribute:: last_modified\n\n      *Last-Modified* header for outgoing response.\n\n      This property accepts raw :class:`str` values,\n      :class:`datetime.datetime` objects, Unix timestamps specified\n      as an :class:`int` or a :class:`float` object, and the\n      value ``None`` to unset the header.\n\n   .. attribute:: etag\n\n      *ETag* header for outgoing response.\n\n      This property accepts raw :class:`str` values, :class:`~aiohttp.ETag`\n      objects and the value ``None`` to unset the header.\n\n      In case of :class:`str` input, etag is considered as strong by default.\n\n      **Do not** use double quotes ``\"`` in the etag value,\n      they will be added automatically.\n\n      .. versionadded:: 3.8\n\n   .. method:: prepare(request)\n      :async:\n\n      :param aiohttp.web.Request request: HTTP request object, that the\n                                          response answers.\n\n      Send *HTTP header*. You should not change any header data after\n      calling this method.\n\n      The coroutine calls :attr:`~aiohttp.web.Application.on_response_prepare`\n      signal handlers after default headers have been computed and directly\n      before headers are sent.\n\n   .. method:: write(data)\n      :async:\n\n      Send byte-ish data as the part of *response BODY*::\n\n          await resp.write(data)\n\n      :meth:`prepare` must be invoked before the call.\n\n      Raises :exc:`TypeError` if data is not :class:`bytes`,\n      :class:`bytearray` or :class:`memoryview` instance.\n\n      Raises :exc:`RuntimeError` if :meth:`prepare` has not been called.\n\n      Raises :exc:`RuntimeError` if :meth:`write_eof` has been called.\n\n   .. method:: write_eof()\n      :async:\n\n      A :ref:`coroutine<coroutine>` *may* be called as a mark of the\n      *HTTP response* processing finish.\n\n      *Internal machinery* will call this method at the end of\n      the request processing if needed.\n\n      After :meth:`write_eof` call any manipulations with the *response*\n      object are forbidden.\n\n\n.. class:: Response(*, body=None, status=200, reason=None, text=None, \\\n                    headers=None, content_type=None, charset=None, \\\n                    zlib_executor_size=sentinel, zlib_executor=None)\n\n   The most usable response class, inherited from :class:`StreamResponse`.\n\n   Accepts *body* argument for setting the *HTTP response BODY*.\n\n   The actual :attr:`body` sending happens in overridden\n   :meth:`~StreamResponse.write_eof`.\n\n   :param bytes body: response's BODY\n\n   :param int status: HTTP status code, 200 OK by default.\n\n   :param collections.abc.Mapping headers: HTTP headers that should be added to\n                           response's ones.\n\n   :param str text: response's BODY\n\n   :param str content_type: response's content type. ``'text/plain'``\n                       if *text* is passed also,\n                       ``'application/octet-stream'`` otherwise.\n\n   :param str charset: response's charset. ``'utf-8'`` if *text* is\n                       passed also, ``None`` otherwise.\n\n   :param int zlib_executor_size: length in bytes which will trigger zlib compression\n                            of body to happen in an executor\n\n      .. versionadded:: 3.5\n\n   :param int zlib_executor: executor to use for zlib compression\n\n      .. versionadded:: 3.5\n\n\n   .. attribute:: body\n\n      Read-write attribute for storing response's content aka BODY,\n      :class:`bytes`.\n\n      Assigning :class:`str` to :attr:`body` will make the :attr:`body`\n      type of :class:`aiohttp.payload.StringPayload`, which tries to encode\n      the given data based on *Content-Type* HTTP header, while defaulting\n      to ``UTF-8``.\n\n   .. attribute:: text\n\n      Read-write attribute for storing response's\n      :attr:`~aiohttp.StreamResponse.body`, represented as :class:`str`.\n\n\n.. class:: FileResponse(*, path, chunk_size=256*1024, status=200, reason=None, headers=None)\n\n   The response class used to send files, inherited from :class:`StreamResponse`.\n\n   Supports the ``Content-Range`` and ``If-Range`` HTTP Headers in requests.\n\n   The actual :attr:`body` sending happens in overridden :meth:`~StreamResponse.prepare`.\n\n   :param path: Path to file. Accepts both :class:`str` and :class:`pathlib.Path`.\n   :param int chunk_size: Chunk size in bytes which will be passed into\n                          :meth:`io.RawIOBase.read` in the event that the\n                          ``sendfile`` system call is not supported.\n\n   :param int status: HTTP status code, ``200`` by default.\n\n   :param str reason: HTTP reason. If param is ``None`` reason will be\n                      calculated basing on *status*\n                      parameter. Otherwise pass :class:`str` with\n                      arbitrary *status* explanation..\n\n   :param collections.abc.Mapping headers: HTTP headers that should be added to\n                           response's ones. The ``Content-Type`` response header\n                           will be overridden if provided.\n\n\n.. class:: WebSocketResponse(*, timeout=10.0, receive_timeout=None, \\\n                             autoclose=True, autoping=True, heartbeat=None, \\\n                             protocols=(), compress=True, max_msg_size=4194304, \\\n                             writer_limit=65536)\n\n   Class for handling server-side websockets, inherited from\n   :class:`StreamResponse`.\n\n   After starting (by :meth:`prepare` call) the response you\n   cannot use :meth:`~StreamResponse.write` method but should to\n   communicate with websocket client by :meth:`send_str`,\n   :meth:`receive` and others.\n\n   To enable back-pressure from slow websocket clients treat methods\n   :meth:`ping`, :meth:`pong`, :meth:`send_str`,\n   :meth:`send_bytes`, :meth:`send_json`, :meth:`send_frame` as coroutines.\n   By default write buffer size is set to 64k.\n\n   :param bool autoping: Automatically send\n                         :const:`~aiohttp.WSMsgType.PONG` on\n                         :const:`~aiohttp.WSMsgType.PING`\n                         message from client, and handle\n                         :const:`~aiohttp.WSMsgType.PONG`\n                         responses from client.\n                         Note that server does not send\n                         :const:`~aiohttp.WSMsgType.PING`\n                         requests, you need to do this explicitly\n                         using :meth:`ping` method.\n\n   :param float heartbeat: Send `ping` message every `heartbeat`\n                           seconds and wait `pong` response, close\n                           connection if `pong` response is not\n                           received. The timer is reset on any data reception.\n\n   :param float receive_timeout: Timeout value for `receive`\n                                 operations.  Default value is None\n                                 (no timeout for receive operation)\n\n   :param bool compress: Enable per-message deflate extension support.\n                          False for disabled, default value is True.\n\n   :param int max_msg_size: maximum size of read websocket message, 4\n                            MB by default. To disable the size limit use ``0``.\n\n      .. versionadded:: 3.3\n\n   :param bool autoclose: Close connection when the client sends\n                           a :const:`~aiohttp.WSMsgType.CLOSE` message,\n                           ``True`` by default. If set to ``False``,\n                           the connection is not closed and the\n                           caller is responsible for calling\n                           ``request.transport.close()`` to avoid\n                           leaking resources.\n\n   :param int writer_limit: maximum size of write buffer, 64 KB by default.\n                            Once the buffer is full, the websocket will pause\n                            to drain the buffer.\n\n      .. versionadded:: 3.11\n\n   The class supports ``async for`` statement for iterating over\n   incoming messages::\n\n      ws = web.WebSocketResponse()\n      await ws.prepare(request)\n\n          async for msg in ws:\n              print(msg.data)\n\n\n   .. method:: prepare(request)\n      :async:\n\n      Starts websocket. After the call you can use websocket methods.\n\n      :param aiohttp.web.Request request: HTTP request object, that the\n                                          response answers.\n\n\n      :raises HTTPException: if websocket handshake has failed.\n\n   .. method:: can_prepare(request)\n\n      Performs checks for *request* data to figure out if websocket\n      can be started on the request.\n\n      If :meth:`can_prepare` call is success then :meth:`prepare` will\n      success too.\n\n      :param aiohttp.web.Request request: HTTP request object, that the\n                                          response answers.\n\n      :return: :class:`WebSocketReady` instance.\n\n               :attr:`WebSocketReady.ok` is\n               ``True`` on success, :attr:`WebSocketReady.protocol` is\n               websocket subprotocol which is passed by client and\n               accepted by server (one of *protocols* sequence from\n               :class:`WebSocketResponse` ctor).\n               :attr:`WebSocketReady.protocol` may be ``None`` if\n               client and server subprotocols are not overlapping.\n\n      .. note:: The method never raises exception.\n\n   .. attribute:: closed\n\n      Read-only property, ``True`` if connection has been closed or in process\n      of closing.\n      :const:`~aiohttp.WSMsgType.CLOSE` message has been received from peer.\n\n   .. attribute:: close_code\n\n      Read-only property, close code from peer. It is set to ``None`` on\n      opened connection.\n\n   .. attribute:: ws_protocol\n\n      Websocket *subprotocol* chosen after :meth:`start` call.\n\n      May be ``None`` if server and client protocols are\n      not overlapping.\n\n   .. method:: get_extra_info(name, default=None)\n\n      Reads optional extra information from the writer's transport.\n      If no value associated with ``name`` is found, ``default`` is returned.\n\n      See :meth:`asyncio.BaseTransport.get_extra_info`\n\n      :param str name: The key to look up in the transport extra information.\n\n      :param default: Default value to be used when no value for ``name`` is\n                      found (default is ``None``).\n\n   .. method:: exception()\n\n      Returns last occurred exception or None.\n\n   .. method:: ping(message=b'')\n      :async:\n\n      Send :const:`~aiohttp.WSMsgType.PING` to peer.\n\n      :param message: optional payload of *ping* message,\n                      :class:`str` (converted to *UTF-8* encoded bytes)\n                      or :class:`bytes`.\n\n      :raise RuntimeError: if connections is not started or closing.\n\n      .. versionchanged:: 3.0\n\n         The method is converted into :term:`coroutine`\n\n   .. method:: pong(message=b'')\n      :async:\n\n      Send *unsolicited* :const:`~aiohttp.WSMsgType.PONG` to peer.\n\n      :param message: optional payload of *pong* message,\n                      :class:`str` (converted to *UTF-8* encoded bytes)\n                      or :class:`bytes`.\n\n      :raise RuntimeError: if connections is not started or closing.\n\n      .. versionchanged:: 3.0\n\n         The method is converted into :term:`coroutine`\n\n   .. method:: send_str(data, compress=None)\n      :async:\n\n      Send *data* to peer as :const:`~aiohttp.WSMsgType.TEXT` message.\n\n      :param str data: data to send.\n\n      :param int compress: sets specific level of compression for\n                           single message,\n                           ``None`` for not overriding per-socket setting.\n\n      :raise RuntimeError: if connection is not started or closing\n\n      :raise TypeError: if data is not :class:`str`\n\n      .. versionchanged:: 3.0\n\n         The method is converted into :term:`coroutine`,\n         *compress* parameter added.\n\n   .. method:: send_bytes(data, compress=None)\n      :async:\n\n      Send *data* to peer as :const:`~aiohttp.WSMsgType.BINARY` message.\n\n      :param data: data to send.\n\n      :param int compress: sets specific level of compression for\n                           single message,\n                           ``None`` for not overriding per-socket setting.\n\n      :raise RuntimeError: if connection is not started or closing\n\n      :raise TypeError: if data is not :class:`bytes`,\n                        :class:`bytearray` or :class:`memoryview`.\n\n      .. versionchanged:: 3.0\n\n         The method is converted into :term:`coroutine`,\n         *compress* parameter added.\n\n   .. method:: send_json(data, compress=None, *, dumps=json.dumps)\n      :async:\n\n      Send *data* to peer as JSON string.\n\n      :param data: data to send.\n\n      :param int compress: sets specific level of compression for\n                           single message,\n                           ``None`` for not overriding per-socket setting.\n\n      :param collections.abc.Callable dumps: any :term:`callable` that accepts an object and\n                             returns a JSON string\n                             (:func:`json.dumps` by default).\n\n      :raise RuntimeError: if connection is not started or closing\n\n      :raise ValueError: if data is not serializable object\n\n      :raise TypeError: if value returned by ``dumps`` param is not :class:`str`\n\n      .. versionchanged:: 3.0\n\n         The method is converted into :term:`coroutine`,\n         *compress* parameter added.\n\n   .. method:: send_frame(message, opcode, compress=None)\n      :async:\n\n      Send a :const:`~aiohttp.WSMsgType` message *message* to peer.\n\n      This method is low-level and should be used with caution as it\n      only accepts bytes which must conform to the correct message type\n      for *message*.\n\n      It is recommended to use the :meth:`send_str`, :meth:`send_bytes`\n      or :meth:`send_json` methods instead of this method.\n\n      The primary use case for this method is to send bytes that are\n      have already been encoded without having to decode and\n      re-encode them.\n\n      :param bytes message: message to send.\n\n      :param ~aiohttp.WSMsgType opcode: opcode of the message.\n\n      :param int compress: sets specific level of compression for\n                           single message,\n                           ``None`` for not overriding per-socket setting.\n\n      .. versionadded:: 3.11\n\n   .. method:: close(*, code=WSCloseCode.OK, message=b'', drain=True)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that initiates closing\n      handshake by sending :const:`~aiohttp.WSMsgType.CLOSE` message.\n\n      It is safe to call `close()` from different task.\n\n      :param int code: closing code. See also :class:`~aiohttp.WSCloseCode`.\n\n      :param message: optional payload of *close* message,\n                      :class:`str` (converted to *UTF-8* encoded bytes)\n                      or :class:`bytes`.\n\n      :param bool drain: drain outgoing buffer before closing connection.\n\n      :raise RuntimeError: if connection is not started\n\n   .. method:: receive(timeout=None)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that waits upcoming *data*\n      message from peer and returns it.\n\n      The coroutine implicitly handles\n      :const:`~aiohttp.WSMsgType.PING`,\n      :const:`~aiohttp.WSMsgType.PONG` and\n      :const:`~aiohttp.WSMsgType.CLOSE` without returning the\n      message.\n\n      It process *ping-pong game* and performs *closing handshake* internally.\n\n      .. note::\n\n         Can only be called by the request handling task.\n\n      :param timeout: timeout for `receive` operation.\n\n         timeout value overrides response`s receive_timeout attribute.\n\n      :return: :class:`~aiohttp.WSMessage`\n\n      :raise RuntimeError: if connection is not started\n\n   .. method:: receive_str(*, timeout=None)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that calls :meth:`receive` but\n      also asserts the message type is :const:`~aiohttp.WSMsgType.TEXT`.\n\n      .. note::\n\n         Can only be called by the request handling task.\n\n      :param timeout: timeout for `receive` operation.\n\n         timeout value overrides response`s receive_timeout attribute.\n\n      :return str: peer's message content.\n\n      :raise TypeError: if message is :const:`~aiohttp.WSMsgType.BINARY`.\n\n   .. method:: receive_bytes(*, timeout=None)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that calls :meth:`receive` but\n      also asserts the message type is\n      :const:`~aiohttp.WSMsgType.BINARY`.\n\n      .. note::\n\n         Can only be called by the request handling task.\n\n      :param timeout: timeout for `receive` operation.\n\n         timeout value overrides response`s receive_timeout attribute.\n\n      :return bytes: peer's message content.\n\n      :raise TypeError: if message is :const:`~aiohttp.WSMsgType.TEXT`.\n\n   .. method:: receive_json(*, loads=json.loads, timeout=None)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that calls :meth:`receive_str` and loads the\n      JSON string to a Python dict.\n\n      .. note::\n\n         Can only be called by the request handling task.\n\n      :param collections.abc.Callable loads: any :term:`callable` that accepts\n                              :class:`str` and returns :class:`dict`\n                              with parsed JSON (:func:`json.loads` by\n                              default).\n\n      :param timeout: timeout for `receive` operation.\n\n         timeout value overrides response`s receive_timeout attribute.\n\n      :return dict: loaded JSON content\n\n      :raise TypeError: if message is :const:`~aiohttp.WSMsgType.BINARY`.\n      :raise ValueError: if message is not valid JSON.\n\n\n.. seealso:: :ref:`WebSockets handling<aiohttp-web-websockets>`\n\n\n.. class:: WebSocketReady\n\n   A named tuple for returning result from\n   :meth:`WebSocketResponse.can_prepare`.\n\n   Has :class:`bool` check implemented, e.g.::\n\n       if not await ws.can_prepare(...):\n           cannot_start_websocket()\n\n   .. attribute:: ok\n\n      ``True`` if websocket connection can be established, ``False``\n      otherwise.\n\n\n   .. attribute:: protocol\n\n      :class:`str` represented selected websocket sub-protocol.\n\n   .. seealso:: :meth:`WebSocketResponse.can_prepare`\n\n\n.. function:: json_response([data], *, text=None, body=None, \\\n                            status=200, reason=None, headers=None, \\\n                            content_type='application/json', \\\n                            dumps=json.dumps)\n\nReturn :class:`Response` with predefined ``'application/json'``\ncontent type and *data* encoded by ``dumps`` parameter\n(:func:`json.dumps` by default).\n\n\n.. _aiohttp-web-app-and-router:\n\nApplication and Router\n----------------------\n\n\n.. class:: Application(*, logger=<default>, middlewares=(), \\\n                       handler_args=None, client_max_size=1024**2, \\\n                       debug=...)\n\n   Application is a synonym for web-server.\n\n   To get a fully working example, you have to make an *application*, register\n   supported urls in the *router* and pass it to :func:`aiohttp.web.run_app`\n   or :class:`aiohttp.web.AppRunner`.\n\n   *Application* contains a *router* instance and a list of callbacks that\n   will be called during application finishing.\n\n   This class is a :obj:`dict`-like object, so you can use it for\n   :ref:`sharing data<aiohttp-web-data-sharing>` globally by storing arbitrary\n   properties for later access from a :ref:`handler<aiohttp-web-handler>` via the\n   :attr:`Request.app` property::\n\n       app = Application()\n       database = AppKey(\"database\", AsyncEngine)\n       app[database] = await create_async_engine(db_url)\n\n       async def handler(request):\n           async with request.app[database].begin() as conn:\n               await conn.execute(\"DELETE * FROM table\")\n\n   Although it` is a :obj:`dict`-like object, it can't be duplicated like one\n   using :meth:`~aiohttp.web.Application.copy`.\n\n   The class inherits :class:`dict`.\n\n   :param logger: :class:`logging.Logger` instance for storing application logs.\n\n                  By default the value is ``logging.getLogger(\"aiohttp.web\")``\n\n   :param middlewares: :class:`list` of middleware factories, see\n                       :ref:`aiohttp-web-middlewares` for details.\n\n   :param handler_args: dict-like object that overrides keyword arguments of\n                        :class:`AppRunner` constructor.\n\n   :param client_max_size: client's maximum size in a request, in\n                           bytes.  If a POST request exceeds this\n                           value, it raises an\n                           `HTTPRequestEntityTooLarge` exception.\n\n   :param debug: Switches debug mode.\n\n      .. deprecated:: 3.5\n\n         The argument does nothing starting from 4.0,\n         use asyncio :ref:`asyncio-debug-mode` instead.\n\n\n   .. attribute:: router\n\n      Read-only property that returns *router instance*.\n\n   .. attribute:: logger\n\n      :class:`logging.Logger` instance for storing application logs.\n\n   .. attribute:: debug\n\n      Boolean value indicating whether the debug mode is turned on or off.\n\n      .. deprecated:: 3.5\n\n         Use asyncio :ref:`asyncio-debug-mode` instead.\n\n   .. attribute:: on_response_prepare\n\n      A :class:`~aiosignal.Signal` that is fired near the end\n      of :meth:`StreamResponse.prepare` with parameters *request* and\n      *response*. It can be used, for example, to add custom headers to each\n      response, or to modify the default headers computed by the application,\n      directly before sending the headers to the client.\n\n      Signal handlers should have the following signature::\n\n          async def on_prepare(request, response):\n              pass\n\n      .. note::\n\n         The headers are written immediately after these callbacks are run.\n         Therefore, if you modify the content of the response, you may need to\n         adjust the `Content-Length` header or similar to match. Aiohttp will\n         not make any updates to the headers from this point.\n\n   .. attribute:: on_startup\n\n      A :class:`~aiosignal.Signal` that is fired on application start-up.\n\n      Subscribers may use the signal to run background tasks in the event\n      loop along with the application's request handler just after the\n      application start-up.\n\n      Signal handlers should have the following signature::\n\n          async def on_startup(app):\n              pass\n\n      .. seealso:: :ref:`aiohttp-web-signals` and :ref:`aiohttp-web-cleanup-ctx`.\n\n   .. attribute:: on_shutdown\n\n      A :class:`~aiosignal.Signal` that is fired on application shutdown.\n\n      Subscribers may use the signal for gracefully closing long running\n      connections, e.g. websockets and data streaming.\n\n      Signal handlers should have the following signature::\n\n          async def on_shutdown(app):\n              pass\n\n      It's up to end user to figure out which :term:`web-handler`\\s\n      are still alive and how to finish them properly.\n\n      We suggest keeping a list of long running handlers in\n      :class:`Application` dictionary.\n\n      .. seealso:: :ref:`aiohttp-web-graceful-shutdown` and :attr:`on_cleanup`.\n\n   .. attribute:: on_cleanup\n\n      A :class:`~aiosignal.Signal` that is fired on application cleanup.\n\n      Subscribers may use the signal for gracefully closing\n      connections to database server etc.\n\n      Signal handlers should have the following signature::\n\n          async def on_cleanup(app):\n              pass\n\n      .. seealso:: :ref:`aiohttp-web-signals` and :attr:`on_shutdown`.\n\n   .. attribute:: cleanup_ctx\n\n      A list of *context generators* for *startup*/*cleanup* handling.\n\n      Signal handlers should have the following signature::\n\n          async def context(app):\n              # do startup stuff\n              yield\n              # do cleanup\n\n      .. versionadded:: 3.1\n\n      .. seealso:: :ref:`aiohttp-web-cleanup-ctx`.\n\n   .. method:: add_subapp(prefix, subapp)\n\n      Register nested sub-application under given path *prefix*.\n\n      In resolving process if request's path starts with *prefix* then\n      further resolving is passed to *subapp*.\n\n      :param str prefix: path's prefix for the resource.\n\n      :param Application subapp: nested application attached under *prefix*.\n\n      :returns: a :class:`PrefixedSubAppResource` instance.\n\n   .. method:: add_domain(domain, subapp)\n\n      Register nested sub-application that serves\n      the domain name or domain name mask.\n\n      In resolving process if request.headers['host']\n      matches the pattern *domain* then\n      further resolving is passed to *subapp*.\n\n      :param str domain: domain or mask of domain for the resource.\n\n      :param Application subapp: nested application.\n\n      :returns: a :class:`~aiohttp.web.MatchedSubAppResource` instance.\n\n   .. method:: add_routes(routes_table)\n\n      Register route definitions from *routes_table*.\n\n      The table is a :class:`list` of :class:`RouteDef` items or\n      :class:`RouteTableDef`.\n\n      :returns: :class:`list` of registered :class:`AbstractRoute` instances.\n\n      The method is a shortcut for\n      ``app.router.add_routes(routes_table)``, see also\n      :meth:`UrlDispatcher.add_routes`.\n\n      .. versionadded:: 3.1\n\n      .. versionchanged:: 3.7\n\n         Return value updated from ``None`` to :class:`list` of\n         :class:`AbstractRoute` instances.\n\n   .. method:: startup()\n      :async:\n\n      A :ref:`coroutine<coroutine>` that will be called along with the\n      application's request handler.\n\n      The purpose of the method is calling :attr:`on_startup` signal\n      handlers.\n\n   .. method:: shutdown()\n      :async:\n\n      A :ref:`coroutine<coroutine>` that should be called on\n      server stopping but before :meth:`cleanup`.\n\n      The purpose of the method is calling :attr:`on_shutdown` signal\n      handlers.\n\n   .. method:: cleanup()\n      :async:\n\n      A :ref:`coroutine<coroutine>` that should be called on\n      server stopping but after :meth:`shutdown`.\n\n      The purpose of the method is calling :attr:`on_cleanup` signal\n      handlers.\n\n   .. note::\n\n      Application object has :attr:`router` attribute but has no\n      ``add_route()`` method. The reason is: we want to support\n      different router implementations (even maybe not url-matching\n      based but traversal ones).\n\n      For sake of that fact we have very trivial ABC for\n      :class:`~aiohttp.abc.AbstractRouter`: it should have only\n      :meth:`aiohttp.abc.AbstractRouter.resolve` coroutine.\n\n      No methods for adding routes or route reversing (getting URL by\n      route name). All those are router implementation details (but,\n      sure, you need to deal with that methods after choosing the\n      router for your application).\n\n\n.. class:: AppKey(name, t)\n\n   This class should be used for the keys in :class:`Application`. They\n   provide a type-safe alternative to `str` keys when checking your code\n   with a type checker (e.g. mypy). They also avoid name clashes with keys\n   from different libraries etc.\n\n   :param name: A name to help with debugging. This should be the same as\n                the variable name (much like how :class:`typing.TypeVar`\n                is used).\n\n   :param t: The type that should be used for the value in the dict (e.g.\n             `str`, `Iterator[int]` etc.)\n\n.. class:: Server\n\n   A protocol factory compatible with\n   :meth:`~asyncio.AbstractEventLoop.create_server`.\n\n   The class is responsible for creating HTTP protocol\n   objects that can handle HTTP connections.\n\n   .. attribute:: connections\n\n      List of all currently opened connections.\n\n   .. attribute:: requests_count\n\n      Amount of processed requests.\n\n   .. method:: Server.shutdown(timeout)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that should be called to close all opened\n      connections.\n\n\n.. class:: UrlDispatcher()\n\n   For dispatching URLs to :ref:`handlers<aiohttp-web-handler>`\n   :mod:`aiohttp.web` uses *routers*, which is any object that implements\n   :class:`~aiohttp.abc.AbstractRouter` interface.\n\n   This class is a straightforward url-matching router, implementing\n   :class:`collections.abc.Mapping` for access to *named routes*.\n\n   :class:`Application` uses this class as\n   :meth:`~aiohttp.web.Application.router` by default.\n\n   Before running an :class:`Application` you should fill *route\n   table* first by calling :meth:`add_route` and :meth:`add_static`.\n\n   :ref:`Handler<aiohttp-web-handler>` lookup is performed by iterating on\n   added *routes* in FIFO order. The first matching *route* will be used\n   to call the corresponding *handler*.\n\n   If during route creation you specify *name* parameter the result is a\n   *named route*.\n\n   A *named route* can be retrieved by a ``app.router[name]`` call, checking for\n   existence can be done with ``name in app.router`` etc.\n\n   .. seealso:: :ref:`Route classes <aiohttp-web-route>`\n\n   .. method:: add_resource(path, *, name=None)\n\n      Append a :term:`resource` to the end of route table.\n\n      *path* may be either *constant* string like ``'/a/b/c'`` or\n      *variable rule* like ``'/a/{var}'`` (see\n      :ref:`handling variable paths <aiohttp-web-variable-handler>`)\n\n      :param str path: resource path spec.\n\n      :param str name: optional resource name.\n\n      :return: created resource instance (:class:`PlainResource` or\n               :class:`DynamicResource`).\n\n   .. method:: add_route(method, path, handler, *, \\\n                         name=None, expect_handler=None)\n\n      Append :ref:`handler<aiohttp-web-handler>` to the end of route table.\n\n      *path* may be either *constant* string like ``'/a/b/c'`` or\n       *variable rule* like ``'/a/{var}'`` (see\n       :ref:`handling variable paths <aiohttp-web-variable-handler>`)\n\n      Pay attention please: *handler* must be a coroutine.\n\n      :param str method: HTTP method for route. Should be one of\n                         ``'GET'``, ``'POST'``, ``'PUT'``,\n                         ``'DELETE'``, ``'PATCH'``, ``'HEAD'``,\n                         ``'OPTIONS'`` or ``'*'`` for any method.\n\n                         The parameter is case-insensitive, e.g. you\n                         can push ``'get'`` as well as ``'GET'``.\n\n      :param str path: route path. Should be started with slash (``'/'``).\n\n      :param collections.abc.Callable handler: route handler.\n\n      :param str name: optional route name.\n\n      :param collections.abc.Coroutine expect_handler: optional *expect* header handler.\n\n      :returns: new :class:`AbstractRoute` instance.\n\n   .. method:: add_routes(routes_table)\n\n      Register route definitions from *routes_table*.\n\n      The table is a :class:`list` of :class:`RouteDef` items or\n      :class:`RouteTableDef`.\n\n      :returns: :class:`list` of registered :class:`AbstractRoute` instances.\n\n      .. versionadded:: 2.3\n\n      .. versionchanged:: 3.7\n\n         Return value updated from ``None`` to :class:`list` of\n         :class:`AbstractRoute` instances.\n\n   .. method:: add_get(path, handler, *, name=None, allow_head=True, **kwargs)\n\n      Shortcut for adding a GET handler. Calls the :meth:`add_route` with \\\n      ``method`` equals to ``'GET'``.\n\n      If *allow_head* is ``True`` (default) the route for method HEAD\n      is added with the same handler as for GET.\n\n      If *name* is provided the name for HEAD route is suffixed with\n      ``'-head'``. For example ``router.add_get(path, handler,\n      name='route')`` call adds two routes: first for GET with name\n      ``'route'`` and second for HEAD with name ``'route-head'``.\n\n   .. method:: add_post(path, handler, **kwargs)\n\n      Shortcut for adding a POST handler. Calls the :meth:`add_route` with \\\n\n\n      ``method`` equals to ``'POST'``.\n\n   .. method:: add_head(path, handler, **kwargs)\n\n      Shortcut for adding a HEAD handler. Calls the :meth:`add_route` with \\\n      ``method`` equals to ``'HEAD'``.\n\n   .. method:: add_put(path, handler, **kwargs)\n\n      Shortcut for adding a PUT handler. Calls the :meth:`add_route` with \\\n      ``method`` equals to ``'PUT'``.\n\n   .. method:: add_patch(path, handler, **kwargs)\n\n      Shortcut for adding a PATCH handler. Calls the :meth:`add_route` with \\\n      ``method`` equals to ``'PATCH'``.\n\n   .. method:: add_delete(path, handler, **kwargs)\n\n      Shortcut for adding a DELETE handler. Calls the :meth:`add_route` with \\\n      ``method`` equals to ``'DELETE'``.\n\n   .. method:: add_view(path, handler, **kwargs)\n\n      Shortcut for adding a class-based view handler. Calls the \\\n      :meth:`add_route` with ``method`` equals to ``'*'``.\n\n      .. versionadded:: 3.0\n\n   .. method:: add_static(prefix, path, *, name=None, expect_handler=None, \\\n                          chunk_size=256*1024, \\\n                          response_factory=StreamResponse, \\\n                          show_index=False, \\\n                          follow_symlinks=False, \\\n                          append_version=False)\n\n      Adds a router and a handler for returning static files.\n\n      Useful for serving static content like images, javascript and css files.\n\n      On platforms that support it, the handler will transfer files more\n      efficiently using the ``sendfile`` system call.\n\n      In some situations it might be necessary to avoid using the ``sendfile``\n      system call even if the platform supports it. This can be accomplished by\n      by setting environment variable ``AIOHTTP_NOSENDFILE=1``.\n\n      If a Brotli or gzip compressed version of the static content exists at\n      the requested path with the ``.br`` or ``.gz`` extension, it will be used\n      for the response. Brotli will be preferred over gzip if both files exist.\n\n      .. warning::\n\n         Use :meth:`add_static` for development only. In production,\n         static content should be processed by web servers like *nginx*\n         or *apache*. Such web servers will be able to provide significantly\n         better performance and security for static assets. Several past security\n         vulnerabilities in aiohttp only affected applications using\n         :meth:`add_static`.\n\n      :param str prefix: URL path prefix for handled static files\n\n      :param path: path to the folder in file system that contains\n                   handled static files, :class:`str` or :class:`pathlib.Path`.\n\n      :param str name: optional route name.\n\n      :param collections.abc.Coroutine expect_handler: optional *expect* header handler.\n\n      :param int chunk_size: size of single chunk for file\n                             downloading, 256Kb by default.\n\n                             Increasing *chunk_size* parameter to,\n                             say, 1Mb may increase file downloading\n                             speed but consumes more memory.\n\n      :param bool show_index: flag for allowing to show indexes of a directory,\n                              by default it's not allowed and HTTP/403 will\n                              be returned on directory access.\n\n      :param bool follow_symlinks: flag for allowing to follow symlinks that lead\n                              outside the static root directory, by default it's not allowed and\n                              HTTP/404 will be returned on access.  Enabling ``follow_symlinks``\n                              can be a security risk, and may lead to a directory transversal attack.\n                              You do NOT need this option to follow symlinks which point to somewhere\n                              else within the static directory, this option is only used to break out\n                              of the security sandbox. Enabling this option is highly discouraged,\n                              and only expected to be used for edge cases in a local development\n                              setting where remote users do not have access to the server.\n\n      :param bool append_version: flag for adding file version (hash)\n                              to the url query string, this value will\n                              be used as default when you call to\n                              :meth:`~aiohttp.web.AbstractRoute.url` and\n                              :meth:`~aiohttp.web.AbstractRoute.url_for` methods.\n\n\n      :returns: new :class:`~aiohttp.web.AbstractRoute` instance.\n\n   .. method:: resolve(request)\n      :async:\n\n      A :ref:`coroutine<coroutine>` that returns\n      :class:`~aiohttp.abc.AbstractMatchInfo` for *request*.\n\n      The method never raises exception, but returns\n      :class:`~aiohttp.abc.AbstractMatchInfo` instance with:\n\n      1. :attr:`~aiohttp.abc.AbstractMatchInfo.http_exception` assigned to\n         :exc:`HTTPException` instance.\n      2. :meth:`~aiohttp.abc.AbstractMatchInfo.handler` which raises\n         :exc:`HTTPNotFound` or :exc:`HTTPMethodNotAllowed` on handler's\n         execution if there is no registered route for *request*.\n\n         *Middlewares* can process that exceptions to render\n         pretty-looking error page for example.\n\n      Used by internal machinery, end user unlikely need to call the method.\n\n      .. note:: The method uses :attr:`aiohttp.web.BaseRequest.raw_path` for pattern\n         matching against registered routes.\n\n   .. method:: resources()\n\n      The method returns a *view* for *all* registered resources.\n\n      The view is an object that allows to:\n\n      1. Get size of the router table::\n\n           len(app.router.resources())\n\n      2. Iterate over registered resources::\n\n           for resource in app.router.resources():\n               print(resource)\n\n      3. Make a check if the resources is registered in the router table::\n\n           route in app.router.resources()\n\n   .. method:: routes()\n\n      The method returns a *view* for *all* registered routes.\n\n   .. method:: named_resources()\n\n      Returns a :obj:`dict`-like :class:`types.MappingProxyType` *view* over\n      *all* named **resources**.\n\n      The view maps every named resource's **name** to the\n      :class:`AbstractResource` instance. It supports the usual\n      :obj:`dict`-like operations, except for any mutable operations\n      (i.e. it's **read-only**)::\n\n          len(app.router.named_resources())\n\n          for name, resource in app.router.named_resources().items():\n              print(name, resource)\n\n          \"name\" in app.router.named_resources()\n\n          app.router.named_resources()[\"name\"]\n\n\n.. _aiohttp-web-resource:\n\nResource\n^^^^^^^^\n\nDefault router :class:`UrlDispatcher` operates with :term:`resource`\\s.\n\nResource is an item in *routing table* which has a *path*, an optional\nunique *name* and at least one :term:`route`.\n\n:term:`web-handler` lookup is performed in the following way:\n\n1. The router splits the URL and checks the index from longest to shortest.\n   For example, '/one/two/three' will first check the index for\n   '/one/two/three', then '/one/two' and finally '/'.\n2. If the URL part is found in the index, the list of routes for\n   that URL part is iterated over. If a route matches to requested HTTP\n   method (or ``'*'`` wildcard) the route's handler is used as the chosen\n   :term:`web-handler`. The lookup is finished.\n3. If the route is not found in the index, the router tries to find\n   the route in the list of :class:`~aiohttp.web.MatchedSubAppResource`,\n   (current only created from :meth:`~aiohttp.web.Application.add_domain`),\n   and will iterate over the list of\n   :class:`~aiohttp.web.MatchedSubAppResource` in a linear fashion\n   until a match is found.\n4. If no *resource* / *route* pair was found, the *router*\n   returns the special :class:`~aiohttp.abc.AbstractMatchInfo`\n   instance with :attr:`aiohttp.abc.AbstractMatchInfo.http_exception` is not ``None``\n   but :exc:`HTTPException` with  either *HTTP 404 Not Found* or\n   *HTTP 405 Method Not Allowed* status code.\n   Registered :meth:`~aiohttp.abc.AbstractMatchInfo.handler` raises this exception on call.\n\nFixed paths are preferred over variable paths. For example,\nif you have two routes ``/a/b`` and ``/a/{name}``, then the first\nroute will always be preferred over the second one.\n\nIf there are multiple dynamic paths with the same fixed prefix,\nthey will be resolved in order of registration.\n\nFor example, if you have two dynamic routes that are prefixed\nwith the fixed ``/users`` path such as ``/users/{x}/{y}/z`` and\n``/users/{x}/y/z``, the first one will be preferred over the\nsecond one.\n\nUser should never instantiate resource classes but give it by\n:meth:`UrlDispatcher.add_resource` call.\n\nAfter that he may add a :term:`route` by calling :meth:`Resource.add_route`.\n\n:meth:`UrlDispatcher.add_route` is just shortcut for::\n\n   router.add_resource(path).add_route(method, handler)\n\nResource with a *name* is called *named resource*.\nThe main purpose of *named resource* is constructing URL by route name for\npassing it into *template engine* for example::\n\n   url = app.router['resource_name'].url_for().with_query({'a': 1, 'b': 2})\n\nResource classes hierarchy::\n\n   AbstractResource\n     Resource\n       PlainResource\n       DynamicResource\n     PrefixResource\n       StaticResource\n       PrefixedSubAppResource\n          MatchedSubAppResource\n\n\n.. class:: AbstractResource\n\n   A base class for all resources.\n\n   Inherited from :class:`collections.abc.Sized` and\n   :class:`collections.abc.Iterable`.\n\n   ``len(resource)`` returns amount of :term:`route`\\s belongs to the resource,\n   ``for route in resource`` allows to iterate over these routes.\n\n   .. attribute:: name\n\n      Read-only *name* of resource or ``None``.\n\n   .. attribute:: canonical\n\n      Read-only *canonical path* associate with the resource. For example\n      ``/path/to`` or ``/path/{to}``\n\n      .. versionadded:: 3.3\n\n   .. method:: resolve(request)\n      :async:\n\n      Resolve resource by finding appropriate :term:`web-handler` for\n      ``(method, path)`` combination.\n\n      :return: (*match_info*, *allowed_methods*) pair.\n\n               *allowed_methods* is a :class:`set` or HTTP methods accepted by\n               resource.\n\n               *match_info* is either :class:`UrlMappingMatchInfo` if\n               request is resolved or ``None`` if no :term:`route` is\n               found.\n\n   .. method:: get_info()\n\n      A resource description, e.g. ``{'path': '/path/to'}`` or\n      ``{'formatter': '/path/{to}', 'pattern':\n      re.compile(r'^/path/(?P<to>[a-zA-Z][_a-zA-Z0-9]+)$``\n\n   .. method:: url_for(*args, **kwargs)\n\n      Construct an URL for route with additional params.\n\n      *args* and **kwargs** depend on a parameters list accepted by\n      inherited resource class.\n\n      :return: :class:`~yarl.URL` -- resulting URL instance.\n\n\n.. class:: Resource\n\n   A base class for new-style resources, inherits :class:`AbstractResource`.\n\n\n   .. method:: add_route(method, handler, *, expect_handler=None)\n\n      Add a :term:`web-handler` to resource.\n\n      :param str method: HTTP method for route. Should be one of\n                         ``'GET'``, ``'POST'``, ``'PUT'``,\n                         ``'DELETE'``, ``'PATCH'``, ``'HEAD'``,\n                         ``'OPTIONS'`` or ``'*'`` for any method.\n\n                         The parameter is case-insensitive, e.g. you\n                         can push ``'get'`` as well as ``'GET'``.\n\n                         The method should be unique for resource.\n\n      :param collections.abc.Callable handler: route handler.\n\n      :param collections.abc.Coroutine expect_handler: optional *expect* header handler.\n\n      :returns: new :class:`ResourceRoute` instance.\n\n\n.. class:: PlainResource\n\n   A resource, inherited from :class:`Resource`.\n\n   The class corresponds to resources with plain-text matching,\n   ``'/path/to'`` for example.\n\n   .. attribute:: canonical\n\n      Read-only *canonical path* associate with the resource. Returns the path\n      used to create the PlainResource. For example ``/path/to``\n\n      .. versionadded:: 3.3\n\n   .. method:: url_for()\n\n      Returns a :class:`~yarl.URL` for the resource.\n\n\n.. class:: DynamicResource\n\n   A resource, inherited from :class:`Resource`.\n\n   The class corresponds to resources with\n   :ref:`variable <aiohttp-web-variable-handler>` matching,\n   e.g. ``'/path/{to}/{param}'`` etc.\n\n   .. attribute:: canonical\n\n      Read-only *canonical path* associate with the resource. Returns the\n      formatter obtained from the path used to create the DynamicResource.\n      For example, from a path ``/get/{num:^\\d+}``, it returns ``/get/{num}``\n\n      .. versionadded:: 3.3\n\n   .. method:: url_for(**params)\n\n      Returns a :class:`~yarl.URL` for the resource.\n\n      :param params: -- a variable substitutions for dynamic resource.\n\n         E.g. for ``'/path/{to}/{param}'`` pattern the method should\n         be called as ``resource.url_for(to='val1', param='val2')``\n\n\n.. class:: StaticResource\n\n   A resource, inherited from :class:`Resource`.\n\n   The class corresponds to resources for :ref:`static file serving\n   <aiohttp-web-static-file-handling>`.\n\n   .. attribute:: canonical\n\n      Read-only *canonical path* associate with the resource. Returns the prefix\n      used to create the StaticResource. For example ``/prefix``\n\n      .. versionadded:: 3.3\n\n   .. method:: url_for(filename, append_version=None)\n\n      Returns a :class:`~yarl.URL` for file path under resource prefix.\n\n      :param filename: -- a file name substitution for static file handler.\n\n         Accepts both :class:`str` and :class:`pathlib.Path`.\n\n         E.g. an URL for ``'/prefix/dir/file.txt'`` should\n         be generated as ``resource.url_for(filename='dir/file.txt')``\n\n      :param bool append_version: -- a flag for adding file version\n                                  (hash) to the url query string for\n                                  cache boosting\n\n         By default has value from a constructor (``False`` by default)\n         When set to ``True`` - ``v=FILE_HASH`` query string param will be added\n         When set to ``False`` has no impact\n\n         if file not found has no impact\n\n\n.. class:: PrefixedSubAppResource\n\n   A resource for serving nested applications. The class instance is\n   returned by :class:`~aiohttp.web.Application.add_subapp` call.\n\n   .. attribute:: canonical\n\n      Read-only *canonical path* associate with the resource. Returns the\n      prefix used to create the PrefixedSubAppResource.\n      For example ``/prefix``\n\n      .. versionadded:: 3.3\n\n   .. method:: url_for(**kwargs)\n\n      The call is not allowed, it raises :exc:`RuntimeError`.\n\n\n.. _aiohttp-web-route:\n\nRoute\n^^^^^\n\nRoute has *HTTP method* (wildcard ``'*'`` is an option),\n:term:`web-handler` and optional *expect handler*.\n\nEvery route belong to some resource.\n\nRoute classes hierarchy::\n\n   AbstractRoute\n     ResourceRoute\n     SystemRoute\n\n:class:`ResourceRoute` is the route used for resources,\n:class:`SystemRoute` serves URL resolving errors like *404 Not Found*\nand *405 Method Not Allowed*.\n\n.. class:: AbstractRoute\n\n   Base class for routes served by :class:`UrlDispatcher`.\n\n   .. attribute:: method\n\n      HTTP method handled by the route, e.g. *GET*, *POST* etc.\n\n   .. attribute:: handler\n\n      :ref:`handler<aiohttp-web-handler>` that processes the route.\n\n   .. attribute:: name\n\n      Name of the route, always equals to name of resource which owns the route.\n\n   .. attribute:: resource\n\n      Resource instance which holds the route, ``None`` for\n      :class:`SystemRoute`.\n\n   .. method:: url_for(*args, **kwargs)\n\n      Abstract method for constructing url handled by the route.\n\n      Actually it's a shortcut for ``route.resource.url_for(...)``.\n\n   .. method:: handle_expect_header(request)\n      :async:\n\n      ``100-continue`` handler.\n\n.. class:: ResourceRoute\n\n   The route class for handling different HTTP methods for :class:`Resource`.\n\n\n.. class:: SystemRoute\n\n   The route class for handling URL resolution errors like like *404 Not Found*\n   and *405 Method Not Allowed*.\n\n   .. attribute:: status\n\n      HTTP status code\n\n   .. attribute:: reason\n\n      HTTP status reason\n\n\n.. _aiohttp-web-route-def:\n\n\nRouteDef and StaticDef\n^^^^^^^^^^^^^^^^^^^^^^\n\nRoute definition, a description for not registered yet route.\n\nCould be used for filing route table by providing a list of route\ndefinitions (Django style).\n\nThe definition is created by functions like :func:`get` or\n:func:`post`, list of definitions could be added to router by\n:meth:`UrlDispatcher.add_routes` call::\n\n   from aiohttp import web\n\n   async def handle_get(request):\n       ...\n\n\n   async def handle_post(request):\n       ...\n\n   app.router.add_routes([web.get('/get', handle_get),\n                          web.post('/post', handle_post),\n\n.. class:: AbstractRouteDef\n\n   A base class for route definitions.\n\n   Inherited from :class:`abc.ABC`.\n\n   .. versionadded:: 3.1\n\n   .. method:: register(router)\n\n      Register itself into :class:`UrlDispatcher`.\n\n      Abstract method, should be overridden by subclasses.\n\n      :returns: :class:`list` of registered :class:`AbstractRoute` objects.\n\n      .. versionchanged:: 3.7\n\n         Return value updated from ``None`` to :class:`list` of\n         :class:`AbstractRoute` instances.\n\n\n.. class:: RouteDef\n\n   A definition of not registered yet route.\n\n   Implements :class:`AbstractRouteDef`.\n\n   .. versionadded:: 2.3\n\n   .. versionchanged:: 3.1\n\n      The class implements :class:`AbstractRouteDef` interface.\n\n   .. attribute:: method\n\n      HTTP method (``GET``, ``POST`` etc.)  (:class:`str`).\n\n   .. attribute:: path\n\n      Path to resource, e.g. ``/path/to``. Could contain ``{}``\n      brackets for :ref:`variable resources\n      <aiohttp-web-variable-handler>` (:class:`str`).\n\n   .. attribute:: handler\n\n      An async function to handle HTTP request.\n\n   .. attribute:: kwargs\n\n      A :class:`dict` of additional arguments.\n\n\n.. class:: StaticDef\n\n   A definition of static file resource.\n\n   Implements :class:`AbstractRouteDef`.\n\n   .. versionadded:: 3.1\n\n   .. attribute:: prefix\n\n      A prefix used for static file handling, e.g. ``/static``.\n\n   .. attribute:: path\n\n      File system directory to serve, :class:`str` or\n      :class:`pathlib.Path`\n      (e.g. ``'/home/web-service/path/to/static'``.\n\n   .. attribute:: kwargs\n\n      A :class:`dict` of additional arguments, see\n      :meth:`UrlDispatcher.add_static` for a list of supported\n      options.\n\n\n.. function:: get(path, handler, *, name=None, allow_head=True, \\\n              expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``GET`` requests. See\n   :meth:`UrlDispatcher.add_get` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: post(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``POST`` requests. See\n   :meth:`UrlDispatcher.add_post` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: head(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``HEAD`` requests. See\n   :meth:`UrlDispatcher.add_head` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: put(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``PUT`` requests. See\n   :meth:`UrlDispatcher.add_put` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: patch(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``PATCH`` requests. See\n   :meth:`UrlDispatcher.add_patch` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: delete(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``DELETE`` requests. See\n   :meth:`UrlDispatcher.add_delete` for information about parameters.\n\n   .. versionadded:: 2.3\n\n.. function:: view(path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing ``ANY`` requests. See\n   :meth:`UrlDispatcher.add_view` for information about parameters.\n\n   .. versionadded:: 3.0\n\n.. function:: static(prefix, path, *, name=None, expect_handler=None, \\\n                     chunk_size=256*1024, \\\n                     show_index=False, follow_symlinks=False, \\\n                     append_version=False)\n\n   Return :class:`StaticDef` for processing static files.\n\n   See :meth:`UrlDispatcher.add_static` for information\n   about supported parameters.\n\n   .. versionadded:: 3.1\n\n.. function:: route(method, path, handler, *, name=None, expect_handler=None)\n\n   Return :class:`RouteDef` for processing requests that decided by\n   ``method``. See :meth:`UrlDispatcher.add_route` for information\n   about parameters.\n\n   .. versionadded:: 2.3\n\n\n.. _aiohttp-web-route-table-def:\n\nRouteTableDef\n^^^^^^^^^^^^^\n\nA routes table definition used for describing routes by decorators\n(Flask style)::\n\n   from aiohttp import web\n\n   routes = web.RouteTableDef()\n\n   @routes.get('/get')\n   async def handle_get(request):\n       ...\n\n\n   @routes.post('/post')\n   async def handle_post(request):\n       ...\n\n   app.router.add_routes(routes)\n\n\n   @routes.view(\"/view\")\n   class MyView(web.View):\n       async def get(self):\n           ...\n\n       async def post(self):\n           ...\n\n.. class:: RouteTableDef()\n\n   A sequence of :class:`RouteDef` instances (implements\n   :class:`collections.abc.Sequence` protocol).\n\n   In addition to all standard :class:`list` methods the class\n   provides also methods like ``get()`` and ``post()`` for adding new\n   route definition.\n\n   .. versionadded:: 2.3\n\n   .. decoratormethod:: get(path, *, allow_head=True, \\\n                            name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``GET`` web-handler.\n\n      See :meth:`UrlDispatcher.add_get` for information about parameters.\n\n   .. decoratormethod:: post(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``POST`` web-handler.\n\n      See :meth:`UrlDispatcher.add_post` for information about parameters.\n\n   .. decoratormethod:: head(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``HEAD`` web-handler.\n\n      See :meth:`UrlDispatcher.add_head` for information about parameters.\n\n   .. decoratormethod:: put(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``PUT`` web-handler.\n\n      See :meth:`UrlDispatcher.add_put` for information about parameters.\n\n   .. decoratormethod:: patch(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``PATCH`` web-handler.\n\n      See :meth:`UrlDispatcher.add_patch` for information about parameters.\n\n   .. decoratormethod:: delete(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``DELETE`` web-handler.\n\n      See :meth:`UrlDispatcher.add_delete` for information about parameters.\n\n   .. decoratormethod:: view(path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering ``ANY`` methods\n      against a class-based view.\n\n      See :meth:`UrlDispatcher.add_view` for information about parameters.\n\n      .. versionadded:: 3.0\n\n   .. method:: static(prefix, path, *, name=None, expect_handler=None, \\\n                      chunk_size=256*1024, \\\n                      show_index=False, follow_symlinks=False, \\\n                      append_version=False)\n\n\n      Add a new :class:`StaticDef` item for registering static files processor.\n\n      See :meth:`UrlDispatcher.add_static` for information about\n      supported parameters.\n\n      .. versionadded:: 3.1\n\n   .. decoratormethod:: route(method, path, *, name=None, expect_handler=None)\n\n      Add a new :class:`RouteDef` item for registering a web-handler\n      for arbitrary HTTP method.\n\n      See :meth:`UrlDispatcher.add_route` for information about parameters.\n\n\nMatchInfo\n^^^^^^^^^\n\nAfter route matching web application calls found handler if any.\n\nMatching result can be accessible from handler as\n:attr:`Request.match_info` attribute.\n\nIn general the result may be any object derived from\n:class:`~aiohttp.abc.AbstractMatchInfo` (:class:`UrlMappingMatchInfo` for default\n:class:`UrlDispatcher` router).\n\n.. class:: UrlMappingMatchInfo\n\n   Inherited from :class:`dict` and :class:`~aiohttp.abc.AbstractMatchInfo`. Dict\n   items are filled by matching info and is :term:`resource`\\-specific.\n\n   .. attribute:: expect_handler\n\n      A coroutine for handling ``100-continue``.\n\n   .. attribute:: handler\n\n      A coroutine for handling request.\n\n   .. attribute:: route\n\n      :class:`AbstractRoute` instance for url matching.\n\n\nView\n^^^^\n\n.. class:: View(request)\n\n   Inherited from :class:`~aiohttp.abc.AbstractView`.\n\n   Base class for class based views. Implementations should derive from\n   :class:`View` and override methods for handling HTTP verbs like\n   ``get()`` or ``post()``::\n\n       class MyView(View):\n\n           async def get(self):\n               resp = await get_response(self.request)\n               return resp\n\n           async def post(self):\n               resp = await post_response(self.request)\n               return resp\n\n       app.router.add_view('/view', MyView)\n\n   The view raises *405 Method Not allowed*\n   (:class:`HTTPMethodNotAllowed`) if requested web verb is not\n   supported.\n\n   :param request: instance of :class:`Request` that has initiated a view\n                   processing.\n\n\n   .. attribute:: request\n\n      Request sent to view's constructor, read-only property.\n\n\n   Overridable coroutine methods: ``connect()``, ``delete()``,\n   ``get()``, ``head()``, ``options()``, ``patch()``, ``post()``,\n   ``put()``, ``trace()``.\n\n.. seealso:: :ref:`aiohttp-web-class-based-views`\n\n\n.. _aiohttp-web-app-runners-reference:\n\nRunning Applications\n--------------------\n\nTo start web application there is ``AppRunner`` and site classes.\n\nRunner is a storage for running application, sites are for running\napplication on specific TCP or Unix socket, e.g.::\n\n    runner = web.AppRunner(app)\n    await runner.setup()\n    site = web.TCPSite(runner, 'localhost', 8080)\n    await site.start()\n    # wait for finish signal\n    await runner.cleanup()\n\n\n.. versionadded:: 3.0\n\n   :class:`AppRunner` / :class:`ServerRunner` and :class:`TCPSite` /\n   :class:`UnixSite` / :class:`SockSite` are added in aiohttp 3.0\n\n\n.. class:: BaseRunner\n\n   A base class for runners. Use :class:`AppRunner` for serving\n   :class:`Application`, :class:`ServerRunner` for low-level\n   :class:`Server`.\n\n   .. attribute:: server\n\n      Low-level web :class:`Server` for handling HTTP requests,\n      read-only attribute.\n\n   .. attribute:: addresses\n\n      A  :class:`list` of served sockets addresses.\n\n      See :meth:`socket.getsockname() <socket.socket.getsockname>` for items type.\n\n      .. versionadded:: 3.3\n\n   .. attribute:: sites\n\n      A read-only :class:`set` of served sites (:class:`TCPSite` /\n      :class:`UnixSite` / :class:`NamedPipeSite` / :class:`SockSite` instances).\n\n   .. method:: setup()\n      :async:\n\n      Initialize the server. Should be called before adding sites.\n\n   .. method:: cleanup()\n      :async:\n\n      Stop handling all registered sites and cleanup used resources.\n\n\n.. class:: AppRunner(app, *, handle_signals=False, **kwargs)\n\n   A runner for :class:`Application`. Used with conjunction with sites\n   to serve on specific port.\n\n   Inherited from :class:`BaseRunner`.\n\n   :param Application app: web application instance to serve.\n\n   :param bool handle_signals: add signal handlers for\n                               :data:`signal.SIGINT` and\n                               :data:`signal.SIGTERM` (``False`` by\n                               default). These handlers will raise\n                               :exc:`GracefulExit`.\n\n   :param kwargs: named parameters to pass into\n                  web protocol.\n\n   Supported *kwargs*:\n\n   :param bool tcp_keepalive: Enable TCP Keep-Alive. Default: ``True``.\n   :param int keepalive_timeout: Number of seconds before closing Keep-Alive\n        connection. Default: ``3630`` seconds (when deployed behind a reverse proxy\n        it's important for this value to be higher than the proxy's timeout. To avoid\n        race conditions we always want the proxy to close the connection).\n   :param logger: Custom logger object. Default:\n        :data:`aiohttp.log.server_logger`.\n   :param access_log: Custom logging object. Default:\n        :data:`aiohttp.log.access_logger`.\n   :param access_log_class: Class for `access_logger`. Default:\n        :data:`aiohttp.helpers.AccessLogger`.\n        Must to be a subclass of :class:`aiohttp.abc.AbstractAccessLogger`.\n   :param str access_log_format: Access log format string. Default:\n        :attr:`helpers.AccessLogger.LOG_FORMAT`.\n   :param int max_line_size: Optional maximum header line size. Default:\n        ``8190``.\n   :param int max_field_size: Optional maximum header field size. Default:\n        ``8190``.\n\n   :param float lingering_time: Maximum time during which the server\n        reads and ignores additional data coming from the client when\n        lingering close is on.  Use ``0`` to disable lingering on\n        server channel closing.\n   :param int read_bufsize: Size of the read buffer (:attr:`BaseRequest.content`).\n                            ``None`` by default,\n                            it means that the session global value is used.\n\n      .. versionadded:: 3.7\n   :param bool auto_decompress: Automatically decompress request body,\n      ``True`` by default.\n\n      .. versionadded:: 3.8\n\n\n\n   .. attribute:: app\n\n      Read-only attribute for accessing to :class:`Application` served\n      instance.\n\n   .. method:: setup()\n      :async:\n\n      Initialize application. Should be called before adding sites.\n\n      The method calls :attr:`Application.on_startup` registered signals.\n\n   .. method:: cleanup()\n      :async:\n\n      Stop handling all registered sites and cleanup used resources.\n\n      :attr:`Application.on_shutdown` and\n      :attr:`Application.on_cleanup` signals are called internally.\n\n\n.. class:: ServerRunner(web_server, *, handle_signals=False, **kwargs)\n\n   A runner for low-level :class:`Server`. Used with conjunction with sites\n   to serve on specific port.\n\n   Inherited from :class:`BaseRunner`.\n\n   :param Server web_server: low-level web server instance to serve.\n\n   :param bool handle_signals: add signal handlers for\n                               :data:`signal.SIGINT` and\n                               :data:`signal.SIGTERM` (``False`` by\n                               default). These handlers will raise\n                               :exc:`GracefulExit`.\n\n   :param kwargs: named parameters to pass into\n                  web protocol.\n\n   .. seealso::\n\n      :ref:`aiohttp-web-lowlevel` demonstrates low-level server usage\n\n.. class:: BaseSite\n\n   An abstract class for handled sites.\n\n   .. attribute:: name\n\n      An identifier for site, read-only :class:`str` property. Could\n      be a handled URL or UNIX socket path.\n\n   .. method:: start()\n      :async:\n\n      Start handling a site.\n\n   .. method:: stop()\n      :async:\n\n      Stop handling a site.\n\n\n.. class:: TCPSite(runner, host=None, port=None, *, \\\n                   shutdown_timeout=60.0, ssl_context=None, \\\n                   backlog=128, reuse_address=None, \\\n                   reuse_port=None)\n\n   Serve a runner on TCP socket.\n\n   :param runner: a runner to serve.\n\n   :param str host: HOST to listen on, all interfaces if ``None`` (default).\n\n   :param int port: PORT to listed on, ``8080`` if ``None`` (default).\n\n   :param float shutdown_timeout: a timeout used for both waiting on pending\n                                  tasks before application shutdown and for\n                                  closing opened connections on\n                                  :meth:`BaseSite.stop` call.\n\n   :param ssl_context: a :class:`ssl.SSLContext` instance for serving\n                       SSL/TLS secure server, ``None`` for plain HTTP\n                       server (default).\n\n   :param int backlog: a number of unaccepted connections that the\n                       system will allow before refusing new\n                       connections, see :meth:`socket.socket.listen` for details.\n\n                       ``128`` by default.\n\n   :param bool reuse_address: tells the kernel to reuse a local socket in\n                              TIME_WAIT state, without waiting for its\n                              natural timeout to expire. If not specified\n                              will automatically be set to True on UNIX.\n\n   :param bool reuse_port: tells the kernel to allow this endpoint to be\n                           bound to the same port as other existing\n                           endpoints are bound to, so long as they all set\n                           this flag when being created. This option is not\n                           supported on Windows.\n\n.. class:: UnixSite(runner, path, *, \\\n                   shutdown_timeout=60.0, ssl_context=None, \\\n                   backlog=128)\n\n   Serve a runner on UNIX socket.\n\n   :param runner: a runner to serve.\n\n   :param str path: PATH to UNIX socket to listen.\n\n   :param float shutdown_timeout: a timeout used for both waiting on pending\n                                  tasks before application shutdown and for\n                                  closing opened connections on\n                                  :meth:`BaseSite.stop` call.\n\n   :param ssl_context: a :class:`ssl.SSLContext` instance for serving\n                       SSL/TLS secure server, ``None`` for plain HTTP\n                       server (default).\n\n   :param int backlog: a number of unaccepted connections that the\n                       system will allow before refusing new\n                       connections, see :meth:`socket.socket.listen` for details.\n\n                       ``128`` by default.\n\n.. class:: NamedPipeSite(runner, path, *, shutdown_timeout=60.0)\n\n   Serve a runner on Named Pipe in Windows.\n\n   :param runner: a runner to serve.\n\n   :param str path: PATH of named pipe to listen.\n\n   :param float shutdown_timeout: a timeout used for both waiting on pending\n                                  tasks before application shutdown and for\n                                  closing opened connections on\n                                  :meth:`BaseSite.stop` call.\n\n.. class:: SockSite(runner, sock, *, \\\n                   shutdown_timeout=60.0, ssl_context=None, \\\n                   backlog=128)\n\n   Serve a runner on UNIX socket.\n\n   :param runner: a runner to serve.\n\n   :param sock: A :ref:`socket instance <socket-objects>` to listen to.\n\n   :param float shutdown_timeout: a timeout used for both waiting on pending\n                                  tasks before application shutdown and for\n                                  closing opened connections on\n                                  :meth:`BaseSite.stop` call.\n\n   :param ssl_context: a :class:`ssl.SSLContext` instance for serving\n                       SSL/TLS secure server, ``None`` for plain HTTP\n                       server (default).\n\n   :param int backlog: a number of unaccepted connections that the\n                       system will allow before refusing new\n                       connections, see :meth:`socket.socket.listen` for details.\n\n                       ``128`` by default.\n\n.. exception:: GracefulExit\n\n   Raised by signal handlers for :data:`signal.SIGINT` and :data:`signal.SIGTERM`\n   defined in :class:`AppRunner` and :class:`ServerRunner`\n   when ``handle_signals`` is set to ``True``.\n\n   Inherited from :exc:`SystemExit`,\n   which exits with error code ``1`` if not handled.\n\n\nUtilities\n---------\n\n.. class:: FileField\n\n   A :mod:`dataclass <dataclasses>` instance that is returned as\n   multidict value by :meth:`aiohttp.web.BaseRequest.post` if field is uploaded file.\n\n   .. attribute:: name\n\n      Field name\n\n   .. attribute:: filename\n\n      File name as specified by uploading (client) side.\n\n   .. attribute:: file\n\n      An :class:`io.IOBase` instance with content of uploaded file.\n\n   .. attribute:: content_type\n\n      *MIME type* of uploaded file, ``'text/plain'`` by default.\n\n   .. seealso:: :ref:`aiohttp-web-file-upload`\n\n\n.. function:: run_app(app, *, debug=False, host=None, port=None, \\\n                      path=None, sock=None, shutdown_timeout=60.0, \\\n                      keepalive_timeout=3630, ssl_context=None, \\\n                      print=print, backlog=128, \\\n                      access_log_class=aiohttp.helpers.AccessLogger, \\\n                      access_log_format=aiohttp.helpers.AccessLogger.LOG_FORMAT, \\\n                      access_log=aiohttp.log.access_logger, \\\n                      handle_signals=True, \\\n                      reuse_address=None, \\\n                      reuse_port=None, \\\n                      handler_cancellation=False)\n\n   A high-level function for running an application, serving it until\n   keyboard interrupt and performing a\n   :ref:`aiohttp-web-graceful-shutdown`.\n\n   This is a high-level function very similar to :func:`asyncio.run` and\n   should be used as the main entry point for an application. The\n   :class:`Application` object essentially becomes our `main()` function.\n   If additional tasks need to be run in parallel, see\n   :ref:`aiohttp-web-complex-applications`.\n\n   The server will listen on any host or Unix domain socket path you supply.\n   If no hosts or paths are supplied, or only a port is supplied, a TCP server\n   listening on 0.0.0.0 (all hosts) will be launched.\n\n   Distributing HTTP traffic to multiple hosts or paths on the same\n   application process provides no performance benefit as the requests are\n   handled on the same event loop. See :doc:`deployment` for ways of\n   distributing work for increased performance.\n\n   :param app: :class:`Application` instance to run or a *coroutine*\n               that returns an application.\n\n   :param bool debug: enable :ref:`asyncio debug mode <asyncio-debug-mode>` if ``True``.\n\n   :param str host: TCP/IP host or a sequence of hosts for HTTP server.\n                    Default is ``'0.0.0.0'`` if *port* has been specified\n                    or if *path* is not supplied.\n\n   :param int port: TCP/IP port for HTTP server. Default is ``8080`` for plain\n                    text HTTP and ``8443`` for HTTP via SSL (when\n                    *ssl_context* parameter is specified).\n\n   :param path: file system path for HTTP server Unix domain socket.\n                    A sequence of file system paths can be used to bind\n                    multiple domain sockets. Listening on Unix domain\n                    sockets is not supported by all operating systems,\n                    :class:`str`, :class:`pathlib.Path` or an iterable of these.\n\n   :param socket.socket sock: a preexisting socket object to accept connections on.\n                       A sequence of socket objects can be passed.\n\n   :param int shutdown_timeout: a delay to wait for graceful server\n                                shutdown before disconnecting all\n                                open client sockets hard way.\n\n                                This is used as a delay to wait for\n                                pending tasks to complete and then\n                                again to close any pending connections.\n\n                                A system with properly\n                                :ref:`aiohttp-web-graceful-shutdown`\n                                implemented never waits for the second\n                                timeout but closes a server in a few\n                                milliseconds.\n\n   :param float keepalive_timeout: a delay before a TCP connection is\n                                   closed after a HTTP request. The delay\n                                   allows for reuse of a TCP connection.\n\n                                   When deployed behind a reverse proxy\n                                   it's important for this value to be\n                                   higher than the proxy's timeout. To avoid\n                                   race conditions, we always want the proxy\n                                   to handle connection closing.\n\n      .. versionadded:: 3.8\n\n   :param ssl_context: :class:`ssl.SSLContext` for HTTPS server,\n                       ``None`` for HTTP connection.\n\n   :param print: a callable compatible with :func:`print`. May be used\n                 to override STDOUT output or suppress it. Passing `None`\n                 disables output.\n\n   :param int backlog: the number of unaccepted connections that the\n                       system will allow before refusing new\n                       connections (``128`` by default).\n\n   :param access_log_class: class for `access_logger`. Default:\n                            :data:`aiohttp.helpers.AccessLogger`.\n                            Must to be a subclass of :class:`aiohttp.abc.AbstractAccessLogger`.\n\n   :param access_log: :class:`logging.Logger` instance used for saving\n                      access logs. Use ``None`` for disabling logs for\n                      sake of speedup.\n\n   :param access_log_format: access log format, see\n                             :ref:`aiohttp-logging-access-log-format-spec`\n                             for details.\n\n   :param bool handle_signals: override signal TERM handling to gracefully\n                               exit the application.\n\n   :param bool reuse_address: tells the kernel to reuse a local socket in\n                              TIME_WAIT state, without waiting for its\n                              natural timeout to expire. If not specified\n                              will automatically be set to True on UNIX.\n\n   :param bool reuse_port: tells the kernel to allow this endpoint to be\n                           bound to the same port as other existing\n                           endpoints are bound to, so long as they all set\n                           this flag when being created. This option is not\n                           supported on Windows.\n\n   :param bool handler_cancellation: cancels the web handler task if the client\n                                     drops the connection. This is recommended\n                                     if familiar with asyncio behavior or\n                                     scalability is a concern.\n                                     :ref:`aiohttp-web-peer-disconnection`\n\n   .. versionadded:: 3.0\n\n      Support *access_log_class* parameter.\n\n      Support *reuse_address*, *reuse_port* parameter.\n\n   .. versionadded:: 3.1\n\n      Accept a coroutine as *app* parameter.\n\n   .. versionadded:: 3.9\n\n      Support handler_cancellation parameter (this was the default behavior\n      in aiohttp <3.7).\n\nConstants\n---------\n\n.. class:: ContentCoding\n\n   An :class:`enum.Enum` class of available Content Codings.\n\n   .. attribute:: deflate\n\n      *DEFLATE compression*\n\n   .. attribute:: gzip\n\n      *GZIP compression*\n\n   .. attribute:: identity\n\n      *no compression*\n\n\nMiddlewares\n-----------\n\n.. function:: normalize_path_middleware(*, \\\n                                        append_slash=True, \\\n                                        remove_slash=False, \\\n                                        merge_slashes=True, \\\n                                        redirect_class=HTTPPermanentRedirect)\n\n   Middleware factory which produces a middleware that normalizes\n   the path of a request. By normalizing it means:\n\n     - Add or remove a trailing slash to the path.\n     - Double slashes are replaced by one.\n\n   The middleware returns as soon as it finds a path that resolves\n   correctly. The order if both merge and append/remove are enabled is:\n\n     1. *merge_slashes*\n     2. *append_slash* or *remove_slash*\n     3. both *merge_slashes* and *append_slash* or *remove_slash*\n\n   If the path resolves with at least one of those conditions, it will\n   redirect to the new path.\n\n   Only one of *append_slash* and *remove_slash* can be enabled. If both are\n   ``True`` the factory will raise an ``AssertionError``\n\n   If *append_slash* is ``True`` the middleware will append a slash when\n   needed. If a resource is defined with trailing slash and the request\n   comes without it, it will append it automatically.\n\n   If *remove_slash* is ``True``, *append_slash* must be ``False``. When enabled\n   the middleware will remove trailing slashes and redirect if the resource is\n   defined.\n\n   If *merge_slashes* is ``True``, merge multiple consecutive slashes in the\n   path into one.\n\n   .. versionadded:: 3.4\n\n      Support for *remove_slash*\n",
            "header": {
                "file": {
                    "path": "docs/web_reference.rst"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "5b92e220",
                "new_commit_hash": "b75b8269",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/docs/web_reference.rst"
            },
            "plus_file": {
                "path": "b/docs/web_reference.rst"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 922,
                            "length": 7
                        },
                        "new_range": {
                            "start": 922,
                            "length": 8
                        },
                        "section": "and :ref:`aiohttp-web-signals` handlers::"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": ".. class:: WebSocketResponse(*, timeout=10.0, receive_timeout=None, \\",
                                "type": "context"
                            },
                            {
                                "content": "                             autoclose=True, autoping=True, heartbeat=None, \\",
                                "type": "context"
                            },
                            {
                                "content": "                             protocols=(), compress=True, max_msg_size=4194304)",
                                "type": "deleted"
                            },
                            {
                                "content": "                             protocols=(), compress=True, max_msg_size=4194304, \\",
                                "type": "added"
                            },
                            {
                                "content": "                             writer_limit=65536)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "   Class for handling server-side websockets, inherited from",
                                "type": "context"
                            },
                            {
                                "content": "   :class:`StreamResponse`.",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 973,
                            "length": 6
                        },
                        "new_range": {
                            "start": 974,
                            "length": 11
                        },
                        "section": "and :ref:`aiohttp-web-signals` handlers::"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                           ``request.transport.close()`` to avoid",
                                "type": "context"
                            },
                            {
                                "content": "                           leaking resources.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "   :param int writer_limit: maximum size of write buffer, 64 KB by default.",
                                "type": "added"
                            },
                            {
                                "content": "                            Once the buffer is full, the websocket will pause",
                                "type": "added"
                            },
                            {
                                "content": "                            to drain the buffer.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "      .. versionadded:: 3.11",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "   The class supports ``async for`` statement for iterating over",
                                "type": "context"
                            },
                            {
                                "content": "   incoming messages::",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import asyncio\nimport time\nfrom typing import Optional, Protocol\nfrom unittest import mock\n\nimport aiosignal\nimport pytest\nfrom multidict import CIMultiDict\nfrom pytest_mock import MockerFixture\n\nfrom aiohttp import WSMsgType, web\nfrom aiohttp.http import WS_CLOSED_MESSAGE, WS_CLOSING_MESSAGE\nfrom aiohttp.http_websocket import WSMessageClose\nfrom aiohttp.streams import EofStream\nfrom aiohttp.test_utils import make_mocked_coro, make_mocked_request\nfrom aiohttp.web_ws import WebSocketReady\n\n\nclass _RequestMaker(Protocol):\n    def __call__(\n        self,\n        method: str,\n        path: str,\n        headers: Optional[CIMultiDict[str]] = None,\n        protocols: bool = False,\n    ) -> web.Request: ...\n\n\n@pytest.fixture\ndef app(loop: asyncio.AbstractEventLoop) -> web.Application:\n    ret: web.Application = mock.create_autospec(web.Application, spec_set=True)\n    ret.on_response_prepare = aiosignal.Signal(ret)  # type: ignore[misc]\n    ret.on_response_prepare.freeze()\n    return ret\n\n\n@pytest.fixture\ndef protocol() -> web.RequestHandler[web.Request]:\n    ret = mock.Mock()\n    ret.set_parser.return_value = ret\n    return ret\n\n\n@pytest.fixture\ndef make_request(\n    app: web.Application, protocol: web.RequestHandler[web.Request]\n) -> _RequestMaker:\n    def maker(\n        method: str,\n        path: str,\n        headers: Optional[CIMultiDict[str]] = None,\n        protocols: bool = False,\n    ) -> web.Request:\n        if headers is None:\n            headers = CIMultiDict(\n                {\n                    \"HOST\": \"server.example.com\",\n                    \"UPGRADE\": \"websocket\",\n                    \"CONNECTION\": \"Upgrade\",\n                    \"SEC-WEBSOCKET-KEY\": \"dGhlIHNhbXBsZSBub25jZQ==\",\n                    \"ORIGIN\": \"http://example.com\",\n                    \"SEC-WEBSOCKET-VERSION\": \"13\",\n                }\n            )\n        if protocols:\n            headers[\"SEC-WEBSOCKET-PROTOCOL\"] = \"chat, superchat\"\n\n        return make_mocked_request(method, path, headers, app=app, protocol=protocol)\n\n    return maker\n\n\nasync def test_nonstarted_ping() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.ping()\n\n\nasync def test_nonstarted_pong() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.pong()\n\n\nasync def test_nonstarted_send_frame() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_frame(b\"string\", WSMsgType.TEXT)\n\n\nasync def test_nonstarted_send_str() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_str(\"string\")\n\n\nasync def test_nonstarted_send_bytes() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_bytes(b\"bytes\")\n\n\nasync def test_nonstarted_send_json() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_json({\"type\": \"json\"})\n\n\nasync def test_nonstarted_close() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.close()\n\n\nasync def test_nonstarted_receive_str() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.receive_str()\n\n\nasync def test_nonstarted_receive_bytes() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.receive_bytes()\n\n\nasync def test_nonstarted_receive_json() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.receive_json()\n\n\nasync def test_send_str_nonstring(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(TypeError):\n        await ws.send_str(b\"bytes\")  # type: ignore[arg-type]\n\n\nasync def test_send_bytes_nonbytes(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(TypeError):\n        await ws.send_bytes(\"string\")  # type: ignore[arg-type]\n\n\nasync def test_send_json_nonjson(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(TypeError):\n        await ws.send_json(set())\n\n\nasync def test_write_non_prepared() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.write(b\"data\")\n\n\nasync def test_heartbeat_timeout(make_request: _RequestMaker) -> None:\n    \"\"\"Verify the transport is closed when the heartbeat timeout is reached.\"\"\"\n    loop = asyncio.get_running_loop()\n    future = loop.create_future()\n    req = make_request(\"GET\", \"/\")\n    assert req.transport is not None\n    req.transport.close.side_effect = lambda: future.set_result(None)  # type: ignore[attr-defined]\n    lowest_time = time.get_clock_info(\"monotonic\").resolution\n    req._protocol._timeout_ceil_threshold = lowest_time\n    ws = web.WebSocketResponse(heartbeat=lowest_time, timeout=lowest_time)\n    await ws.prepare(req)\n    await future\n    assert ws.closed\n\n\ndef test_websocket_ready() -> None:\n    websocket_ready = WebSocketReady(True, \"chat\")\n    assert websocket_ready.ok is True\n    assert websocket_ready.protocol == \"chat\"\n\n\ndef test_websocket_not_ready() -> None:\n    websocket_ready = WebSocketReady(False, None)\n    assert websocket_ready.ok is False\n    assert websocket_ready.protocol is None\n\n\ndef test_websocket_ready_unknown_protocol() -> None:\n    websocket_ready = WebSocketReady(True, None)\n    assert websocket_ready.ok is True\n    assert websocket_ready.protocol is None\n\n\ndef test_bool_websocket_ready() -> None:\n    websocket_ready = WebSocketReady(True, None)\n    assert bool(websocket_ready) is True\n\n\ndef test_bool_websocket_not_ready() -> None:\n    websocket_ready = WebSocketReady(False, None)\n    assert bool(websocket_ready) is False\n\n\ndef test_can_prepare_ok(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\", protocols=True)\n    ws = web.WebSocketResponse(protocols=(\"chat\",))\n    assert WebSocketReady(True, \"chat\") == ws.can_prepare(req)\n\n\ndef test_can_prepare_unknown_protocol(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    assert WebSocketReady(True, None) == ws.can_prepare(req)\n\n\ndef test_can_prepare_without_upgrade(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\", headers=CIMultiDict({}))\n    ws = web.WebSocketResponse()\n    assert WebSocketReady(False, None) == ws.can_prepare(req)\n\n\nasync def test_can_prepare_started(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(RuntimeError) as ctx:\n        ws.can_prepare(req)\n\n    assert \"Already started\" in str(ctx.value)\n\n\ndef test_closed_after_ctor() -> None:\n    ws = web.WebSocketResponse()\n    assert not ws.closed\n    assert ws.close_code is None\n\n\nasync def test_send_str_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n    with pytest.raises(ConnectionError):\n        await ws.send_str(\"string\")\n\n\nasync def test_send_bytes_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.send_bytes(b\"bytes\")\n\n\nasync def test_send_json_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.send_json({\"type\": \"json\"})\n\n\nasync def test_send_frame_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.send_frame(b'{\"type\": \"json\"}', WSMsgType.TEXT)\n\n\nasync def test_ping_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.ping()\n\n\nasync def test_pong_closed(make_request: _RequestMaker, mocker: MockerFixture) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.pong()\n\n\nasync def test_close_idempotent(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    close_code = await ws.close(code=1, message=b\"message1\")\n    assert close_code == 1\n    assert ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n    close_code = await ws.close(code=2, message=b\"message2\")\n    assert close_code == 0\n\n\nasync def test_prepare_post_method_ok(make_request: _RequestMaker) -> None:\n    req = make_request(\"POST\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws.prepared\n\n\nasync def test_prepare_without_upgrade(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\", headers=CIMultiDict({}))\n    ws = web.WebSocketResponse()\n    with pytest.raises(web.HTTPBadRequest):\n        await ws.prepare(req)\n\n\nasync def test_wait_closed_before_start() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.close()\n\n\nasync def test_write_eof_not_started() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.write_eof()\n\n\nasync def test_write_eof_idempotent(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    await ws.write_eof()\n    await ws.write_eof()\n    await ws.write_eof()\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n\nasync def test_receive_eofstream_in_reader(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n\n    ws._reader = mock.Mock()\n    exc = EofStream()\n    res = loop.create_future()\n    res.set_exception(exc)\n    ws._reader.read = make_mocked_coro(res)\n    assert ws._payload_writer is not None\n    f = loop.create_future()\n    f.set_result(True)\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n    assert ws.closed\n\n\nasync def test_receive_exception_in_reader(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n\n    ws._reader = mock.Mock()\n    exc = Exception()\n    res = loop.create_future()\n    res.set_exception(exc)\n    ws._reader.read = make_mocked_coro(res)\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.ERROR\n    assert ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n\nasync def test_receive_close_but_left_open(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    close_message = WSMessageClose(data=1000, extra=\"close\")\n\n    ws._reader = mock.Mock()\n    ws._reader.read = mock.AsyncMock(return_value=close_message)\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n    assert ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n\nasync def test_receive_closing(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    closing_message = WS_CLOSING_MESSAGE\n\n    ws._reader = mock.Mock()\n    read_mock = mock.AsyncMock(return_value=closing_message)\n    ws._reader.read = read_mock\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n    assert not ws.closed\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n    assert not ws.closed\n\n    ws._cancel(ConnectionResetError(\"Connection lost\"))\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n\n\nasync def test_close_after_closing(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    closing_message = WS_CLOSING_MESSAGE\n\n    ws._reader = mock.Mock()\n    ws._reader.read = mock.AsyncMock(return_value=closing_message)\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n    assert not ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    await ws.close()\n    assert ws.closed\n    assert len(req.transport.close.mock_calls) == 1\n\n\nasync def test_receive_timeouterror(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    ws._reader = mock.Mock()\n    res = loop.create_future()\n    res.set_exception(asyncio.TimeoutError())\n    ws._reader.read = make_mocked_coro(res)\n\n    with pytest.raises(asyncio.TimeoutError):\n        await ws.receive()\n\n    # Should not close the connection on timeout\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n\nasync def test_multiple_receive_on_close_connection(\n    make_request: _RequestMaker,\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    await ws.receive()\n    await ws.receive()\n    await ws.receive()\n    await ws.receive()\n\n    with pytest.raises(RuntimeError):\n        await ws.receive()\n\n\nasync def test_concurrent_receive(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    ws._waiting = True\n\n    with pytest.raises(RuntimeError):\n        await ws.receive()\n\n\nasync def test_close_exc(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    exc = ValueError()\n    ws._writer = mock.Mock()\n    ws._writer.close.side_effect = exc\n    await ws.close()\n    assert ws.closed\n    assert ws.exception() is exc\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n    ws._closed = False\n    ws._writer.close.side_effect = asyncio.CancelledError()\n    with pytest.raises(asyncio.CancelledError):\n        await ws.close()\n\n\nasync def test_prepare_twice_idempotent(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n\n    impl1 = await ws.prepare(req)\n    impl2 = await ws.prepare(req)\n    assert impl1 is impl2\n\n\nasync def test_send_with_per_message_deflate(\n    make_request: _RequestMaker, mocker: MockerFixture\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with mock.patch.object(ws._writer, \"send_frame\", autospec=True, spec_set=True) as m:\n        await ws.send_str(\"string\", compress=15)\n        m.assert_called_with(b\"string\", WSMsgType.TEXT, compress=15)\n\n        await ws.send_bytes(b\"bytes\", compress=0)\n        m.assert_called_with(b\"bytes\", WSMsgType.BINARY, compress=0)\n\n        await ws.send_json(\"[{}]\", compress=9)\n        m.assert_called_with(b'\"[{}]\"', WSMsgType.TEXT, compress=9)\n\n        await ws.send_frame(b\"[{}]\", WSMsgType.TEXT, compress=9)\n        m.assert_called_with(b\"[{}]\", WSMsgType.TEXT, compress=9)\n\n\nasync def test_no_transfer_encoding_header(\n    make_request: _RequestMaker, mocker: MockerFixture\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws._start(req)\n\n    assert \"Transfer-Encoding\" not in ws.headers\n\n\n@pytest.mark.parametrize(\n    \"ws_transport, expected_result\",\n    [\n        (\n            mock.MagicMock(\n                transport=mock.MagicMock(\n                    get_extra_info=lambda name, default=None: {\"test\": \"existent\"}.get(\n                        name, default\n                    )\n                )\n            ),\n            \"existent\",\n        ),\n        (None, \"default\"),\n        (mock.MagicMock(transport=None), \"default\"),\n    ],\n)\nasync def test_get_extra_info(\n    make_request: _RequestMaker,\n    mocker: MockerFixture,\n    ws_transport: Optional[mock.MagicMock],\n    expected_result: str,\n) -> None:\n    valid_key = \"test\"\n    default_value = \"default\"\n\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n\n    await ws.prepare(req)\n    ws._writer = ws_transport\n\n    assert ws.get_extra_info(valid_key, default_value) == expected_result\n",
            "new_file_content": "import asyncio\nimport time\nfrom typing import Optional, Protocol\nfrom unittest import mock\n\nimport aiosignal\nimport pytest\nfrom multidict import CIMultiDict\nfrom pytest_mock import MockerFixture\n\nfrom aiohttp import WSMsgType, web\nfrom aiohttp.http import WS_CLOSED_MESSAGE, WS_CLOSING_MESSAGE\nfrom aiohttp.http_websocket import WSMessageClose\nfrom aiohttp.streams import EofStream\nfrom aiohttp.test_utils import make_mocked_coro, make_mocked_request\nfrom aiohttp.web_ws import WebSocketReady\n\n\nclass _RequestMaker(Protocol):\n    def __call__(\n        self,\n        method: str,\n        path: str,\n        headers: Optional[CIMultiDict[str]] = None,\n        protocols: bool = False,\n    ) -> web.Request: ...\n\n\n@pytest.fixture\ndef app(loop: asyncio.AbstractEventLoop) -> web.Application:\n    ret: web.Application = mock.create_autospec(web.Application, spec_set=True)\n    ret.on_response_prepare = aiosignal.Signal(ret)  # type: ignore[misc]\n    ret.on_response_prepare.freeze()\n    return ret\n\n\n@pytest.fixture\ndef protocol() -> web.RequestHandler[web.Request]:\n    ret = mock.Mock()\n    ret.set_parser.return_value = ret\n    return ret\n\n\n@pytest.fixture\ndef make_request(\n    app: web.Application, protocol: web.RequestHandler[web.Request]\n) -> _RequestMaker:\n    def maker(\n        method: str,\n        path: str,\n        headers: Optional[CIMultiDict[str]] = None,\n        protocols: bool = False,\n    ) -> web.Request:\n        if headers is None:\n            headers = CIMultiDict(\n                {\n                    \"HOST\": \"server.example.com\",\n                    \"UPGRADE\": \"websocket\",\n                    \"CONNECTION\": \"Upgrade\",\n                    \"SEC-WEBSOCKET-KEY\": \"dGhlIHNhbXBsZSBub25jZQ==\",\n                    \"ORIGIN\": \"http://example.com\",\n                    \"SEC-WEBSOCKET-VERSION\": \"13\",\n                }\n            )\n        if protocols:\n            headers[\"SEC-WEBSOCKET-PROTOCOL\"] = \"chat, superchat\"\n\n        return make_mocked_request(method, path, headers, app=app, protocol=protocol)\n\n    return maker\n\n\nasync def test_nonstarted_ping() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.ping()\n\n\nasync def test_nonstarted_pong() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.pong()\n\n\nasync def test_nonstarted_send_frame() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_frame(b\"string\", WSMsgType.TEXT)\n\n\nasync def test_nonstarted_send_str() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_str(\"string\")\n\n\nasync def test_nonstarted_send_bytes() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_bytes(b\"bytes\")\n\n\nasync def test_nonstarted_send_json() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_json({\"type\": \"json\"})\n\n\nasync def test_nonstarted_close() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.close()\n\n\nasync def test_nonstarted_receive_str() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.receive_str()\n\n\nasync def test_nonstarted_receive_bytes() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.receive_bytes()\n\n\nasync def test_nonstarted_receive_json() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.receive_json()\n\n\nasync def test_send_str_nonstring(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(TypeError):\n        await ws.send_str(b\"bytes\")  # type: ignore[arg-type]\n\n\nasync def test_send_bytes_nonbytes(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(TypeError):\n        await ws.send_bytes(\"string\")  # type: ignore[arg-type]\n\n\nasync def test_send_json_nonjson(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(TypeError):\n        await ws.send_json(set())\n\n\nasync def test_write_non_prepared() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.write(b\"data\")\n\n\nasync def test_heartbeat_timeout(make_request: _RequestMaker) -> None:\n    \"\"\"Verify the transport is closed when the heartbeat timeout is reached.\"\"\"\n    loop = asyncio.get_running_loop()\n    future = loop.create_future()\n    req = make_request(\"GET\", \"/\")\n    assert req.transport is not None\n    req.transport.close.side_effect = lambda: future.set_result(None)  # type: ignore[attr-defined]\n    lowest_time = time.get_clock_info(\"monotonic\").resolution\n    req._protocol._timeout_ceil_threshold = lowest_time\n    ws = web.WebSocketResponse(heartbeat=lowest_time, timeout=lowest_time)\n    await ws.prepare(req)\n    await future\n    assert ws.closed\n\n\ndef test_websocket_ready() -> None:\n    websocket_ready = WebSocketReady(True, \"chat\")\n    assert websocket_ready.ok is True\n    assert websocket_ready.protocol == \"chat\"\n\n\ndef test_websocket_not_ready() -> None:\n    websocket_ready = WebSocketReady(False, None)\n    assert websocket_ready.ok is False\n    assert websocket_ready.protocol is None\n\n\ndef test_websocket_ready_unknown_protocol() -> None:\n    websocket_ready = WebSocketReady(True, None)\n    assert websocket_ready.ok is True\n    assert websocket_ready.protocol is None\n\n\ndef test_bool_websocket_ready() -> None:\n    websocket_ready = WebSocketReady(True, None)\n    assert bool(websocket_ready) is True\n\n\ndef test_bool_websocket_not_ready() -> None:\n    websocket_ready = WebSocketReady(False, None)\n    assert bool(websocket_ready) is False\n\n\ndef test_can_prepare_ok(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\", protocols=True)\n    ws = web.WebSocketResponse(protocols=(\"chat\",))\n    assert WebSocketReady(True, \"chat\") == ws.can_prepare(req)\n\n\ndef test_can_prepare_unknown_protocol(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    assert WebSocketReady(True, None) == ws.can_prepare(req)\n\n\ndef test_can_prepare_without_upgrade(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\", headers=CIMultiDict({}))\n    ws = web.WebSocketResponse()\n    assert WebSocketReady(False, None) == ws.can_prepare(req)\n\n\nasync def test_can_prepare_started(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(RuntimeError) as ctx:\n        ws.can_prepare(req)\n\n    assert \"Already started\" in str(ctx.value)\n\n\ndef test_closed_after_ctor() -> None:\n    ws = web.WebSocketResponse()\n    assert not ws.closed\n    assert ws.close_code is None\n\n\nasync def test_raise_writer_limit(make_request: _RequestMaker) -> None:\n    \"\"\"Test the writer limit can be adjusted.\"\"\"\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse(writer_limit=1234567)\n    await ws.prepare(req)\n    assert ws._reader is not None\n    assert ws._writer is not None\n    assert ws._writer._limit == 1234567\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n\nasync def test_send_str_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n    with pytest.raises(ConnectionError):\n        await ws.send_str(\"string\")\n\n\nasync def test_send_bytes_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.send_bytes(b\"bytes\")\n\n\nasync def test_send_json_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.send_json({\"type\": \"json\"})\n\n\nasync def test_send_frame_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.send_frame(b'{\"type\": \"json\"}', WSMsgType.TEXT)\n\n\nasync def test_ping_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.ping()\n\n\nasync def test_pong_closed(make_request: _RequestMaker, mocker: MockerFixture) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.pong()\n\n\nasync def test_close_idempotent(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    close_code = await ws.close(code=1, message=b\"message1\")\n    assert close_code == 1\n    assert ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n    close_code = await ws.close(code=2, message=b\"message2\")\n    assert close_code == 0\n\n\nasync def test_prepare_post_method_ok(make_request: _RequestMaker) -> None:\n    req = make_request(\"POST\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws.prepared\n\n\nasync def test_prepare_without_upgrade(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\", headers=CIMultiDict({}))\n    ws = web.WebSocketResponse()\n    with pytest.raises(web.HTTPBadRequest):\n        await ws.prepare(req)\n\n\nasync def test_wait_closed_before_start() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.close()\n\n\nasync def test_write_eof_not_started() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.write_eof()\n\n\nasync def test_write_eof_idempotent(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    await ws.write_eof()\n    await ws.write_eof()\n    await ws.write_eof()\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n\nasync def test_receive_eofstream_in_reader(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n\n    ws._reader = mock.Mock()\n    exc = EofStream()\n    res = loop.create_future()\n    res.set_exception(exc)\n    ws._reader.read = make_mocked_coro(res)\n    assert ws._payload_writer is not None\n    f = loop.create_future()\n    f.set_result(True)\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n    assert ws.closed\n\n\nasync def test_receive_exception_in_reader(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n\n    ws._reader = mock.Mock()\n    exc = Exception()\n    res = loop.create_future()\n    res.set_exception(exc)\n    ws._reader.read = make_mocked_coro(res)\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.ERROR\n    assert ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n\nasync def test_receive_close_but_left_open(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    close_message = WSMessageClose(data=1000, extra=\"close\")\n\n    ws._reader = mock.Mock()\n    ws._reader.read = mock.AsyncMock(return_value=close_message)\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n    assert ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n\nasync def test_receive_closing(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    closing_message = WS_CLOSING_MESSAGE\n\n    ws._reader = mock.Mock()\n    read_mock = mock.AsyncMock(return_value=closing_message)\n    ws._reader.read = read_mock\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n    assert not ws.closed\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n    assert not ws.closed\n\n    ws._cancel(ConnectionResetError(\"Connection lost\"))\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n\n\nasync def test_close_after_closing(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    closing_message = WS_CLOSING_MESSAGE\n\n    ws._reader = mock.Mock()\n    ws._reader.read = mock.AsyncMock(return_value=closing_message)\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n    assert not ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    await ws.close()\n    assert ws.closed\n    assert len(req.transport.close.mock_calls) == 1\n\n\nasync def test_receive_timeouterror(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    ws._reader = mock.Mock()\n    res = loop.create_future()\n    res.set_exception(asyncio.TimeoutError())\n    ws._reader.read = make_mocked_coro(res)\n\n    with pytest.raises(asyncio.TimeoutError):\n        await ws.receive()\n\n    # Should not close the connection on timeout\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n\nasync def test_multiple_receive_on_close_connection(\n    make_request: _RequestMaker,\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    await ws.receive()\n    await ws.receive()\n    await ws.receive()\n    await ws.receive()\n\n    with pytest.raises(RuntimeError):\n        await ws.receive()\n\n\nasync def test_concurrent_receive(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    ws._waiting = True\n\n    with pytest.raises(RuntimeError):\n        await ws.receive()\n\n\nasync def test_close_exc(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    exc = ValueError()\n    ws._writer = mock.Mock()\n    ws._writer.close.side_effect = exc\n    await ws.close()\n    assert ws.closed\n    assert ws.exception() is exc\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n    ws._closed = False\n    ws._writer.close.side_effect = asyncio.CancelledError()\n    with pytest.raises(asyncio.CancelledError):\n        await ws.close()\n\n\nasync def test_prepare_twice_idempotent(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n\n    impl1 = await ws.prepare(req)\n    impl2 = await ws.prepare(req)\n    assert impl1 is impl2\n\n\nasync def test_send_with_per_message_deflate(\n    make_request: _RequestMaker, mocker: MockerFixture\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with mock.patch.object(ws._writer, \"send_frame\", autospec=True, spec_set=True) as m:\n        await ws.send_str(\"string\", compress=15)\n        m.assert_called_with(b\"string\", WSMsgType.TEXT, compress=15)\n\n        await ws.send_bytes(b\"bytes\", compress=0)\n        m.assert_called_with(b\"bytes\", WSMsgType.BINARY, compress=0)\n\n        await ws.send_json(\"[{}]\", compress=9)\n        m.assert_called_with(b'\"[{}]\"', WSMsgType.TEXT, compress=9)\n\n        await ws.send_frame(b\"[{}]\", WSMsgType.TEXT, compress=9)\n        m.assert_called_with(b\"[{}]\", WSMsgType.TEXT, compress=9)\n\n\nasync def test_no_transfer_encoding_header(\n    make_request: _RequestMaker, mocker: MockerFixture\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws._start(req)\n\n    assert \"Transfer-Encoding\" not in ws.headers\n\n\n@pytest.mark.parametrize(\n    \"ws_transport, expected_result\",\n    [\n        (\n            mock.MagicMock(\n                transport=mock.MagicMock(\n                    get_extra_info=lambda name, default=None: {\"test\": \"existent\"}.get(\n                        name, default\n                    )\n                )\n            ),\n            \"existent\",\n        ),\n        (None, \"default\"),\n        (mock.MagicMock(transport=None), \"default\"),\n    ],\n)\nasync def test_get_extra_info(\n    make_request: _RequestMaker,\n    mocker: MockerFixture,\n    ws_transport: Optional[mock.MagicMock],\n    expected_result: str,\n) -> None:\n    valid_key = \"test\"\n    default_value = \"default\"\n\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n\n    await ws.prepare(req)\n    ws._writer = ws_transport\n\n    assert ws.get_extra_info(valid_key, default_value) == expected_result\n",
            "header": {
                "file": {
                    "path": "tests/test_web_websocket.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "9cf3ffe5",
                "new_commit_hash": "5ee6d475",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tests/test_web_websocket.py"
            },
            "plus_file": {
                "path": "b/tests/test_web_websocket.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 237,
                            "length": 6
                        },
                        "new_range": {
                            "start": 237,
                            "length": 18
                        },
                        "section": "def test_closed_after_ctor() -> None:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    assert ws.close_code is None",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "async def test_raise_writer_limit(make_request: _RequestMaker) -> None:",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"Test the writer limit can be adjusted.\"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "    req = make_request(\"GET\", \"/\")",
                                "type": "added"
                            },
                            {
                                "content": "    ws = web.WebSocketResponse(writer_limit=1234567)",
                                "type": "added"
                            },
                            {
                                "content": "    await ws.prepare(req)",
                                "type": "added"
                            },
                            {
                                "content": "    assert ws._reader is not None",
                                "type": "added"
                            },
                            {
                                "content": "    assert ws._writer is not None",
                                "type": "added"
                            },
                            {
                                "content": "    assert ws._writer._limit == 1234567",
                                "type": "added"
                            },
                            {
                                "content": "    ws._reader.feed_data(WS_CLOSED_MESSAGE)",
                                "type": "added"
                            },
                            {
                                "content": "    await ws.close()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "async def test_send_str_closed(make_request: _RequestMaker) -> None:",
                                "type": "context"
                            },
                            {
                                "content": "    req = make_request(\"GET\", \"/\")",
                                "type": "context"
                            },
                            {
                                "content": "    ws = web.WebSocketResponse()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tests/test_web_websocket.py",
                            "type": "function",
                            "name": "test_raise_writer_limit",
                            "content": "async def test_raise_writer_limit(make_request: _RequestMaker) -> None:\n    \"\"\"Test the writer limit can be adjusted.\"\"\"\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse(writer_limit=1234567)\n    await ws.prepare(req)\n    assert ws._reader is not None\n    assert ws._writer is not None\n    assert ws._writer._limit == 1234567\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()",
                            "ast_type_str": "AsyncFunctionDef",
                            "start_lineno": 240,
                            "end_lineno": 249,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "e36c5f0ffeeea0076736c5756d63f5933c91eb8d^",
    "new_commit_hash": "e36c5f0ffeeea0076736c5756d63f5933c91eb8d",
    "commit_message": "Add support for adjusting the server WebSocket writer limit (#9572)",
    "commit_date": "2024-10-28T20:56:26Z",
    "metadata": {}
}
{
    "repo_name": "aiohttp",
    "new_commit_hash": "e36c5f0ffeeea0076736c5756d63f5933c91eb8d",
    "test_file_codes": [
        "import asyncio\nimport time\nfrom typing import Optional, Protocol\nfrom unittest import mock\n\nimport aiosignal\nimport pytest\nfrom multidict import CIMultiDict\nfrom pytest_mock import MockerFixture\n\nfrom aiohttp import WSMsgType, web\nfrom aiohttp.http import WS_CLOSED_MESSAGE, WS_CLOSING_MESSAGE\nfrom aiohttp.http_websocket import WSMessageClose\nfrom aiohttp.streams import EofStream\nfrom aiohttp.test_utils import make_mocked_coro, make_mocked_request\nfrom aiohttp.web_ws import WebSocketReady\n\n\nclass _RequestMaker(Protocol):\n    def __call__(\n        self,\n        method: str,\n        path: str,\n        headers: Optional[CIMultiDict[str]] = None,\n        protocols: bool = False,\n    ) -> web.Request: ...\n\n\n@pytest.fixture\ndef app(loop: asyncio.AbstractEventLoop) -> web.Application:\n    ret: web.Application = mock.create_autospec(web.Application, spec_set=True)\n    ret.on_response_prepare = aiosignal.Signal(ret)  # type: ignore[misc]\n    ret.on_response_prepare.freeze()\n    return ret\n\n\n@pytest.fixture\ndef protocol() -> web.RequestHandler[web.Request]:\n    ret = mock.Mock()\n    ret.set_parser.return_value = ret\n    return ret\n\n\n@pytest.fixture\ndef make_request(\n    app: web.Application, protocol: web.RequestHandler[web.Request]\n) -> _RequestMaker:\n    def maker(\n        method: str,\n        path: str,\n        headers: Optional[CIMultiDict[str]] = None,\n        protocols: bool = False,\n    ) -> web.Request:\n        if headers is None:\n            headers = CIMultiDict(\n                {\n                    \"HOST\": \"server.example.com\",\n                    \"UPGRADE\": \"websocket\",\n                    \"CONNECTION\": \"Upgrade\",\n                    \"SEC-WEBSOCKET-KEY\": \"dGhlIHNhbXBsZSBub25jZQ==\",\n                    \"ORIGIN\": \"http://example.com\",\n                    \"SEC-WEBSOCKET-VERSION\": \"13\",\n                }\n            )\n        if protocols:\n            headers[\"SEC-WEBSOCKET-PROTOCOL\"] = \"chat, superchat\"\n\n        return make_mocked_request(method, path, headers, app=app, protocol=protocol)\n\n    return maker\n\n\nasync def test_nonstarted_ping() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.ping()\n\n\nasync def test_nonstarted_pong() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.pong()\n\n\nasync def test_nonstarted_send_frame() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_frame(b\"string\", WSMsgType.TEXT)\n\n\nasync def test_nonstarted_send_str() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_str(\"string\")\n\n\nasync def test_nonstarted_send_bytes() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_bytes(b\"bytes\")\n\n\nasync def test_nonstarted_send_json() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.send_json({\"type\": \"json\"})\n\n\nasync def test_nonstarted_close() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.close()\n\n\nasync def test_nonstarted_receive_str() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.receive_str()\n\n\nasync def test_nonstarted_receive_bytes() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.receive_bytes()\n\n\nasync def test_nonstarted_receive_json() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.receive_json()\n\n\nasync def test_send_str_nonstring(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(TypeError):\n        await ws.send_str(b\"bytes\")  # type: ignore[arg-type]\n\n\nasync def test_send_bytes_nonbytes(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(TypeError):\n        await ws.send_bytes(\"string\")  # type: ignore[arg-type]\n\n\nasync def test_send_json_nonjson(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(TypeError):\n        await ws.send_json(set())\n\n\nasync def test_write_non_prepared() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.write(b\"data\")\n\n\nasync def test_heartbeat_timeout(make_request: _RequestMaker) -> None:\n    \"\"\"Verify the transport is closed when the heartbeat timeout is reached.\"\"\"\n    loop = asyncio.get_running_loop()\n    future = loop.create_future()\n    req = make_request(\"GET\", \"/\")\n    assert req.transport is not None\n    req.transport.close.side_effect = lambda: future.set_result(None)  # type: ignore[attr-defined]\n    lowest_time = time.get_clock_info(\"monotonic\").resolution\n    req._protocol._timeout_ceil_threshold = lowest_time\n    ws = web.WebSocketResponse(heartbeat=lowest_time, timeout=lowest_time)\n    await ws.prepare(req)\n    await future\n    assert ws.closed\n\n\ndef test_websocket_ready() -> None:\n    websocket_ready = WebSocketReady(True, \"chat\")\n    assert websocket_ready.ok is True\n    assert websocket_ready.protocol == \"chat\"\n\n\ndef test_websocket_not_ready() -> None:\n    websocket_ready = WebSocketReady(False, None)\n    assert websocket_ready.ok is False\n    assert websocket_ready.protocol is None\n\n\ndef test_websocket_ready_unknown_protocol() -> None:\n    websocket_ready = WebSocketReady(True, None)\n    assert websocket_ready.ok is True\n    assert websocket_ready.protocol is None\n\n\ndef test_bool_websocket_ready() -> None:\n    websocket_ready = WebSocketReady(True, None)\n    assert bool(websocket_ready) is True\n\n\ndef test_bool_websocket_not_ready() -> None:\n    websocket_ready = WebSocketReady(False, None)\n    assert bool(websocket_ready) is False\n\n\ndef test_can_prepare_ok(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\", protocols=True)\n    ws = web.WebSocketResponse(protocols=(\"chat\",))\n    assert WebSocketReady(True, \"chat\") == ws.can_prepare(req)\n\n\ndef test_can_prepare_unknown_protocol(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    assert WebSocketReady(True, None) == ws.can_prepare(req)\n\n\ndef test_can_prepare_without_upgrade(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\", headers=CIMultiDict({}))\n    ws = web.WebSocketResponse()\n    assert WebSocketReady(False, None) == ws.can_prepare(req)\n\n\nasync def test_can_prepare_started(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with pytest.raises(RuntimeError) as ctx:\n        ws.can_prepare(req)\n\n    assert \"Already started\" in str(ctx.value)\n\n\ndef test_closed_after_ctor() -> None:\n    ws = web.WebSocketResponse()\n    assert not ws.closed\n    assert ws.close_code is None\n\n\nasync def test_raise_writer_limit(make_request: _RequestMaker) -> None:\n    \"\"\"Test the writer limit can be adjusted.\"\"\"\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse(writer_limit=1234567)\n    await ws.prepare(req)\n    assert ws._reader is not None\n    assert ws._writer is not None\n    assert ws._writer._limit == 1234567\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n\nasync def test_send_str_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n    with pytest.raises(ConnectionError):\n        await ws.send_str(\"string\")\n\n\nasync def test_send_bytes_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.send_bytes(b\"bytes\")\n\n\nasync def test_send_json_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.send_json({\"type\": \"json\"})\n\n\nasync def test_send_frame_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.send_frame(b'{\"type\": \"json\"}', WSMsgType.TEXT)\n\n\nasync def test_ping_closed(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.ping()\n\n\nasync def test_pong_closed(make_request: _RequestMaker, mocker: MockerFixture) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    with pytest.raises(ConnectionError):\n        await ws.pong()\n\n\nasync def test_close_idempotent(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    close_code = await ws.close(code=1, message=b\"message1\")\n    assert close_code == 1\n    assert ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n    close_code = await ws.close(code=2, message=b\"message2\")\n    assert close_code == 0\n\n\nasync def test_prepare_post_method_ok(make_request: _RequestMaker) -> None:\n    req = make_request(\"POST\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws.prepared\n\n\nasync def test_prepare_without_upgrade(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\", headers=CIMultiDict({}))\n    ws = web.WebSocketResponse()\n    with pytest.raises(web.HTTPBadRequest):\n        await ws.prepare(req)\n\n\nasync def test_wait_closed_before_start() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.close()\n\n\nasync def test_write_eof_not_started() -> None:\n    ws = web.WebSocketResponse()\n    with pytest.raises(RuntimeError):\n        await ws.write_eof()\n\n\nasync def test_write_eof_idempotent(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    await ws.write_eof()\n    await ws.write_eof()\n    await ws.write_eof()\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n\nasync def test_receive_eofstream_in_reader(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n\n    ws._reader = mock.Mock()\n    exc = EofStream()\n    res = loop.create_future()\n    res.set_exception(exc)\n    ws._reader.read = make_mocked_coro(res)\n    assert ws._payload_writer is not None\n    f = loop.create_future()\n    f.set_result(True)\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n    assert ws.closed\n\n\nasync def test_receive_exception_in_reader(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n\n    ws._reader = mock.Mock()\n    exc = Exception()\n    res = loop.create_future()\n    res.set_exception(exc)\n    ws._reader.read = make_mocked_coro(res)\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.ERROR\n    assert ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n\nasync def test_receive_close_but_left_open(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    close_message = WSMessageClose(data=1000, extra=\"close\")\n\n    ws._reader = mock.Mock()\n    ws._reader.read = mock.AsyncMock(return_value=close_message)\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n    assert ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n\nasync def test_receive_closing(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    closing_message = WS_CLOSING_MESSAGE\n\n    ws._reader = mock.Mock()\n    read_mock = mock.AsyncMock(return_value=closing_message)\n    ws._reader.read = read_mock\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n    assert not ws.closed\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n    assert not ws.closed\n\n    ws._cancel(ConnectionResetError(\"Connection lost\"))\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n\n\nasync def test_close_after_closing(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    closing_message = WS_CLOSING_MESSAGE\n\n    ws._reader = mock.Mock()\n    ws._reader.read = mock.AsyncMock(return_value=closing_message)\n\n    f = loop.create_future()\n    assert ws._payload_writer is not None\n    ws._payload_writer.drain.return_value = f  # type: ignore[attr-defined]\n    f.set_result(True)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSING\n    assert not ws.closed\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    await ws.close()\n    assert ws.closed\n    assert len(req.transport.close.mock_calls) == 1\n\n\nasync def test_receive_timeouterror(\n    make_request: _RequestMaker, loop: asyncio.AbstractEventLoop\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    ws._reader = mock.Mock()\n    res = loop.create_future()\n    res.set_exception(asyncio.TimeoutError())\n    ws._reader.read = make_mocked_coro(res)\n\n    with pytest.raises(asyncio.TimeoutError):\n        await ws.receive()\n\n    # Should not close the connection on timeout\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n\nasync def test_multiple_receive_on_close_connection(\n    make_request: _RequestMaker,\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert ws._reader is not None\n    ws._reader.feed_data(WS_CLOSED_MESSAGE)\n    await ws.close()\n\n    await ws.receive()\n    await ws.receive()\n    await ws.receive()\n    await ws.receive()\n\n    with pytest.raises(RuntimeError):\n        await ws.receive()\n\n\nasync def test_concurrent_receive(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    ws._waiting = True\n\n    with pytest.raises(RuntimeError):\n        await ws.receive()\n\n\nasync def test_close_exc(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    assert req.transport is not None\n    assert len(req.transport.close.mock_calls) == 0  # type: ignore[attr-defined]\n\n    exc = ValueError()\n    ws._writer = mock.Mock()\n    ws._writer.close.side_effect = exc\n    await ws.close()\n    assert ws.closed\n    assert ws.exception() is exc\n    assert len(req.transport.close.mock_calls) == 1  # type: ignore[attr-defined]\n\n    ws._closed = False\n    ws._writer.close.side_effect = asyncio.CancelledError()\n    with pytest.raises(asyncio.CancelledError):\n        await ws.close()\n\n\nasync def test_prepare_twice_idempotent(make_request: _RequestMaker) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n\n    impl1 = await ws.prepare(req)\n    impl2 = await ws.prepare(req)\n    assert impl1 is impl2\n\n\nasync def test_send_with_per_message_deflate(\n    make_request: _RequestMaker, mocker: MockerFixture\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws.prepare(req)\n    with mock.patch.object(ws._writer, \"send_frame\", autospec=True, spec_set=True) as m:\n        await ws.send_str(\"string\", compress=15)\n        m.assert_called_with(b\"string\", WSMsgType.TEXT, compress=15)\n\n        await ws.send_bytes(b\"bytes\", compress=0)\n        m.assert_called_with(b\"bytes\", WSMsgType.BINARY, compress=0)\n\n        await ws.send_json(\"[{}]\", compress=9)\n        m.assert_called_with(b'\"[{}]\"', WSMsgType.TEXT, compress=9)\n\n        await ws.send_frame(b\"[{}]\", WSMsgType.TEXT, compress=9)\n        m.assert_called_with(b\"[{}]\", WSMsgType.TEXT, compress=9)\n\n\nasync def test_no_transfer_encoding_header(\n    make_request: _RequestMaker, mocker: MockerFixture\n) -> None:\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n    await ws._start(req)\n\n    assert \"Transfer-Encoding\" not in ws.headers\n\n\n@pytest.mark.parametrize(\n    \"ws_transport, expected_result\",\n    [\n        (\n            mock.MagicMock(\n                transport=mock.MagicMock(\n                    get_extra_info=lambda name, default=None: {\"test\": \"existent\"}.get(\n                        name, default\n                    )\n                )\n            ),\n            \"existent\",\n        ),\n        (None, \"default\"),\n        (mock.MagicMock(transport=None), \"default\"),\n    ],\n)\nasync def test_get_extra_info(\n    make_request: _RequestMaker,\n    mocker: MockerFixture,\n    ws_transport: Optional[mock.MagicMock],\n    expected_result: str,\n) -> None:\n    valid_key = \"test\"\n    default_value = \"default\"\n\n    req = make_request(\"GET\", \"/\")\n    ws = web.WebSocketResponse()\n\n    await ws.prepare(req)\n    ws._writer = ws_transport\n\n    assert ws.get_extra_info(valid_key, default_value) == expected_result\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, Callable, Iterator\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() -> trustme.CA:\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: trustme.CA) -> trustme.LeafCert:\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: trustme.LeafCert) -> ssl.SSLContext:\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: trustme.CA) -> ssl.SSLContext:\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: trustme.CA) -> Iterator[str]:\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: trustme.LeafCert) -> Iterator[str]:\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: trustme.LeafCert) -> bytes:\n    return tls_certificate.cert_chain_pems[0].bytes()\n\n\n@pytest.fixture\ndef tls_certificate_fingerprint_sha256(tls_certificate_pem_bytes: bytes) -> 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 pipe_name() -> str:\n    name = rf\"\\\\.\\pipe\\{uuid4().hex}\"\n    return name\n\n\n@pytest.fixture\ndef create_mocked_conn(\n    loop: asyncio.AbstractEventLoop,\n) -> Iterator[Callable[[], ResponseHandler]]:\n    def _proto_factory() -> Any:\n        proto = mock.create_autospec(ResponseHandler, instance=True)\n        proto.closed = loop.create_future()\n        proto.closed.set_result(None)\n        return proto\n\n    yield _proto_factory\n\n\n@pytest.fixture\ndef unix_sockname(\n    tmp_path: Path, tmp_path_factory: pytest.TempPathFactory\n) -> Iterator[str]:\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 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    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    # Ref: https://unix.stackexchange.com/a/367012/27133\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: Path) -> TemporaryDirectory[str]:\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: str) -> None:\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 tmps:\n            tmpd = Path(tmps).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 selector_loop() -> Iterator[asyncio.AbstractEventLoop]:\n    policy = asyncio.WindowsSelectorEventLoopPolicy()  # type: ignore[attr-defined]\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) -> Path:\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() -> Iterator[mock.Mock]:\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() -> bytes:\n    return os.urandom(16)\n\n\n@pytest.fixture\ndef key(key_data: bytes) -> bytes:\n    return base64.b64encode(key_data)\n\n\n@pytest.fixture\ndef ws_key(key: bytes) -> str:\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_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/requirements/cython.txt\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/tools/gen.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/hdrs.py\n./tools/gen.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_http_parser.pyx\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_http_writer.pyx\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_cparser.pxd\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_find_header.pxd\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_websocket/mask.pyx\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_websocket/mask.pxd\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/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_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/vendor/llhttp'\nnpx ts-node bin/generate.ts\nmake[1]: Leaving directory '/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/vendor/llhttp'\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/__init__.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/abc.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/base_protocol.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/client.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/client_exceptions.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/client_proto.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/client_reqrep.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/client_ws.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/compression_utils.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/connector.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/cookiejar.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/formdata.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/helpers.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/http.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/http_exceptions.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/http_parser.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/http_websocket.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/http_writer.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/log.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/multipart.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/payload.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/pytest_plugin.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/resolver.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/streams.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/tcp_helpers.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/test_utils.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/tracing.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/typedefs.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_app.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_exceptions.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_fileresponse.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_log.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_middlewares.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_protocol.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_request.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_response.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_routedef.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_runner.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_server.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_urldispatcher.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/web_ws.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/worker.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_websocket/__init__.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_websocket/helpers.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_websocket/models.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_websocket/reader.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_websocket/reader_c.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/aiohttp/_websocket/reader_py.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/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 2ms\nPrepared 1 package in 0.28ms\nInstalled 1 package in 15ms\n + pip==24.3.1\nResolved 3 packages in 11ms\nInstalled 3 packages in 31ms\n + cython==3.0.11\n + multidict==6.1.0\n + typing-extensions==4.12.2\nResolved 94 packages in 93ms\nInstalled 91 packages in 71ms\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 + 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.6\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.1.1\n + pytest-codspeed==2.2.1\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 + 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.15.2\n + zipp==3.20.2\nResolved 10 packages in 1.82s\n  × Failed to build `aiohttp @ file:///home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d`\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/.tmprSMnx6/.tmp-9c15i6d7/aiohttp.egg-info\n      writing /home/gcpuser/.cache/uv/builds-v0/.tmprSMnx6/.tmp-9c15i6d7/aiohttp.egg-info/PKG-INFO\n      writing dependency_links to /home/gcpuser/.cache/uv/builds-v0/.tmprSMnx6/.tmp-9c15i6d7/aiohttp.egg-info/dependency_links.txt\n      writing requirements to /home/gcpuser/.cache/uv/builds-v0/.tmprSMnx6/.tmp-9c15i6d7/aiohttp.egg-info/requires.txt\n      writing top-level names to /home/gcpuser/.cache/uv/builds-v0/.tmprSMnx6/.tmp-9c15i6d7/aiohttp.egg-info/top_level.txt\n      writing manifest file '/home/gcpuser/.cache/uv/builds-v0/.tmprSMnx6/.tmp-9c15i6d7/aiohttp.egg-info/SOURCES.txt'\n      reading manifest file '/home/gcpuser/.cache/uv/builds-v0/.tmprSMnx6/.tmp-9c15i6d7/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/.tmprSMnx6/.tmp-9c15i6d7/aiohttp.egg-info/SOURCES.txt'\n      creating '/home/gcpuser/.cache/uv/builds-v0/.tmprSMnx6/.tmp-9c15i6d7/aiohttp-4.0.0a2.dev0.dist-info'\n      creating /home/gcpuser/.cache/uv/builds-v0/.tmprSMnx6/.tmp-9c15i6d7/aiohttp-4.0.0a2.dev0.dist-info/WHEEL\n      running build_py\n      running build_ext\n      building 'aiohttp._websocket.mask' extension\n      creating /tmp/tmp376tnqj5.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/.tmpbZkfwo/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/tmp376tnqj5.build-temp/aiohttp/_websocket/mask.o\n      creating /tmp/tmpgnwuytkz.build-lib/aiohttp/_websocket\n      cc -pthread -shared -Wl,--exclude-libs,ALL /tmp/tmp376tnqj5.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/tmpgnwuytkz.build-lib/aiohttp/_websocket/mask.cpython-39-x86_64-linux-gnu.so\n      building 'aiohttp._http_parser' extension\n      creating /tmp/tmp376tnqj5.build-temp/vendor/llhttp/build/c\n      creating /tmp/tmp376tnqj5.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/.tmpbZkfwo/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/tmp376tnqj5.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/.tmpbZkfwo/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/tmp376tnqj5.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/.tmpbZkfwo/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/tmp376tnqj5.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/.tmpbZkfwo/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/tmp376tnqj5.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/.tmpbZkfwo/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/tmp376tnqj5.build-temp/vendor/llhttp/src/native/http.o\n      cc -pthread -shared -Wl,--exclude-libs,ALL /tmp/tmp376tnqj5.build-temp/aiohttp/_find_header.o /tmp/tmp376tnqj5.build-temp/aiohttp/_http_parser.o\n      /tmp/tmp376tnqj5.build-temp/vendor/llhttp/build/c/llhttp.o /tmp/tmp376tnqj5.build-temp/vendor/llhttp/src/native/api.o\n      /tmp/tmp376tnqj5.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/tmpgnwuytkz.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/.tmpbZkfwo/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/tmp376tnqj5.build-temp/aiohttp/_http_writer.o\n      cc -pthread -shared -Wl,--exclude-libs,ALL /tmp/tmp376tnqj5.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/tmpgnwuytkz.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/.tmpbZkfwo/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/tmp376tnqj5.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/.tmpbZkfwo/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/.tmpbZkfwo/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/tmp376tnqj5.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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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/.tmpbZkfwo/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.23.8\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.1.1, pluggy-1.5.0 -- /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/.venv/bin/python\ncodspeed: 2.2.1 (callgraph: not supported)\ncachedir: .pytest_cache\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d\nconfigfile: setup.cfg\nplugins: cov-5.0.0, mock-3.14.0, asyncio-0.23.8, codspeed-2.2.1\nasyncio: mode=strict\ncollecting ... collected 53 items\n\nr2e_tests/test_1.py::test_nonstarted_ping PASSED                         [  1%]\nr2e_tests/test_1.py::test_nonstarted_pong PASSED                         [  3%]\nr2e_tests/test_1.py::test_nonstarted_send_frame PASSED                   [  5%]\nr2e_tests/test_1.py::test_nonstarted_send_str PASSED                     [  7%]\nr2e_tests/test_1.py::test_nonstarted_send_bytes PASSED                   [  9%]\nr2e_tests/test_1.py::test_nonstarted_send_json PASSED                    [ 11%]\nr2e_tests/test_1.py::test_nonstarted_close PASSED                        [ 13%]\nr2e_tests/test_1.py::test_nonstarted_receive_str PASSED                  [ 15%]\nr2e_tests/test_1.py::test_nonstarted_receive_bytes PASSED                [ 16%]\nr2e_tests/test_1.py::test_nonstarted_receive_json PASSED                 [ 18%]\nr2e_tests/test_1.py::test_send_str_nonstring[pyloop] PASSED              [ 20%]\nr2e_tests/test_1.py::test_send_bytes_nonbytes[pyloop] PASSED             [ 22%]\nr2e_tests/test_1.py::test_send_json_nonjson[pyloop] PASSED               [ 24%]\nr2e_tests/test_1.py::test_write_non_prepared PASSED                      [ 26%]\nr2e_tests/test_1.py::test_heartbeat_timeout[pyloop] PASSED               [ 28%]\nr2e_tests/test_1.py::test_websocket_ready PASSED                         [ 30%]\nr2e_tests/test_1.py::test_websocket_not_ready PASSED                     [ 32%]\nr2e_tests/test_1.py::test_websocket_ready_unknown_protocol PASSED        [ 33%]\nr2e_tests/test_1.py::test_bool_websocket_ready PASSED                    [ 35%]\nr2e_tests/test_1.py::test_bool_websocket_not_ready PASSED                [ 37%]\nr2e_tests/test_1.py::test_can_prepare_ok[pyloop] PASSED                  [ 39%]\nr2e_tests/test_1.py::test_can_prepare_unknown_protocol[pyloop] PASSED    [ 41%]\nr2e_tests/test_1.py::test_can_prepare_without_upgrade[pyloop] PASSED     [ 43%]\nr2e_tests/test_1.py::test_can_prepare_started[pyloop] PASSED             [ 45%]\nr2e_tests/test_1.py::test_closed_after_ctor PASSED                       [ 47%]\nr2e_tests/test_1.py::test_raise_writer_limit[pyloop] PASSED              [ 49%]\nr2e_tests/test_1.py::test_send_str_closed[pyloop] PASSED                 [ 50%]\nr2e_tests/test_1.py::test_send_bytes_closed[pyloop] PASSED               [ 52%]\nr2e_tests/test_1.py::test_send_json_closed[pyloop] PASSED                [ 54%]\nr2e_tests/test_1.py::test_send_frame_closed[pyloop] PASSED               [ 56%]\nr2e_tests/test_1.py::test_ping_closed[pyloop] PASSED                     [ 58%]\nr2e_tests/test_1.py::test_pong_closed[pyloop] PASSED                     [ 60%]\nr2e_tests/test_1.py::test_close_idempotent[pyloop] PASSED                [ 62%]\nr2e_tests/test_1.py::test_prepare_post_method_ok[pyloop] PASSED          [ 64%]\nr2e_tests/test_1.py::test_prepare_without_upgrade[pyloop] PASSED         [ 66%]\nr2e_tests/test_1.py::test_wait_closed_before_start PASSED                [ 67%]\nr2e_tests/test_1.py::test_write_eof_not_started PASSED                   [ 69%]\nr2e_tests/test_1.py::test_write_eof_idempotent[pyloop] PASSED            [ 71%]\nr2e_tests/test_1.py::test_receive_eofstream_in_reader[pyloop] PASSED     [ 73%]\nr2e_tests/test_1.py::test_receive_exception_in_reader[pyloop] PASSED     [ 75%]\nr2e_tests/test_1.py::test_receive_close_but_left_open[pyloop] PASSED     [ 77%]\nr2e_tests/test_1.py::test_receive_closing[pyloop] PASSED                 [ 79%]\nr2e_tests/test_1.py::test_close_after_closing[pyloop] PASSED             [ 81%]\nr2e_tests/test_1.py::test_receive_timeouterror[pyloop] PASSED            [ 83%]\nr2e_tests/test_1.py::test_multiple_receive_on_close_connection[pyloop] PASSED [ 84%]\nr2e_tests/test_1.py::test_concurrent_receive[pyloop] PASSED              [ 86%]\nr2e_tests/test_1.py::test_close_exc[pyloop] PASSED                       [ 88%]\nr2e_tests/test_1.py::test_prepare_twice_idempotent[pyloop] PASSED        [ 90%]\nr2e_tests/test_1.py::test_send_with_per_message_deflate[pyloop] PASSED   [ 92%]\nr2e_tests/test_1.py::test_no_transfer_encoding_header[pyloop] PASSED     [ 94%]\nr2e_tests/test_1.py::test_get_extra_info[pyloop-ws_transport0-existent] PASSED [ 96%]\nr2e_tests/test_1.py::test_get_extra_info[pyloop-None-default] PASSED     [ 98%]\nr2e_tests/test_1.py::test_get_extra_info[pyloop-ws_transport2-default] 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                          26     10      2      0    57%\naiohttp/_websocket/__init__.py                0      0      0      0   100%\naiohttp/_websocket/helpers.py                77     50     38      1    24%\naiohttp/_websocket/models.py                 78      5      0      0    94%\naiohttp/_websocket/reader.py                  5      0      0      0   100%\naiohttp/_websocket/reader_py.py             201    155     84      0    17%\naiohttp/_websocket/writer.py                 75     31     24      4    51%\naiohttp/abc.py                               98      7      0      0    93%\naiohttp/base_protocol.py                     68     51     22      0    19%\naiohttp/client.py                           528    388    194      2    20%\naiohttp/client_exceptions.py                140     59     14      0    53%\naiohttp/client_proto.py                     169    136     58      0    15%\naiohttp/client_reqrep.py                    668    497    276      0    19%\naiohttp/client_ws.py                        272    215     82      1    17%\naiohttp/compression_utils.py                 70     36     14      0    40%\naiohttp/connector.py                        732    596    319      1    13%\naiohttp/cookiejar.py                        272    216    132      0    14%\naiohttp/formdata.py                          88     71     40      0    13%\naiohttp/hdrs.py                              90      0      0      0   100%\naiohttp/helpers.py                          519    321    196      5    31%\naiohttp/http.py                               8      0      0      0   100%\naiohttp/http_exceptions.py                   48     18      2      0    60%\naiohttp/http_parser.py                      496    401    208      1    14%\naiohttp/http_websocket.py                     5      0      0      0   100%\naiohttp/http_writer.py                      119     82     50      0    22%\naiohttp/log.py                                7      0      0      0   100%\naiohttp/multipart.py                        625    510    268      1    13%\naiohttp/payload.py                          237    113     58      1    44%\naiohttp/pytest_plugin.py                    161     73     42      5    53%\naiohttp/resolver.py                          62     42     18      0    25%\naiohttp/streams.py                          401    298    142      2    19%\naiohttp/tcp_helpers.py                       19     11      6      0    32%\naiohttp/test_utils.py                       303    139     52     11    52%\naiohttp/tracing.py                          193     69     32      0    69%\naiohttp/typedefs.py                          24      0      0      0   100%\naiohttp/web.py                              128     90     54      0    22%\naiohttp/web_app.py                          237    150     50      0    31%\naiohttp/web_exceptions.py                   216     38     28      6    79%\naiohttp/web_fileresponse.py                 160    126     52      0    18%\naiohttp/web_log.py                           96     52     14      0    40%\naiohttp/web_middlewares.py                   58     44     22      0    18%\naiohttp/web_protocol.py                     376    311    158      0    13%\naiohttp/web_request.py                      444    258    142      9    34%\naiohttp/web_response.py                     441    260    198     12    32%\naiohttp/web_routedef.py                     100     44     10      0    55%\naiohttp/web_runner.py                       222    132     40      0    34%\naiohttp/web_server.py                        49     26     14      0    37%\naiohttp/web_urldispatcher.py                719    447    155      2    31%\naiohttp/web_ws.py                           391     72    134     23    78%\naiohttp/worker.py                           123    123     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_request.py      13     13      0      0     0%\ntests/test_benchmarks_cookiejar.py           14     14      0      0     0%\ntests/test_benchmarks_http_websocket.py      38     38      6      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              98     98      0      0     0%\ntests/test_client_exceptions.py             182    182     14      0     0%\ntests/test_client_fingerprint.py             23     23      0      0     0%\ntests/test_client_functional.py            2629   2629     74      0     0%\ntests/test_client_proto.py                  103    103      0      0     0%\ntests/test_client_request.py                799    799     18      0     0%\ntests/test_client_response.py               502    502      6      0     0%\ntests/test_client_session.py                588    588     29      0     0%\ntests/test_client_ws.py                     489    489      2      0     0%\ntests/test_client_ws_functional.py          804    804     22      0     0%\ntests/test_connector.py                    1852   1852    102      0     0%\ntests/test_cookiejar.py                     469    469     28      0     0%\ntests/test_flowcontrol_streams.py            98     98      0      0     0%\ntests/test_formdata.py                       92     92      4      0     0%\ntests/test_helpers.py                       553    553     20      0     0%\ntests/test_http_exceptions.py               110    110     10      0     0%\ntests/test_http_parser.py                  1091   1091     44      0     0%\ntests/test_http_writer.py                   178    178     10      0     0%\ntests/test_imports.py                        34     34      6      0     0%\ntests/test_loop.py                           35     35      0      0     0%\ntests/test_multipart.py                     869    869     34      0     0%\ntests/test_multipart_helpers.py             446    446      0      0     0%\ntests/test_payload.py                        81     81      0      0     0%\ntests/test_proxy.py                         358    358      2      0     0%\ntests/test_proxy_functional.py              465    465     20      0     0%\ntests/test_pytest_plugin.py                  47     47      0      0     0%\ntests/test_resolver.py                      201    201     18      0     0%\ntests/test_route_def.py                     191    191      0      0     0%\ntests/test_run_app.py                       576    576     30      0     0%\ntests/test_streams.py                      1061   1061     38      0     0%\ntests/test_tcp_helpers.py                    52     52      2      0     0%\ntests/test_test_utils.py                    257    257     12      0     0%\ntests/test_tracing.py                        49     49      0      0     0%\ntests/test_urldispatch.py                   862    862     24      0     0%\ntests/test_web_app.py                       384    384      6      0     0%\ntests/test_web_cli.py                        94     94      0      0     0%\ntests/test_web_exceptions.py                277    277     30      0     0%\ntests/test_web_functional.py               1557   1557     24      0     0%\ntests/test_web_log.py                       145    145      4      0     0%\ntests/test_web_middleware.py                245    245      6      0     0%\ntests/test_web_request.py                   544    544      0      0     0%\ntests/test_web_request_handler.py            42     42      0      0     0%\ntests/test_web_response.py                  872    872      6      0     0%\ntests/test_web_runner.py                    179    179      4      0     0%\ntests/test_web_sendfile.py                   85     85      0      0     0%\ntests/test_web_sendfile_functional.py       681    681     18      0     0%\ntests/test_web_server.py                    179    179      0      0     0%\ntests/test_web_urldispatcher.py             511    511     24      0     0%\ntests/test_web_websocket.py                 432    432      8      0     0%\ntests/test_web_websocket_functional.py      831    831     24      0     0%\ntests/test_websocket_handshake.py           153    153     12      0     0%\ntests/test_websocket_parser.py              310    310     12      0     0%\ntests/test_websocket_writer.py               97     97      6      0     0%\ntests/test_worker.py                        190    190      2      0     0%\n---------------------------------------------------------------------------\nTOTAL                                     35158  31287   4266     87    11%\n\n============================= slowest 10 durations =============================\n0.04s setup    r2e_tests/test_1.py::test_send_str_nonstring[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_get_extra_info[pyloop-None-default]\n0.03s setup    r2e_tests/test_1.py::test_close_exc[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_send_with_per_message_deflate[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_no_transfer_encoding_header[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_raise_writer_limit[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_get_extra_info[pyloop-ws_transport2-default]\n0.03s setup    r2e_tests/test_1.py::test_send_bytes_nonbytes[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_get_extra_info[pyloop-ws_transport0-existent]\n0.03s setup    r2e_tests/test_1.py::test_concurrent_receive[pyloop]\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_nonstarted_ping\nPASSED r2e_tests/test_1.py::test_nonstarted_pong\nPASSED r2e_tests/test_1.py::test_nonstarted_send_frame\nPASSED r2e_tests/test_1.py::test_nonstarted_send_str\nPASSED r2e_tests/test_1.py::test_nonstarted_send_bytes\nPASSED r2e_tests/test_1.py::test_nonstarted_send_json\nPASSED r2e_tests/test_1.py::test_nonstarted_close\nPASSED r2e_tests/test_1.py::test_nonstarted_receive_str\nPASSED r2e_tests/test_1.py::test_nonstarted_receive_bytes\nPASSED r2e_tests/test_1.py::test_nonstarted_receive_json\nPASSED r2e_tests/test_1.py::test_send_str_nonstring[pyloop]\nPASSED r2e_tests/test_1.py::test_send_bytes_nonbytes[pyloop]\nPASSED r2e_tests/test_1.py::test_send_json_nonjson[pyloop]\nPASSED r2e_tests/test_1.py::test_write_non_prepared\nPASSED r2e_tests/test_1.py::test_heartbeat_timeout[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_ready\nPASSED r2e_tests/test_1.py::test_websocket_not_ready\nPASSED r2e_tests/test_1.py::test_websocket_ready_unknown_protocol\nPASSED r2e_tests/test_1.py::test_bool_websocket_ready\nPASSED r2e_tests/test_1.py::test_bool_websocket_not_ready\nPASSED r2e_tests/test_1.py::test_can_prepare_ok[pyloop]\nPASSED r2e_tests/test_1.py::test_can_prepare_unknown_protocol[pyloop]\nPASSED r2e_tests/test_1.py::test_can_prepare_without_upgrade[pyloop]\nPASSED r2e_tests/test_1.py::test_can_prepare_started[pyloop]\nPASSED r2e_tests/test_1.py::test_closed_after_ctor\nPASSED r2e_tests/test_1.py::test_raise_writer_limit[pyloop]\nPASSED r2e_tests/test_1.py::test_send_str_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_send_bytes_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_send_json_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_send_frame_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_ping_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_pong_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_close_idempotent[pyloop]\nPASSED r2e_tests/test_1.py::test_prepare_post_method_ok[pyloop]\nPASSED r2e_tests/test_1.py::test_prepare_without_upgrade[pyloop]\nPASSED r2e_tests/test_1.py::test_wait_closed_before_start\nPASSED r2e_tests/test_1.py::test_write_eof_not_started\nPASSED r2e_tests/test_1.py::test_write_eof_idempotent[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_eofstream_in_reader[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_exception_in_reader[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_close_but_left_open[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_closing[pyloop]\nPASSED r2e_tests/test_1.py::test_close_after_closing[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_timeouterror[pyloop]\nPASSED r2e_tests/test_1.py::test_multiple_receive_on_close_connection[pyloop]\nPASSED r2e_tests/test_1.py::test_concurrent_receive[pyloop]\nPASSED r2e_tests/test_1.py::test_close_exc[pyloop]\nPASSED r2e_tests/test_1.py::test_prepare_twice_idempotent[pyloop]\nPASSED r2e_tests/test_1.py::test_send_with_per_message_deflate[pyloop]\nPASSED r2e_tests/test_1.py::test_no_transfer_encoding_header[pyloop]\nPASSED r2e_tests/test_1.py::test_get_extra_info[pyloop-ws_transport0-existent]\nPASSED r2e_tests/test_1.py::test_get_extra_info[pyloop-None-default]\nPASSED r2e_tests/test_1.py::test_get_extra_info[pyloop-ws_transport2-default]\n============================== 53 passed in 6.75s ==============================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.1.1, pluggy-1.5.0 -- /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d/.venv/bin/python\ncodspeed: 2.2.1 (callgraph: not supported)\ncachedir: .pytest_cache\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_e36c5f0ffeeea0076736c5756d63f5933c91eb8d\nconfigfile: setup.cfg\nplugins: cov-5.0.0, mock-3.14.0, asyncio-0.23.8, codspeed-2.2.1\nasyncio: mode=strict\ncollecting ... collected 53 items\n\nr2e_tests/test_1.py::test_nonstarted_ping PASSED                         [  1%]\nr2e_tests/test_1.py::test_nonstarted_pong PASSED                         [  3%]\nr2e_tests/test_1.py::test_nonstarted_send_frame PASSED                   [  5%]\nr2e_tests/test_1.py::test_nonstarted_send_str PASSED                     [  7%]\nr2e_tests/test_1.py::test_nonstarted_send_bytes PASSED                   [  9%]\nr2e_tests/test_1.py::test_nonstarted_send_json PASSED                    [ 11%]\nr2e_tests/test_1.py::test_nonstarted_close PASSED                        [ 13%]\nr2e_tests/test_1.py::test_nonstarted_receive_str PASSED                  [ 15%]\nr2e_tests/test_1.py::test_nonstarted_receive_bytes PASSED                [ 16%]\nr2e_tests/test_1.py::test_nonstarted_receive_json PASSED                 [ 18%]\nr2e_tests/test_1.py::test_send_str_nonstring[pyloop] PASSED              [ 20%]\nr2e_tests/test_1.py::test_send_bytes_nonbytes[pyloop] PASSED             [ 22%]\nr2e_tests/test_1.py::test_send_json_nonjson[pyloop] PASSED               [ 24%]\nr2e_tests/test_1.py::test_write_non_prepared PASSED                      [ 26%]\nr2e_tests/test_1.py::test_heartbeat_timeout[pyloop] PASSED               [ 28%]\nr2e_tests/test_1.py::test_websocket_ready PASSED                         [ 30%]\nr2e_tests/test_1.py::test_websocket_not_ready PASSED                     [ 32%]\nr2e_tests/test_1.py::test_websocket_ready_unknown_protocol PASSED        [ 33%]\nr2e_tests/test_1.py::test_bool_websocket_ready PASSED                    [ 35%]\nr2e_tests/test_1.py::test_bool_websocket_not_ready PASSED                [ 37%]\nr2e_tests/test_1.py::test_can_prepare_ok[pyloop] PASSED                  [ 39%]\nr2e_tests/test_1.py::test_can_prepare_unknown_protocol[pyloop] PASSED    [ 41%]\nr2e_tests/test_1.py::test_can_prepare_without_upgrade[pyloop] PASSED     [ 43%]\nr2e_tests/test_1.py::test_can_prepare_started[pyloop] PASSED             [ 45%]\nr2e_tests/test_1.py::test_closed_after_ctor PASSED                       [ 47%]\nr2e_tests/test_1.py::test_raise_writer_limit[pyloop] FAILED              [ 49%]\nr2e_tests/test_1.py::test_send_str_closed[pyloop] PASSED                 [ 50%]\nr2e_tests/test_1.py::test_send_bytes_closed[pyloop] PASSED               [ 52%]\nr2e_tests/test_1.py::test_send_json_closed[pyloop] PASSED                [ 54%]\nr2e_tests/test_1.py::test_send_frame_closed[pyloop] PASSED               [ 56%]\nr2e_tests/test_1.py::test_ping_closed[pyloop] PASSED                     [ 58%]\nr2e_tests/test_1.py::test_pong_closed[pyloop] PASSED                     [ 60%]\nr2e_tests/test_1.py::test_close_idempotent[pyloop] PASSED                [ 62%]\nr2e_tests/test_1.py::test_prepare_post_method_ok[pyloop] PASSED          [ 64%]\nr2e_tests/test_1.py::test_prepare_without_upgrade[pyloop] PASSED         [ 66%]\nr2e_tests/test_1.py::test_wait_closed_before_start PASSED                [ 67%]\nr2e_tests/test_1.py::test_write_eof_not_started PASSED                   [ 69%]\nr2e_tests/test_1.py::test_write_eof_idempotent[pyloop] PASSED            [ 71%]\nr2e_tests/test_1.py::test_receive_eofstream_in_reader[pyloop] PASSED     [ 73%]\nr2e_tests/test_1.py::test_receive_exception_in_reader[pyloop] PASSED     [ 75%]\nr2e_tests/test_1.py::test_receive_close_but_left_open[pyloop] PASSED     [ 77%]\nr2e_tests/test_1.py::test_receive_closing[pyloop] PASSED                 [ 79%]\nr2e_tests/test_1.py::test_close_after_closing[pyloop] PASSED             [ 81%]\nr2e_tests/test_1.py::test_receive_timeouterror[pyloop] PASSED            [ 83%]\nr2e_tests/test_1.py::test_multiple_receive_on_close_connection[pyloop] PASSED [ 84%]\nr2e_tests/test_1.py::test_concurrent_receive[pyloop] PASSED              [ 86%]\nr2e_tests/test_1.py::test_close_exc[pyloop] PASSED                       [ 88%]\nr2e_tests/test_1.py::test_prepare_twice_idempotent[pyloop] PASSED        [ 90%]\nr2e_tests/test_1.py::test_send_with_per_message_deflate[pyloop] PASSED   [ 92%]\nr2e_tests/test_1.py::test_no_transfer_encoding_header[pyloop] PASSED     [ 94%]\nr2e_tests/test_1.py::test_get_extra_info[pyloop-ws_transport0-existent] PASSED [ 96%]\nr2e_tests/test_1.py::test_get_extra_info[pyloop-None-default] PASSED     [ 98%]\nr2e_tests/test_1.py::test_get_extra_info[pyloop-ws_transport2-default] PASSED [100%]\n\n=================================== FAILURES ===================================\n_______________________ test_raise_writer_limit[pyloop] ________________________\n\nmake_request = <function make_request.<locals>.maker at 0x7376ab146040>\n\n    async def test_raise_writer_limit(make_request: _RequestMaker) -> None:\n        \"\"\"Test the writer limit can be adjusted.\"\"\"\n        req = make_request(\"GET\", \"/\")\n>       ws = web.WebSocketResponse(writer_limit=1234567)\nE       TypeError: __init__() got an unexpected keyword argument 'writer_limit'\n\nmake_request = <function make_request.<locals>.maker at 0x7376ab146040>\nreq        = <Request GET / >\n\nr2e_tests/test_1.py:243: TypeError\n==================================== PASSES ====================================\n\n---------- coverage: platform linux, python 3.9.21-final-0 -----------\nName                                      Stmts   Miss Branch BrPart  Cover\n---------------------------------------------------------------------------\naiohttp/__init__.py                          26     10      2      0    57%\naiohttp/_websocket/__init__.py                0      0      0      0   100%\naiohttp/_websocket/helpers.py                77     50     38      1    24%\naiohttp/_websocket/models.py                 78      5      0      0    94%\naiohttp/_websocket/reader.py                  5      0      0      0   100%\naiohttp/_websocket/reader_py.py             201    155     84      0    17%\naiohttp/_websocket/writer.py                 75     31     24      4    51%\naiohttp/abc.py                               98      7      0      0    93%\naiohttp/base_protocol.py                     68     51     22      0    19%\naiohttp/client.py                           528    388    194      2    20%\naiohttp/client_exceptions.py                140     59     14      0    53%\naiohttp/client_proto.py                     169    136     58      0    15%\naiohttp/client_reqrep.py                    668    497    276      0    19%\naiohttp/client_ws.py                        272    215     82      1    17%\naiohttp/compression_utils.py                 70     36     14      0    40%\naiohttp/connector.py                        732    596    319      1    13%\naiohttp/cookiejar.py                        272    216    132      0    14%\naiohttp/formdata.py                          88     71     40      0    13%\naiohttp/hdrs.py                              90      0      0      0   100%\naiohttp/helpers.py                          519    321    196      5    31%\naiohttp/http.py                               8      0      0      0   100%\naiohttp/http_exceptions.py                   48     18      2      0    60%\naiohttp/http_parser.py                      496    401    208      1    14%\naiohttp/http_websocket.py                     5      0      0      0   100%\naiohttp/http_writer.py                      119     82     50      0    22%\naiohttp/log.py                                7      0      0      0   100%\naiohttp/multipart.py                        625    510    268      1    13%\naiohttp/payload.py                          237    113     58      1    44%\naiohttp/pytest_plugin.py                    161     72     42      5    53%\naiohttp/resolver.py                          62     42     18      0    25%\naiohttp/streams.py                          401    298    142      2    19%\naiohttp/tcp_helpers.py                       19     11      6      0    32%\naiohttp/test_utils.py                       303    139     52     11    52%\naiohttp/tracing.py                          193     69     32      0    69%\naiohttp/typedefs.py                          24      0      0      0   100%\naiohttp/web.py                              128     90     54      0    22%\naiohttp/web_app.py                          237    150     50      0    31%\naiohttp/web_exceptions.py                   216     38     28      6    79%\naiohttp/web_fileresponse.py                 160    126     52      0    18%\naiohttp/web_log.py                           96     52     14      0    40%\naiohttp/web_middlewares.py                   58     44     22      0    18%\naiohttp/web_protocol.py                     376    311    158      0    13%\naiohttp/web_request.py                      444    255    142      9    35%\naiohttp/web_response.py                     441    260    198     12    32%\naiohttp/web_routedef.py                     100     44     10      0    55%\naiohttp/web_runner.py                       222    132     40      0    34%\naiohttp/web_server.py                        49     26     14      0    37%\naiohttp/web_urldispatcher.py                719    447    155      2    31%\naiohttp/web_ws.py                           389     72    134     23    78%\naiohttp/worker.py                           123    123     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_request.py      13     13      0      0     0%\ntests/test_benchmarks_cookiejar.py           14     14      0      0     0%\ntests/test_benchmarks_http_websocket.py      38     38      6      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              98     98      0      0     0%\ntests/test_client_exceptions.py             182    182     14      0     0%\ntests/test_client_fingerprint.py             23     23      0      0     0%\ntests/test_client_functional.py            2629   2629     74      0     0%\ntests/test_client_proto.py                  103    103      0      0     0%\ntests/test_client_request.py                799    799     18      0     0%\ntests/test_client_response.py               502    502      6      0     0%\ntests/test_client_session.py                588    588     29      0     0%\ntests/test_client_ws.py                     489    489      2      0     0%\ntests/test_client_ws_functional.py          804    804     22      0     0%\ntests/test_connector.py                    1852   1852    102      0     0%\ntests/test_cookiejar.py                     469    469     28      0     0%\ntests/test_flowcontrol_streams.py            98     98      0      0     0%\ntests/test_formdata.py                       92     92      4      0     0%\ntests/test_helpers.py                       553    553     20      0     0%\ntests/test_http_exceptions.py               110    110     10      0     0%\ntests/test_http_parser.py                  1091   1091     44      0     0%\ntests/test_http_writer.py                   178    178     10      0     0%\ntests/test_imports.py                        34     34      6      0     0%\ntests/test_loop.py                           35     35      0      0     0%\ntests/test_multipart.py                     869    869     34      0     0%\ntests/test_multipart_helpers.py             446    446      0      0     0%\ntests/test_payload.py                        81     81      0      0     0%\ntests/test_proxy.py                         358    358      2      0     0%\ntests/test_proxy_functional.py              465    465     20      0     0%\ntests/test_pytest_plugin.py                  47     47      0      0     0%\ntests/test_resolver.py                      201    201     18      0     0%\ntests/test_route_def.py                     191    191      0      0     0%\ntests/test_run_app.py                       576    576     30      0     0%\ntests/test_streams.py                      1061   1061     38      0     0%\ntests/test_tcp_helpers.py                    52     52      2      0     0%\ntests/test_test_utils.py                    257    257     12      0     0%\ntests/test_tracing.py                        49     49      0      0     0%\ntests/test_urldispatch.py                   862    862     24      0     0%\ntests/test_web_app.py                       384    384      6      0     0%\ntests/test_web_cli.py                        94     94      0      0     0%\ntests/test_web_exceptions.py                277    277     30      0     0%\ntests/test_web_functional.py               1557   1557     24      0     0%\ntests/test_web_log.py                       145    145      4      0     0%\ntests/test_web_middleware.py                245    245      6      0     0%\ntests/test_web_request.py                   544    544      0      0     0%\ntests/test_web_request_handler.py            42     42      0      0     0%\ntests/test_web_response.py                  872    872      6      0     0%\ntests/test_web_runner.py                    179    179      4      0     0%\ntests/test_web_sendfile.py                   85     85      0      0     0%\ntests/test_web_sendfile_functional.py       681    681     18      0     0%\ntests/test_web_server.py                    179    179      0      0     0%\ntests/test_web_urldispatcher.py             511    511     24      0     0%\ntests/test_web_websocket.py                 423    423      8      0     0%\ntests/test_web_websocket_functional.py      831    831     24      0     0%\ntests/test_websocket_handshake.py           153    153     12      0     0%\ntests/test_websocket_parser.py              310    310     12      0     0%\ntests/test_websocket_writer.py               97     97      6      0     0%\ntests/test_worker.py                        190    190      2      0     0%\n---------------------------------------------------------------------------\nTOTAL                                     35147  31274   4266     87    11%\n\n============================= slowest 10 durations =============================\n0.03s setup    r2e_tests/test_1.py::test_send_str_nonstring[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_receive_close_but_left_open[pyloop]\n0.03s teardown r2e_tests/test_1.py::test_multiple_receive_on_close_connection[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_can_prepare_ok[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_pong_closed[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_send_bytes_nonbytes[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_receive_closing[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_send_json_nonjson[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_send_with_per_message_deflate[pyloop]\n0.03s setup    r2e_tests/test_1.py::test_get_extra_info[pyloop-ws_transport0-existent]\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_nonstarted_ping\nPASSED r2e_tests/test_1.py::test_nonstarted_pong\nPASSED r2e_tests/test_1.py::test_nonstarted_send_frame\nPASSED r2e_tests/test_1.py::test_nonstarted_send_str\nPASSED r2e_tests/test_1.py::test_nonstarted_send_bytes\nPASSED r2e_tests/test_1.py::test_nonstarted_send_json\nPASSED r2e_tests/test_1.py::test_nonstarted_close\nPASSED r2e_tests/test_1.py::test_nonstarted_receive_str\nPASSED r2e_tests/test_1.py::test_nonstarted_receive_bytes\nPASSED r2e_tests/test_1.py::test_nonstarted_receive_json\nPASSED r2e_tests/test_1.py::test_send_str_nonstring[pyloop]\nPASSED r2e_tests/test_1.py::test_send_bytes_nonbytes[pyloop]\nPASSED r2e_tests/test_1.py::test_send_json_nonjson[pyloop]\nPASSED r2e_tests/test_1.py::test_write_non_prepared\nPASSED r2e_tests/test_1.py::test_heartbeat_timeout[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_ready\nPASSED r2e_tests/test_1.py::test_websocket_not_ready\nPASSED r2e_tests/test_1.py::test_websocket_ready_unknown_protocol\nPASSED r2e_tests/test_1.py::test_bool_websocket_ready\nPASSED r2e_tests/test_1.py::test_bool_websocket_not_ready\nPASSED r2e_tests/test_1.py::test_can_prepare_ok[pyloop]\nPASSED r2e_tests/test_1.py::test_can_prepare_unknown_protocol[pyloop]\nPASSED r2e_tests/test_1.py::test_can_prepare_without_upgrade[pyloop]\nPASSED r2e_tests/test_1.py::test_can_prepare_started[pyloop]\nPASSED r2e_tests/test_1.py::test_closed_after_ctor\nPASSED r2e_tests/test_1.py::test_send_str_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_send_bytes_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_send_json_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_send_frame_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_ping_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_pong_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_close_idempotent[pyloop]\nPASSED r2e_tests/test_1.py::test_prepare_post_method_ok[pyloop]\nPASSED r2e_tests/test_1.py::test_prepare_without_upgrade[pyloop]\nPASSED r2e_tests/test_1.py::test_wait_closed_before_start\nPASSED r2e_tests/test_1.py::test_write_eof_not_started\nPASSED r2e_tests/test_1.py::test_write_eof_idempotent[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_eofstream_in_reader[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_exception_in_reader[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_close_but_left_open[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_closing[pyloop]\nPASSED r2e_tests/test_1.py::test_close_after_closing[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_timeouterror[pyloop]\nPASSED r2e_tests/test_1.py::test_multiple_receive_on_close_connection[pyloop]\nPASSED r2e_tests/test_1.py::test_concurrent_receive[pyloop]\nPASSED r2e_tests/test_1.py::test_close_exc[pyloop]\nPASSED r2e_tests/test_1.py::test_prepare_twice_idempotent[pyloop]\nPASSED r2e_tests/test_1.py::test_send_with_per_message_deflate[pyloop]\nPASSED r2e_tests/test_1.py::test_no_transfer_encoding_header[pyloop]\nPASSED r2e_tests/test_1.py::test_get_extra_info[pyloop-ws_transport0-existent]\nPASSED r2e_tests/test_1.py::test_get_extra_info[pyloop-None-default]\nPASSED r2e_tests/test_1.py::test_get_extra_info[pyloop-ws_transport2-default]\nFAILED r2e_tests/test_1.py::test_raise_writer_limit[pyloop] - TypeError: __in...\n========================= 1 failed, 52 passed in 6.64s =========================\n",
    "old_commit_res_stderr": ""
}
CHANGES/9572.feature.rst aiohttp/web_ws.py docs/web_reference.rst tests/test_web_websocket.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Unable to Set Custom `writer_limit` on WebSocketResponse

**Description:**
When attempting to initialize a `WebSocketResponse` with a custom `writer_limit`, a `TypeError` is raised indicating that the `__init__()` method received an unexpected keyword argument.

**Example Code:**
```python
ws = web.WebSocketResponse(writer_limit=1234567)
await ws.prepare(request)
```

**Expected Behavior:**
The `WebSocketResponse` should accept the `writer_limit` parameter, allowing developers to adjust the server WebSocket writer limit as needed.

**Actual Behavior:**
Initializing `WebSocketResponse` with the `writer_limit` argument results in the following error:
```
TypeError: __init__() got an unexpected keyword argument 'writer_limit'
```
This prevents the customization of the WebSocket writer limit and may lead to limitations in handling large or high-throughput WebSocket connections.
[/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/web_ws.py
import asyncio
import base64
import binascii
import dataclasses
import hashlib
import json
import sys
from typing import Any, Final, Iterable, Optional, Tuple

from multidict import CIMultiDict

from . import hdrs
from .abc import AbstractStreamWriter
from .helpers import calculate_timeout_when, set_exception, set_result
from .http import (
    WS_CLOSED_MESSAGE,
    WS_CLOSING_MESSAGE,
    WS_KEY,
    WebSocketError,
    WebSocketReader,
    WebSocketWriter,
    WSCloseCode,
    WSMessage,
    WSMsgType,
    ws_ext_gen,
    ws_ext_parse,
)
from .http_websocket import WSMessageError
from .log import ws_logger
from .streams import EofStream, FlowControlDataQueue
from .typedefs import JSONDecoder, JSONEncoder
from .web_exceptions import HTTPBadRequest, HTTPException
from .web_request import BaseRequest
from .web_response import StreamResponse

if sys.version_info >= (3, 11):
    import asyncio as async_timeout
else:
    import async_timeout

__all__ = (
    "WebSocketResponse",
    "WebSocketReady",
    "WSMsgType",
)

THRESHOLD_CONNLOST_ACCESS: Final[int] = 5


@dataclasses.dataclass(frozen=True)
class WebSocketReady:
    ok: bool
    protocol: Optional[str]

    def __bool__(self) -> bool:
        return self.ok


class WebSocketResponse(StreamResponse):
    __slots__ = (
        "_protocols",
        "_ws_protocol",
        "_writer",
        "_reader",
        "_closed",
        "_closing",
        "_conn_lost",
        "_close_code",
        "_loop",
        "_waiting",
        "_close_wait",
        "_exception",
        "_timeout",
        "_receive_timeout",
        "_autoclose",
        "_autoping",
        "_heartbeat",
        "_heartbeat_when",
        "_heartbeat_cb",
        "_pong_heartbeat",
        "_pong_response_cb",
        "_compress",
        "_max_msg_size",
        "_ping_task",
    )

    def __init__(
        self,
        *,
        timeout: float = 10.0,
        receive_timeout: Optional[float] = None,
        autoclose: bool = True,
        autoping: bool = True,
        heartbeat: Optional[float] = None,
        protocols: Iterable[str] = (),
        compress: bool = True,
        max_msg_size: int = 4 * 1024 * 1024,
    ) -> None:
        super().__init__(status=101)
        self._length_check = False
        self._protocols = protocols
        self._ws_protocol: Optional[str] = None
        self._writer: Optional[WebSocketWriter] = None
        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None
        self._closed = False
        self._closing = False
        self._conn_lost = 0
        self._close_code: Optional[int] = None
        self._loop: Optional[asyncio.AbstractEventLoop] = None
        self._waiting: bool = False
        self._close_wait: Optional[asyncio.Future[None]] = None
        self._exception: Optional[BaseException] = None
        self._timeout = timeout
        self._receive_timeout = receive_timeout
        self._autoclose = autoclose
        self._autoping = autoping
        self._heartbeat = heartbeat
        self._heartbeat_when = 0.0
        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None
        if heartbeat is not None:
            self._pong_heartbeat = heartbeat / 2.0
        self._pong_response_cb: Optional[asyncio.TimerHandle] = None
        self._compress = compress
        self._max_msg_size = max_msg_size
        self._ping_task: Optional[asyncio.Task[None]] = None

    def _cancel_heartbeat(self) -> None:
        self._cancel_pong_response_cb()
        if self._heartbeat_cb is not None:
            self._heartbeat_cb.cancel()
            self._heartbeat_cb = None
        if self._ping_task is not None:
            self._ping_task.cancel()
            self._ping_task = None

    def _cancel_pong_response_cb(self) -> None:
        if self._pong_response_cb is not None:
            self._pong_response_cb.cancel()
            self._pong_response_cb = None

    def _reset_heartbeat(self) -> None:
        if self._heartbeat is None:
            return
        self._cancel_pong_response_cb()
        req = self._req
        timeout_ceil_threshold = (
            req._protocol._timeout_ceil_threshold if req is not None else 5
        )
        loop = self._loop
        assert loop is not None
        now = loop.time()
        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)
        self._heartbeat_when = when
        if self._heartbeat_cb is None:
            # We do not cancel the previous heartbeat_cb here because
            # it generates a significant amount of TimerHandle churn
            # which causes asyncio to rebuild the heap frequently.
            # Instead _send_heartbeat() will reschedule the next
            # heartbeat if it fires too early.
            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)

    def _send_heartbeat(self) -> None:
        self._heartbeat_cb = None
        loop = self._loop
        assert loop is not None and self._writer is not None
        now = loop.time()
        if now < self._heartbeat_when:
            # Heartbeat fired too early, reschedule
            self._heartbeat_cb = loop.call_at(
                self._heartbeat_when, self._send_heartbeat
            )
            return

        req = self._req
        timeout_ceil_threshold = (
            req._protocol._timeout_ceil_threshold if req is not None else 5
        )
        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)
        self._cancel_pong_response_cb()
        self._pong_response_cb = loop.call_at(when, self._pong_not_received)

        coro = self._writer.send_frame(b"", WSMsgType.PING)
        if sys.version_info >= (3, 12):
            # Optimization for Python 3.12, try to send the ping
            # immediately to avoid having to schedule
            # the task on the event loop.
            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)
        else:
            ping_task = loop.create_task(coro)

        if not ping_task.done():
            self._ping_task = ping_task
            ping_task.add_done_callback(self._ping_task_done)
        else:
            self._ping_task_done(ping_task)

    def _ping_task_done(self, task: "asyncio.Task[None]") -> None:
        """Callback for when the ping task completes."""
        if not task.cancelled() and (exc := task.exception()):
            self._handle_ping_pong_exception(exc)
        self._ping_task = None

    def _pong_not_received(self) -> None:
        if self._req is not None and self._req.transport is not None:
            self._handle_ping_pong_exception(asyncio.TimeoutError())

    def _handle_ping_pong_exception(self, exc: BaseException) -> None:
        """Handle exceptions raised during ping/pong processing."""
        if self._closed:
            return
        self._set_closed()
        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
        self._exception = exc
        if self._waiting and not self._closing and self._reader is not None:
            self._reader.feed_data(WSMessageError(data=exc, extra=None))

    def _set_closed(self) -> None:
        """Set the connection to closed.

        Cancel any heartbeat timers and set the closed flag.
        """
        self._closed = True
        self._cancel_heartbeat()

    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:
        # make pre-check to don't hide it by do_handshake() exceptions
        if self._payload_writer is not None:
            return self._payload_writer

        protocol, writer = self._pre_start(request)
        payload_writer = await super().prepare(request)
        assert payload_writer is not None
        self._post_start(request, protocol, writer)
        await payload_writer.drain()
        return payload_writer

    def _handshake(
        self, request: BaseRequest
    ) -> Tuple["CIMultiDict[str]", str, bool, bool]:
        headers = request.headers
        if "websocket" != headers.get(hdrs.UPGRADE, "").lower().strip():
            raise HTTPBadRequest(
                text=(
                    "No WebSocket UPGRADE hdr: {}\n Can "
                    '"Upgrade" only to "WebSocket".'
                ).format(headers.get(hdrs.UPGRADE))
            )

        if "upgrade" not in headers.get(hdrs.CONNECTION, "").lower():
            raise HTTPBadRequest(
                text="No CONNECTION upgrade hdr: {}".format(
                    headers.get(hdrs.CONNECTION)
                )
            )

        # find common sub-protocol between client and server
        protocol = None
        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:
            req_protocols = [
                str(proto.strip())
                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",")
            ]

            for proto in req_protocols:
                if proto in self._protocols:
                    protocol = proto
                    break
            else:
                # No overlap found: Return no protocol as per spec
                ws_logger.warning(
                    "Client protocols %r don’t overlap server-known ones %r",
                    req_protocols,
                    self._protocols,
                )

        # check supported version
        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, "")
        if version not in ("13", "8", "7"):
            raise HTTPBadRequest(text=f"Unsupported version: {version}")

        # check client handshake for validity
        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)
        try:
            if not key or len(base64.b64decode(key)) != 16:
                raise HTTPBadRequest(text=f"Handshake error: {key!r}")
        except binascii.Error:
            raise HTTPBadRequest(text=f"Handshake error: {key!r}") from None

        accept_val = base64.b64encode(
            hashlib.sha1(key.encode() + WS_KEY).digest()
        ).decode()
        response_headers = CIMultiDict(
            {
                hdrs.UPGRADE: "websocket",
                hdrs.CONNECTION: "upgrade",
                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,
            }
        )

        notakeover = False
        compress = 0
        if self._compress:
            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)
            # Server side always get return with no exception.
            # If something happened, just drop compress extension
            compress, notakeover = ws_ext_parse(extensions, isserver=True)
            if compress:
                enabledext = ws_ext_gen(
                    compress=compress, isserver=True, server_notakeover=notakeover
                )
                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext

        if protocol:
            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol
        return (
            response_headers,
            protocol,
            compress,
            notakeover,
        )  # type: ignore[return-value]

    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:
        self._loop = request._loop

        headers, protocol, compress, notakeover = self._handshake(request)

        self.set_status(101)
        self.headers.update(headers)
        self.force_close()
        self._compress = compress
        transport = request._protocol.transport
        assert transport is not None
        writer = WebSocketWriter(
            request._protocol, transport, compress=compress, notakeover=notakeover
        )

        return protocol, writer

    def _post_start(
        self, request: BaseRequest, protocol: str, writer: WebSocketWriter
    ) -> None:
        self._ws_protocol = protocol
        self._writer = writer

        self._reset_heartbeat()

        loop = self._loop
        assert loop is not None
        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)
        request.protocol.set_parser(
            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)
        )
        # disable HTTP keepalive for WebSocket
        request.protocol.keep_alive(False)

    def can_prepare(self, request: BaseRequest) -> WebSocketReady:
        if self._writer is not None:
            raise RuntimeError("Already started")
        try:
            _, protocol, _, _ = self._handshake(request)
        except HTTPException:
            return WebSocketReady(False, None)
        else:
            return WebSocketReady(True, protocol)

    @property
    def closed(self) -> bool:
        return self._closed

    @property
    def close_code(self) -> Optional[int]:
        return self._close_code

    @property
    def ws_protocol(self) -> Optional[str]:
        return self._ws_protocol

    @property
    def compress(self) -> bool:
        return self._compress

    def get_extra_info(self, name: str, default: Any = None) -> Any:
        """Get optional transport information.

        If no value associated with ``name`` is found, ``default`` is returned.
        """
        writer = self._writer
        if writer is None:
            return default
        transport = writer.transport
        if transport is None:
            return default
        return transport.get_extra_info(name, default)

    def exception(self) -> Optional[BaseException]:
        return self._exception

    async def ping(self, message: bytes = b"") -> None:
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")
        await self._writer.send_frame(message, WSMsgType.PING)

    async def pong(self, message: bytes = b"") -> None:
        # unsolicited pong
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")
        await self._writer.send_frame(message, WSMsgType.PONG)

    async def send_frame(
        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None
    ) -> None:
        """Send a frame over the websocket."""
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")
        await self._writer.send_frame(message, opcode, compress)

    async def send_str(self, data: str, compress: Optional[int] = None) -> None:
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")
        if not isinstance(data, str):
            raise TypeError("data argument must be str (%r)" % type(data))
        await self._writer.send_frame(
            data.encode("utf-8"), WSMsgType.TEXT, compress=compress
        )

    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError("data argument must be byte-ish (%r)" % type(data))
        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)

    async def send_json(
        self,
        data: Any,
        compress: Optional[int] = None,
        *,
        dumps: JSONEncoder = json.dumps,
    ) -> None:
        await self.send_str(dumps(data), compress=compress)

    async def write_eof(self) -> None:  # type: ignore[override]
        if self._eof_sent:
            return
        if self._payload_writer is None:
            raise RuntimeError("Response has not been started")

        await self.close()
        self._eof_sent = True

    async def close(
        self, *, code: int = WSCloseCode.OK, message: bytes = b"", drain: bool = True
    ) -> bool:
        """Close websocket connection."""
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")

        if self._closed:
            return False
        self._set_closed()

        try:
            await self._writer.close(code, message)
            writer = self._payload_writer
            assert writer is not None
            if drain:
                await writer.drain()
        except (asyncio.CancelledError, asyncio.TimeoutError):
            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
            raise
        except Exception as exc:
            self._exception = exc
            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
            return True

        reader = self._reader
        assert reader is not None
        # we need to break `receive()` cycle before we can call
        # `reader.read()` as `close()` may be called from different task
        if self._waiting:
            assert self._loop is not None
            assert self._close_wait is None
            self._close_wait = self._loop.create_future()
            reader.feed_data(WS_CLOSING_MESSAGE)
            await self._close_wait

        if self._closing:
            self._close_transport()
            return True

        try:
            async with async_timeout.timeout(self._timeout):
                msg = await reader.read()
        except asyncio.CancelledError:
            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
            raise
        except Exception as exc:
            self._exception = exc
            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
            return True

        if msg.type is WSMsgType.CLOSE:
            self._set_code_close_transport(msg.data)
            return True

        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
        self._exception = asyncio.TimeoutError()
        return True

    def _set_closing(self, code: int) -> None:
        """Set the close code and mark the connection as closing."""
        self._closing = True
        self._close_code = code
        self._cancel_heartbeat()

    def _set_code_close_transport(self, code: int) -> None:
        """Set the close code and close the transport."""
        self._close_code = code
        self._close_transport()

    def _close_transport(self) -> None:
        """Close the transport."""
        if self._req is not None and self._req.transport is not None:
            self._req.transport.close()

    async def receive(self, timeout: Optional[float] = None) -> WSMessage:
        if self._reader is None:
            raise RuntimeError("Call .prepare() first")

        loop = self._loop
        assert loop is not None
        receive_timeout = timeout or self._receive_timeout
        while True:
            if self._waiting:
                raise RuntimeError("Concurrent call to receive() is not allowed")

            if self._closed:
                self._conn_lost += 1
                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:
                    raise RuntimeError("WebSocket connection is closed.")
                return WS_CLOSED_MESSAGE
            elif self._closing:
                return WS_CLOSING_MESSAGE

            try:
                self._waiting = True
                try:
                    if receive_timeout:
                        # Entering the context manager and creating
                        # Timeout() object can take almost 50% of the
                        # run time in this loop so we avoid it if
                        # there is no read timeout.
                        async with async_timeout.timeout(receive_timeout):
                            msg = await self._reader.read()
                    else:
                        msg = await self._reader.read()
                    self._reset_heartbeat()
                finally:
                    self._waiting = False
                    if self._close_wait:
                        set_result(self._close_wait, None)
            except asyncio.TimeoutError:
                raise
            except EofStream:
                self._close_code = WSCloseCode.OK
                await self.close()
                return WS_CLOSED_MESSAGE
            except WebSocketError as exc:
                self._close_code = exc.code
                await self.close(code=exc.code)
                return WSMessageError(data=exc)
            except Exception as exc:
                self._exception = exc
                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)
                await self.close()
                return WSMessageError(data=exc)

            if msg.type is WSMsgType.CLOSE:
                self._set_closing(msg.data)
                # Could be closed while awaiting reader.
                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]
                    # The client is likely going to close the
                    # connection out from under us so we do not
                    # want to drain any pending writes as it will
                    # likely result writing to a broken pipe.
                    await self.close(drain=False)
            elif msg.type is WSMsgType.CLOSING:
                self._set_closing(WSCloseCode.OK)
            elif msg.type is WSMsgType.PING and self._autoping:
                await self.pong(msg.data)
                continue
            elif msg.type is WSMsgType.PONG and self._autoping:
                continue

            return msg

    async def receive_str(self, *, timeout: Optional[float] = None) -> str:
        msg = await self.receive(timeout)
        if msg.type is not WSMsgType.TEXT:
            raise TypeError(
                "Received message {}:{!r} is not WSMsgType.TEXT".format(
                    msg.type, msg.data
                )
            )
        return msg.data

    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:
        msg = await self.receive(timeout)
        if msg.type is not WSMsgType.BINARY:
            raise TypeError(f"Received message {msg.type}:{msg.data!r} is not bytes")
        return msg.data

    async def receive_json(
        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None
    ) -> Any:
        data = await self.receive_str(timeout=timeout)
        return loads(data)

    async def write(self, data: bytes) -> None:
        raise RuntimeError("Cannot call .write() for websocket")

    def __aiter__(self) -> "WebSocketResponse":
        return self

    async def __anext__(self) -> WSMessage:
        msg = await self.receive()
        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):
            raise StopAsyncIteration
        return msg

    def _cancel(self, exc: BaseException) -> None:
        # web_protocol calls this from connection_lost
        # or when the server is shutting down.
        self._closing = True
        self._cancel_heartbeat()
        if self._reader is not None:
            set_exception(self._reader, exc)

```
--- 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:** Unable to Set Custom `writer_limit` on WebSocketResponse

**Description:**
When attempting to initialize a `WebSocketResponse` with a custom `writer_limit`, a `TypeError` is raised indicating that the `__init__()` method received an unexpected keyword argument.

**Example Code:**
```python
ws = web.WebSocketResponse(writer_limit=1234567)
await ws.prepare(request)
```

**Expected Behavior:**
The `WebSocketResponse` should accept the `writer_limit` parameter, allowing developers to adjust the server WebSocket writer limit as needed.

**Actual Behavior:**
Initializing `WebSocketResponse` with the `writer_limit` argument results in the following error:
```
TypeError: __init__() got an unexpected keyword argument 'writer_limit'
```
This prevents the customization of the WebSocket writer limit and may lead to limitations in handling large or high-throughput WebSocket connections.
[/ISSUE]
{
    "test_nonstarted_ping": "PASSED",
    "test_nonstarted_pong": "PASSED",
    "test_nonstarted_send_frame": "PASSED",
    "test_nonstarted_send_str": "PASSED",
    "test_nonstarted_send_bytes": "PASSED",
    "test_nonstarted_send_json": "PASSED",
    "test_nonstarted_close": "PASSED",
    "test_nonstarted_receive_str": "PASSED",
    "test_nonstarted_receive_bytes": "PASSED",
    "test_nonstarted_receive_json": "PASSED",
    "test_send_str_nonstring[pyloop]": "PASSED",
    "test_send_bytes_nonbytes[pyloop]": "PASSED",
    "test_send_json_nonjson[pyloop]": "PASSED",
    "test_write_non_prepared": "PASSED",
    "test_heartbeat_timeout[pyloop]": "PASSED",
    "test_websocket_ready": "PASSED",
    "test_websocket_not_ready": "PASSED",
    "test_websocket_ready_unknown_protocol": "PASSED",
    "test_bool_websocket_ready": "PASSED",
    "test_bool_websocket_not_ready": "PASSED",
    "test_can_prepare_ok[pyloop]": "PASSED",
    "test_can_prepare_unknown_protocol[pyloop]": "PASSED",
    "test_can_prepare_without_upgrade[pyloop]": "PASSED",
    "test_can_prepare_started[pyloop]": "PASSED",
    "test_closed_after_ctor": "PASSED",
    "test_raise_writer_limit[pyloop]": "PASSED",
    "test_send_str_closed[pyloop]": "PASSED",
    "test_send_bytes_closed[pyloop]": "PASSED",
    "test_send_json_closed[pyloop]": "PASSED",
    "test_send_frame_closed[pyloop]": "PASSED",
    "test_ping_closed[pyloop]": "PASSED",
    "test_pong_closed[pyloop]": "PASSED",
    "test_close_idempotent[pyloop]": "PASSED",
    "test_prepare_post_method_ok[pyloop]": "PASSED",
    "test_prepare_without_upgrade[pyloop]": "PASSED",
    "test_wait_closed_before_start": "PASSED",
    "test_write_eof_not_started": "PASSED",
    "test_write_eof_idempotent[pyloop]": "PASSED",
    "test_receive_eofstream_in_reader[pyloop]": "PASSED",
    "test_receive_exception_in_reader[pyloop]": "PASSED",
    "test_receive_close_but_left_open[pyloop]": "PASSED",
    "test_receive_closing[pyloop]": "PASSED",
    "test_close_after_closing[pyloop]": "PASSED",
    "test_receive_timeouterror[pyloop]": "PASSED",
    "test_multiple_receive_on_close_connection[pyloop]": "PASSED",
    "test_concurrent_receive[pyloop]": "PASSED",
    "test_close_exc[pyloop]": "PASSED",
    "test_prepare_twice_idempotent[pyloop]": "PASSED",
    "test_send_with_per_message_deflate[pyloop]": "PASSED",
    "test_no_transfer_encoding_header[pyloop]": "PASSED",
    "test_get_extra_info[pyloop-ws_transport0-existent]": "PASSED",
    "test_get_extra_info[pyloop-None-default]": "PASSED",
    "test_get_extra_info[pyloop-ws_transport2-default]": "PASSED"
}
diff --git a/aiohttp/web_ws.py b/aiohttp/web_ws.py
index 9fa78dd9..007e309d 100644
--- a/aiohttp/web_ws.py
+++ b/aiohttp/web_ws.py
@@ -10,6 +10,7 @@ from typing import Any, Final, Iterable, Optional, Tuple
 from multidict import CIMultiDict
 
 from . import hdrs
+from ._websocket.writer import DEFAULT_LIMIT
 from .abc import AbstractStreamWriter
 from .helpers import calculate_timeout_when, set_exception, set_result
 from .http import (
@@ -82,6 +83,7 @@ class WebSocketResponse(StreamResponse):
         "_compress",
         "_max_msg_size",
         "_ping_task",
+        "_writer_limit",
     )
 
     def __init__(
@@ -95,6 +97,7 @@ class WebSocketResponse(StreamResponse):
         protocols: Iterable[str] = (),
         compress: bool = True,
         max_msg_size: int = 4 * 1024 * 1024,
+        writer_limit: int = DEFAULT_LIMIT,
     ) -> None:
         super().__init__(status=101)
         self._length_check = False
@@ -123,6 +126,7 @@ class WebSocketResponse(StreamResponse):
         self._compress = compress
         self._max_msg_size = max_msg_size
         self._ping_task: Optional[asyncio.Task[None]] = None
+        self._writer_limit = writer_limit
 
     def _cancel_heartbeat(self) -> None:
         self._cancel_pong_response_cb()
@@ -331,7 +335,11 @@ class WebSocketResponse(StreamResponse):
         transport = request._protocol.transport
         assert transport is not None
         writer = WebSocketWriter(
-            request._protocol, transport, compress=compress, notakeover=notakeover
+            request._protocol,
+            transport,
+            compress=compress,
+            notakeover=notakeover,
+            limit=self._writer_limit,
         )
 
         return protocol, writer

{"aiohttp/web_ws.py": "import asyncio\nimport base64\nimport binascii\nimport dataclasses\nimport hashlib\nimport json\nimport sys\nfrom typing import Any, Final, Iterable, Optional, Tuple\n\nfrom multidict import CIMultiDict\n\nfrom . import hdrs\nfrom .abc import AbstractStreamWriter\nfrom .helpers import calculate_timeout_when, set_exception, set_result\nfrom .http import (\n    WS_CLOSED_MESSAGE,\n    WS_CLOSING_MESSAGE,\n    WS_KEY,\n    WebSocketError,\n    WebSocketReader,\n    WebSocketWriter,\n    WSCloseCode,\n    WSMessage,\n    WSMsgType,\n    ws_ext_gen,\n    ws_ext_parse,\n)\nfrom .http_websocket import WSMessageError\nfrom .log import ws_logger\nfrom .streams import EofStream, FlowControlDataQueue\nfrom .typedefs import JSONDecoder, JSONEncoder\nfrom .web_exceptions import HTTPBadRequest, HTTPException\nfrom .web_request import BaseRequest\nfrom .web_response import StreamResponse\n\nif sys.version_info >= (3, 11):\n    import asyncio as async_timeout\nelse:\n    import async_timeout\n\n__all__ = (\n    \"WebSocketResponse\",\n    \"WebSocketReady\",\n    \"WSMsgType\",\n)\n\nTHRESHOLD_CONNLOST_ACCESS: Final[int] = 5\n\n\n@dataclasses.dataclass(frozen=True)\nclass WebSocketReady:\n    ok: bool\n    protocol: Optional[str]\n\n    def __bool__(self) -> bool:\n        return self.ok\n\n\nclass WebSocketResponse(StreamResponse):\n    __slots__ = (\n        \"_protocols\",\n        \"_ws_protocol\",\n        \"_writer\",\n        \"_reader\",\n        \"_closed\",\n        \"_closing\",\n        \"_conn_lost\",\n        \"_close_code\",\n        \"_loop\",\n        \"_waiting\",\n        \"_close_wait\",\n        \"_exception\",\n        \"_timeout\",\n        \"_receive_timeout\",\n        \"_autoclose\",\n        \"_autoping\",\n        \"_heartbeat\",\n        \"_heartbeat_when\",\n        \"_heartbeat_cb\",\n        \"_pong_heartbeat\",\n        \"_pong_response_cb\",\n        \"_compress\",\n        \"_max_msg_size\",\n        \"_ping_task\",\n    )\n\n    def __init__(\n        self,\n        *,\n        timeout: float = 10.0,\n        receive_timeout: Optional[float] = None,\n        autoclose: bool = True,\n        autoping: bool = True,\n        heartbeat: Optional[float] = None,\n        protocols: Iterable[str] = (),\n        compress: bool = True,\n        max_msg_size: int = 4 * 1024 * 1024,\n    ) -> None:\n        super().__init__(status=101)\n        self._length_check = False\n        self._protocols = protocols\n        self._ws_protocol: Optional[str] = None\n        self._writer: Optional[WebSocketWriter] = None\n        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None\n        self._closed = False\n        self._closing = False\n        self._conn_lost = 0\n        self._close_code: Optional[int] = None\n        self._loop: Optional[asyncio.AbstractEventLoop] = None\n        self._waiting: bool = False\n        self._close_wait: Optional[asyncio.Future[None]] = None\n        self._exception: Optional[BaseException] = None\n        self._timeout = timeout\n        self._receive_timeout = receive_timeout\n        self._autoclose = autoclose\n        self._autoping = autoping\n        self._heartbeat = heartbeat\n        self._heartbeat_when = 0.0\n        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None\n        if heartbeat is not None:\n            self._pong_heartbeat = heartbeat / 2.0\n        self._pong_response_cb: Optional[asyncio.TimerHandle] = None\n        self._compress = compress\n        self._max_msg_size = max_msg_size\n        self._ping_task: Optional[asyncio.Task[None]] = None\n\n    def _cancel_heartbeat(self) -> None:\n        self._cancel_pong_response_cb()\n        if self._heartbeat_cb is not None:\n            self._heartbeat_cb.cancel()\n            self._heartbeat_cb = None\n        if self._ping_task is not None:\n            self._ping_task.cancel()\n            self._ping_task = None\n\n    def _cancel_pong_response_cb(self) -> None:\n        if self._pong_response_cb is not None:\n            self._pong_response_cb.cancel()\n            self._pong_response_cb = None\n\n    def _reset_heartbeat(self) -> None:\n        if self._heartbeat is None:\n            return\n        self._cancel_pong_response_cb()\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        loop = self._loop\n        assert loop is not None\n        now = loop.time()\n        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)\n        self._heartbeat_when = when\n        if self._heartbeat_cb is None:\n            # We do not cancel the previous heartbeat_cb here because\n            # it generates a significant amount of TimerHandle churn\n            # which causes asyncio to rebuild the heap frequently.\n            # Instead _send_heartbeat() will reschedule the next\n            # heartbeat if it fires too early.\n            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)\n\n    def _send_heartbeat(self) -> None:\n        self._heartbeat_cb = None\n        loop = self._loop\n        assert loop is not None and self._writer is not None\n        now = loop.time()\n        if now < self._heartbeat_when:\n            # Heartbeat fired too early, reschedule\n            self._heartbeat_cb = loop.call_at(\n                self._heartbeat_when, self._send_heartbeat\n            )\n            return\n\n        req = self._req\n        timeout_ceil_threshold = (\n            req._protocol._timeout_ceil_threshold if req is not None else 5\n        )\n        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)\n        self._cancel_pong_response_cb()\n        self._pong_response_cb = loop.call_at(when, self._pong_not_received)\n\n        coro = self._writer.send_frame(b\"\", WSMsgType.PING)\n        if sys.version_info >= (3, 12):\n            # Optimization for Python 3.12, try to send the ping\n            # immediately to avoid having to schedule\n            # the task on the event loop.\n            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)\n        else:\n            ping_task = loop.create_task(coro)\n\n        if not ping_task.done():\n            self._ping_task = ping_task\n            ping_task.add_done_callback(self._ping_task_done)\n        else:\n            self._ping_task_done(ping_task)\n\n    def _ping_task_done(self, task: \"asyncio.Task[None]\") -> None:\n        \"\"\"Callback for when the ping task completes.\"\"\"\n        if not task.cancelled() and (exc := task.exception()):\n            self._handle_ping_pong_exception(exc)\n        self._ping_task = None\n\n    def _pong_not_received(self) -> None:\n        if self._req is not None and self._req.transport is not None:\n            self._handle_ping_pong_exception(asyncio.TimeoutError())\n\n    def _handle_ping_pong_exception(self, exc: BaseException) -> None:\n        \"\"\"Handle exceptions raised during ping/pong processing.\"\"\"\n        if self._closed:\n            return\n        self._set_closed()\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = exc\n        if self._waiting and not self._closing and self._reader is not None:\n            self._reader.feed_data(WSMessageError(data=exc, extra=None))\n\n    def _set_closed(self) -> None:\n        \"\"\"Set the connection to closed.\n\n        Cancel any heartbeat timers and set the closed flag.\n        \"\"\"\n        self._closed = True\n        self._cancel_heartbeat()\n\n    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:\n        # make pre-check to don't hide it by do_handshake() exceptions\n        if self._payload_writer is not None:\n            return self._payload_writer\n\n        protocol, writer = self._pre_start(request)\n        payload_writer = await super().prepare(request)\n        assert payload_writer is not None\n        self._post_start(request, protocol, writer)\n        await payload_writer.drain()\n        return payload_writer\n\n    def _handshake(\n        self, request: BaseRequest\n    ) -> Tuple[\"CIMultiDict[str]\", str, bool, bool]:\n        headers = request.headers\n        if \"websocket\" != headers.get(hdrs.UPGRADE, \"\").lower().strip():\n            raise HTTPBadRequest(\n                text=(\n                    \"No WebSocket UPGRADE hdr: {}\\n Can \"\n                    '\"Upgrade\" only to \"WebSocket\".'\n                ).format(headers.get(hdrs.UPGRADE))\n            )\n\n        if \"upgrade\" not in headers.get(hdrs.CONNECTION, \"\").lower():\n            raise HTTPBadRequest(\n                text=\"No CONNECTION upgrade hdr: {}\".format(\n                    headers.get(hdrs.CONNECTION)\n                )\n            )\n\n        # find common sub-protocol between client and server\n        protocol = None\n        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:\n            req_protocols = [\n                str(proto.strip())\n                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(\",\")\n            ]\n\n            for proto in req_protocols:\n                if proto in self._protocols:\n                    protocol = proto\n                    break\n            else:\n                # No overlap found: Return no protocol as per spec\n                ws_logger.warning(\n                    \"Client protocols %r don\u2019t overlap server-known ones %r\",\n                    req_protocols,\n                    self._protocols,\n                )\n\n        # check supported version\n        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, \"\")\n        if version not in (\"13\", \"8\", \"7\"):\n            raise HTTPBadRequest(text=f\"Unsupported version: {version}\")\n\n        # check client handshake for validity\n        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)\n        try:\n            if not key or len(base64.b64decode(key)) != 16:\n                raise HTTPBadRequest(text=f\"Handshake error: {key!r}\")\n        except binascii.Error:\n            raise HTTPBadRequest(text=f\"Handshake error: {key!r}\") from None\n\n        accept_val = base64.b64encode(\n            hashlib.sha1(key.encode() + WS_KEY).digest()\n        ).decode()\n        response_headers = CIMultiDict(\n            {\n                hdrs.UPGRADE: \"websocket\",\n                hdrs.CONNECTION: \"upgrade\",\n                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,\n            }\n        )\n\n        notakeover = False\n        compress = 0\n        if self._compress:\n            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)\n            # Server side always get return with no exception.\n            # If something happened, just drop compress extension\n            compress, notakeover = ws_ext_parse(extensions, isserver=True)\n            if compress:\n                enabledext = ws_ext_gen(\n                    compress=compress, isserver=True, server_notakeover=notakeover\n                )\n                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext\n\n        if protocol:\n            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol\n        return (\n            response_headers,\n            protocol,\n            compress,\n            notakeover,\n        )  # type: ignore[return-value]\n\n    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:\n        self._loop = request._loop\n\n        headers, protocol, compress, notakeover = self._handshake(request)\n\n        self.set_status(101)\n        self.headers.update(headers)\n        self.force_close()\n        self._compress = compress\n        transport = request._protocol.transport\n        assert transport is not None\n        writer = WebSocketWriter(\n            request._protocol, transport, compress=compress, notakeover=notakeover\n        )\n\n        return protocol, writer\n\n    def _post_start(\n        self, request: BaseRequest, protocol: str, writer: WebSocketWriter\n    ) -> None:\n        self._ws_protocol = protocol\n        self._writer = writer\n\n        self._reset_heartbeat()\n\n        loop = self._loop\n        assert loop is not None\n        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)\n        request.protocol.set_parser(\n            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)\n        )\n        # disable HTTP keepalive for WebSocket\n        request.protocol.keep_alive(False)\n\n    def can_prepare(self, request: BaseRequest) -> WebSocketReady:\n        if self._writer is not None:\n            raise RuntimeError(\"Already started\")\n        try:\n            _, protocol, _, _ = self._handshake(request)\n        except HTTPException:\n            return WebSocketReady(False, None)\n        else:\n            return WebSocketReady(True, protocol)\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    @property\n    def close_code(self) -> Optional[int]:\n        return self._close_code\n\n    @property\n    def ws_protocol(self) -> Optional[str]:\n        return self._ws_protocol\n\n    @property\n    def compress(self) -> bool:\n        return self._compress\n\n    def get_extra_info(self, name: str, default: Any = None) -> Any:\n        \"\"\"Get optional transport information.\n\n        If no value associated with ``name`` is found, ``default`` is returned.\n        \"\"\"\n        writer = self._writer\n        if writer is None:\n            return default\n        transport = writer.transport\n        if transport is None:\n            return default\n        return transport.get_extra_info(name, default)\n\n    def exception(self) -> Optional[BaseException]:\n        return self._exception\n\n    async def ping(self, message: bytes = b\"\") -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PING)\n\n    async def pong(self, message: bytes = b\"\") -> None:\n        # unsolicited pong\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, WSMsgType.PONG)\n\n    async def send_frame(\n        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None\n    ) -> None:\n        \"\"\"Send a frame over the websocket.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        await self._writer.send_frame(message, opcode, compress)\n\n    async def send_str(self, data: str, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, str):\n            raise TypeError(\"data argument must be str (%r)\" % type(data))\n        await self._writer.send_frame(\n            data.encode(\"utf-8\"), WSMsgType.TEXT, compress=compress\n        )\n\n    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\"data argument must be byte-ish (%r)\" % type(data))\n        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)\n\n    async def send_json(\n        self,\n        data: Any,\n        compress: Optional[int] = None,\n        *,\n        dumps: JSONEncoder = json.dumps,\n    ) -> None:\n        await self.send_str(dumps(data), compress=compress)\n\n    async def write_eof(self) -> None:  # type: ignore[override]\n        if self._eof_sent:\n            return\n        if self._payload_writer is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        await self.close()\n        self._eof_sent = True\n\n    async def close(\n        self, *, code: int = WSCloseCode.OK, message: bytes = b\"\", drain: bool = True\n    ) -> bool:\n        \"\"\"Close websocket connection.\"\"\"\n        if self._writer is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        if self._closed:\n            return False\n        self._set_closed()\n\n        try:\n            await self._writer.close(code, message)\n            writer = self._payload_writer\n            assert writer is not None\n            if drain:\n                await writer.drain()\n        except (asyncio.CancelledError, asyncio.TimeoutError):\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        reader = self._reader\n        assert reader is not None\n        # we need to break `receive()` cycle before we can call\n        # `reader.read()` as `close()` may be called from different task\n        if self._waiting:\n            assert self._loop is not None\n            assert self._close_wait is None\n            self._close_wait = self._loop.create_future()\n            reader.feed_data(WS_CLOSING_MESSAGE)\n            await self._close_wait\n\n        if self._closing:\n            self._close_transport()\n            return True\n\n        try:\n            async with async_timeout.timeout(self._timeout):\n                msg = await reader.read()\n        except asyncio.CancelledError:\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            raise\n        except Exception as exc:\n            self._exception = exc\n            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n            return True\n\n        if msg.type is WSMsgType.CLOSE:\n            self._set_code_close_transport(msg.data)\n            return True\n\n        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)\n        self._exception = asyncio.TimeoutError()\n        return True\n\n    def _set_closing(self, code: int) -> None:\n        \"\"\"Set the close code and mark the connection as closing.\"\"\"\n        self._closing = True\n        self._close_code = code\n        self._cancel_heartbeat()\n\n    def _set_code_close_transport(self, code: int) -> None:\n        \"\"\"Set the close code and close the transport.\"\"\"\n        self._close_code = code\n        self._close_transport()\n\n    def _close_transport(self) -> None:\n        \"\"\"Close the transport.\"\"\"\n        if self._req is not None and self._req.transport is not None:\n            self._req.transport.close()\n\n    async def receive(self, timeout: Optional[float] = None) -> WSMessage:\n        if self._reader is None:\n            raise RuntimeError(\"Call .prepare() first\")\n\n        loop = self._loop\n        assert loop is not None\n        receive_timeout = timeout or self._receive_timeout\n        while True:\n            if self._waiting:\n                raise RuntimeError(\"Concurrent call to receive() is not allowed\")\n\n            if self._closed:\n                self._conn_lost += 1\n                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:\n                    raise RuntimeError(\"WebSocket connection is closed.\")\n                return WS_CLOSED_MESSAGE\n            elif self._closing:\n                return WS_CLOSING_MESSAGE\n\n            try:\n                self._waiting = True\n                try:\n                    if receive_timeout:\n                        # Entering the context manager and creating\n                        # Timeout() object can take almost 50% of the\n                        # run time in this loop so we avoid it if\n                        # there is no read timeout.\n                        async with async_timeout.timeout(receive_timeout):\n                            msg = await self._reader.read()\n                    else:\n                        msg = await self._reader.read()\n                    self._reset_heartbeat()\n                finally:\n                    self._waiting = False\n                    if self._close_wait:\n                        set_result(self._close_wait, None)\n            except asyncio.TimeoutError:\n                raise\n            except EofStream:\n                self._close_code = WSCloseCode.OK\n                await self.close()\n                return WS_CLOSED_MESSAGE\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessageError(data=exc)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessageError(data=exc)\n\n            if msg.type is WSMsgType.CLOSE:\n                self._set_closing(msg.data)\n                # Could be closed while awaiting reader.\n                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]\n                    # The client is likely going to close the\n                    # connection out from under us so we do not\n                    # want to drain any pending writes as it will\n                    # likely result writing to a broken pipe.\n                    await self.close(drain=False)\n            elif msg.type is WSMsgType.CLOSING:\n                self._set_closing(WSCloseCode.OK)\n            elif msg.type is WSMsgType.PING and self._autoping:\n                await self.pong(msg.data)\n                continue\n            elif msg.type is WSMsgType.PONG and self._autoping:\n                continue\n\n            return msg\n\n    async def receive_str(self, *, timeout: Optional[float] = None) -> str:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.TEXT:\n            raise TypeError(\n                \"Received message {}:{!r} is not WSMsgType.TEXT\".format(\n                    msg.type, msg.data\n                )\n            )\n        return msg.data\n\n    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:\n        msg = await self.receive(timeout)\n        if msg.type is not WSMsgType.BINARY:\n            raise TypeError(f\"Received message {msg.type}:{msg.data!r} is not bytes\")\n        return msg.data\n\n    async def receive_json(\n        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None\n    ) -> Any:\n        data = await self.receive_str(timeout=timeout)\n        return loads(data)\n\n    async def write(self, data: bytes) -> None:\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n    def __aiter__(self) -> \"WebSocketResponse\":\n        return self\n\n    async def __anext__(self) -> WSMessage:\n        msg = await self.receive()\n        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):\n            raise StopAsyncIteration\n        return msg\n\n    def _cancel(self, exc: BaseException) -> None:\n        # web_protocol calls this from connection_lost\n        # or when the server is shutting down.\n        self._closing = True\n        self._cancel_heartbeat()\n        if self._reader is not None:\n            set_exception(self._reader, exc)\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:** Unable to Set Custom `writer_limit` on WebSocketResponse

**Description:**
When attempting to initialize a `WebSocketResponse` with a custom `writer_limit`, a `TypeError` is raised indicating that the `__init__()` method received an unexpected keyword argument.

**Example Code:**
```python
ws = web.WebSocketResponse(writer_limit=1234567)
await ws.prepare(request)
```

**Expected Behavior:**
The `WebSocketResponse` should accept the `writer_limit` parameter, allowing developers to adjust the server WebSocket writer limit as needed.

**Actual Behavior:**
Initializing `WebSocketResponse` with the `writer_limit` argument results in the following error:
```
TypeError: __init__() got an unexpected keyword argument 'writer_limit'
```
This prevents the customization of the WebSocket writer limit and may lead to limitations in handling large or high-throughput WebSocket connections.
[/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/web_ws.py
import asyncio
import base64
import binascii
import dataclasses
import hashlib
import json
import sys
from typing import Any, Final, Iterable, Optional, Tuple

from multidict import CIMultiDict

from . import hdrs
from .abc import AbstractStreamWriter
from .helpers import calculate_timeout_when, set_exception, set_result
from .http import (
    WS_CLOSED_MESSAGE,
    WS_CLOSING_MESSAGE,
    WS_KEY,
    WebSocketError,
    WebSocketReader,
    WebSocketWriter,
    WSCloseCode,
    WSMessage,
    WSMsgType,
    ws_ext_gen,
    ws_ext_parse,
)
from .http_websocket import WSMessageError
from .log import ws_logger
from .streams import EofStream, FlowControlDataQueue
from .typedefs import JSONDecoder, JSONEncoder
from .web_exceptions import HTTPBadRequest, HTTPException
from .web_request import BaseRequest
from .web_response import StreamResponse

if sys.version_info >= (3, 11):
    import asyncio as async_timeout
else:
    import async_timeout

__all__ = (
    "WebSocketResponse",
    "WebSocketReady",
    "WSMsgType",
)

THRESHOLD_CONNLOST_ACCESS: Final[int] = 5


@dataclasses.dataclass(frozen=True)
class WebSocketReady:
    ok: bool
    protocol: Optional[str]

    def __bool__(self) -> bool:
        return self.ok


class WebSocketResponse(StreamResponse):
    __slots__ = (
        "_protocols",
        "_ws_protocol",
        "_writer",
        "_reader",
        "_closed",
        "_closing",
        "_conn_lost",
        "_close_code",
        "_loop",
        "_waiting",
        "_close_wait",
        "_exception",
        "_timeout",
        "_receive_timeout",
        "_autoclose",
        "_autoping",
        "_heartbeat",
        "_heartbeat_when",
        "_heartbeat_cb",
        "_pong_heartbeat",
        "_pong_response_cb",
        "_compress",
        "_max_msg_size",
        "_ping_task",
    )

    def __init__(
        self,
        *,
        timeout: float = 10.0,
        receive_timeout: Optional[float] = None,
        autoclose: bool = True,
        autoping: bool = True,
        heartbeat: Optional[float] = None,
        protocols: Iterable[str] = (),
        compress: bool = True,
        max_msg_size: int = 4 * 1024 * 1024,
    ) -> None:
        super().__init__(status=101)
        self._length_check = False
        self._protocols = protocols
        self._ws_protocol: Optional[str] = None
        self._writer: Optional[WebSocketWriter] = None
        self._reader: Optional[FlowControlDataQueue[WSMessage]] = None
        self._closed = False
        self._closing = False
        self._conn_lost = 0
        self._close_code: Optional[int] = None
        self._loop: Optional[asyncio.AbstractEventLoop] = None
        self._waiting: bool = False
        self._close_wait: Optional[asyncio.Future[None]] = None
        self._exception: Optional[BaseException] = None
        self._timeout = timeout
        self._receive_timeout = receive_timeout
        self._autoclose = autoclose
        self._autoping = autoping
        self._heartbeat = heartbeat
        self._heartbeat_when = 0.0
        self._heartbeat_cb: Optional[asyncio.TimerHandle] = None
        if heartbeat is not None:
            self._pong_heartbeat = heartbeat / 2.0
        self._pong_response_cb: Optional[asyncio.TimerHandle] = None
        self._compress = compress
        self._max_msg_size = max_msg_size
        self._ping_task: Optional[asyncio.Task[None]] = None

    def _cancel_heartbeat(self) -> None:
        self._cancel_pong_response_cb()
        if self._heartbeat_cb is not None:
            self._heartbeat_cb.cancel()
            self._heartbeat_cb = None
        if self._ping_task is not None:
            self._ping_task.cancel()
            self._ping_task = None

    def _cancel_pong_response_cb(self) -> None:
        if self._pong_response_cb is not None:
            self._pong_response_cb.cancel()
            self._pong_response_cb = None

    def _reset_heartbeat(self) -> None:
        if self._heartbeat is None:
            return
        self._cancel_pong_response_cb()
        req = self._req
        timeout_ceil_threshold = (
            req._protocol._timeout_ceil_threshold if req is not None else 5
        )
        loop = self._loop
        assert loop is not None
        now = loop.time()
        when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold)
        self._heartbeat_when = when
        if self._heartbeat_cb is None:
            # We do not cancel the previous heartbeat_cb here because
            # it generates a significant amount of TimerHandle churn
            # which causes asyncio to rebuild the heap frequently.
            # Instead _send_heartbeat() will reschedule the next
            # heartbeat if it fires too early.
            self._heartbeat_cb = loop.call_at(when, self._send_heartbeat)

    def _send_heartbeat(self) -> None:
        self._heartbeat_cb = None
        loop = self._loop
        assert loop is not None and self._writer is not None
        now = loop.time()
        if now < self._heartbeat_when:
            # Heartbeat fired too early, reschedule
            self._heartbeat_cb = loop.call_at(
                self._heartbeat_when, self._send_heartbeat
            )
            return

        req = self._req
        timeout_ceil_threshold = (
            req._protocol._timeout_ceil_threshold if req is not None else 5
        )
        when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold)
        self._cancel_pong_response_cb()
        self._pong_response_cb = loop.call_at(when, self._pong_not_received)

        coro = self._writer.send_frame(b"", WSMsgType.PING)
        if sys.version_info >= (3, 12):
            # Optimization for Python 3.12, try to send the ping
            # immediately to avoid having to schedule
            # the task on the event loop.
            ping_task = asyncio.Task(coro, loop=loop, eager_start=True)
        else:
            ping_task = loop.create_task(coro)

        if not ping_task.done():
            self._ping_task = ping_task
            ping_task.add_done_callback(self._ping_task_done)
        else:
            self._ping_task_done(ping_task)

    def _ping_task_done(self, task: "asyncio.Task[None]") -> None:
        """Callback for when the ping task completes."""
        if not task.cancelled() and (exc := task.exception()):
            self._handle_ping_pong_exception(exc)
        self._ping_task = None

    def _pong_not_received(self) -> None:
        if self._req is not None and self._req.transport is not None:
            self._handle_ping_pong_exception(asyncio.TimeoutError())

    def _handle_ping_pong_exception(self, exc: BaseException) -> None:
        """Handle exceptions raised during ping/pong processing."""
        if self._closed:
            return
        self._set_closed()
        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
        self._exception = exc
        if self._waiting and not self._closing and self._reader is not None:
            self._reader.feed_data(WSMessageError(data=exc, extra=None))

    def _set_closed(self) -> None:
        """Set the connection to closed.

        Cancel any heartbeat timers and set the closed flag.
        """
        self._closed = True
        self._cancel_heartbeat()

    async def prepare(self, request: BaseRequest) -> AbstractStreamWriter:
        # make pre-check to don't hide it by do_handshake() exceptions
        if self._payload_writer is not None:
            return self._payload_writer

        protocol, writer = self._pre_start(request)
        payload_writer = await super().prepare(request)
        assert payload_writer is not None
        self._post_start(request, protocol, writer)
        await payload_writer.drain()
        return payload_writer

    def _handshake(
        self, request: BaseRequest
    ) -> Tuple["CIMultiDict[str]", str, bool, bool]:
        headers = request.headers
        if "websocket" != headers.get(hdrs.UPGRADE, "").lower().strip():
            raise HTTPBadRequest(
                text=(
                    "No WebSocket UPGRADE hdr: {}\n Can "
                    '"Upgrade" only to "WebSocket".'
                ).format(headers.get(hdrs.UPGRADE))
            )

        if "upgrade" not in headers.get(hdrs.CONNECTION, "").lower():
            raise HTTPBadRequest(
                text="No CONNECTION upgrade hdr: {}".format(
                    headers.get(hdrs.CONNECTION)
                )
            )

        # find common sub-protocol between client and server
        protocol = None
        if hdrs.SEC_WEBSOCKET_PROTOCOL in headers:
            req_protocols = [
                str(proto.strip())
                for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",")
            ]

            for proto in req_protocols:
                if proto in self._protocols:
                    protocol = proto
                    break
            else:
                # No overlap found: Return no protocol as per spec
                ws_logger.warning(
                    "Client protocols %r don’t overlap server-known ones %r",
                    req_protocols,
                    self._protocols,
                )

        # check supported version
        version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, "")
        if version not in ("13", "8", "7"):
            raise HTTPBadRequest(text=f"Unsupported version: {version}")

        # check client handshake for validity
        key = headers.get(hdrs.SEC_WEBSOCKET_KEY)
        try:
            if not key or len(base64.b64decode(key)) != 16:
                raise HTTPBadRequest(text=f"Handshake error: {key!r}")
        except binascii.Error:
            raise HTTPBadRequest(text=f"Handshake error: {key!r}") from None

        accept_val = base64.b64encode(
            hashlib.sha1(key.encode() + WS_KEY).digest()
        ).decode()
        response_headers = CIMultiDict(
            {
                hdrs.UPGRADE: "websocket",
                hdrs.CONNECTION: "upgrade",
                hdrs.SEC_WEBSOCKET_ACCEPT: accept_val,
            }
        )

        notakeover = False
        compress = 0
        if self._compress:
            extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)
            # Server side always get return with no exception.
            # If something happened, just drop compress extension
            compress, notakeover = ws_ext_parse(extensions, isserver=True)
            if compress:
                enabledext = ws_ext_gen(
                    compress=compress, isserver=True, server_notakeover=notakeover
                )
                response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext

        if protocol:
            response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol
        return (
            response_headers,
            protocol,
            compress,
            notakeover,
        )  # type: ignore[return-value]

    def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]:
        self._loop = request._loop

        headers, protocol, compress, notakeover = self._handshake(request)

        self.set_status(101)
        self.headers.update(headers)
        self.force_close()
        self._compress = compress
        transport = request._protocol.transport
        assert transport is not None
        writer = WebSocketWriter(
            request._protocol, transport, compress=compress, notakeover=notakeover
        )

        return protocol, writer

    def _post_start(
        self, request: BaseRequest, protocol: str, writer: WebSocketWriter
    ) -> None:
        self._ws_protocol = protocol
        self._writer = writer

        self._reset_heartbeat()

        loop = self._loop
        assert loop is not None
        self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop)
        request.protocol.set_parser(
            WebSocketReader(self._reader, self._max_msg_size, compress=self._compress)
        )
        # disable HTTP keepalive for WebSocket
        request.protocol.keep_alive(False)

    def can_prepare(self, request: BaseRequest) -> WebSocketReady:
        if self._writer is not None:
            raise RuntimeError("Already started")
        try:
            _, protocol, _, _ = self._handshake(request)
        except HTTPException:
            return WebSocketReady(False, None)
        else:
            return WebSocketReady(True, protocol)

    @property
    def closed(self) -> bool:
        return self._closed

    @property
    def close_code(self) -> Optional[int]:
        return self._close_code

    @property
    def ws_protocol(self) -> Optional[str]:
        return self._ws_protocol

    @property
    def compress(self) -> bool:
        return self._compress

    def get_extra_info(self, name: str, default: Any = None) -> Any:
        """Get optional transport information.

        If no value associated with ``name`` is found, ``default`` is returned.
        """
        writer = self._writer
        if writer is None:
            return default
        transport = writer.transport
        if transport is None:
            return default
        return transport.get_extra_info(name, default)

    def exception(self) -> Optional[BaseException]:
        return self._exception

    async def ping(self, message: bytes = b"") -> None:
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")
        await self._writer.send_frame(message, WSMsgType.PING)

    async def pong(self, message: bytes = b"") -> None:
        # unsolicited pong
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")
        await self._writer.send_frame(message, WSMsgType.PONG)

    async def send_frame(
        self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None
    ) -> None:
        """Send a frame over the websocket."""
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")
        await self._writer.send_frame(message, opcode, compress)

    async def send_str(self, data: str, compress: Optional[int] = None) -> None:
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")
        if not isinstance(data, str):
            raise TypeError("data argument must be str (%r)" % type(data))
        await self._writer.send_frame(
            data.encode("utf-8"), WSMsgType.TEXT, compress=compress
        )

    async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError("data argument must be byte-ish (%r)" % type(data))
        await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress)

    async def send_json(
        self,
        data: Any,
        compress: Optional[int] = None,
        *,
        dumps: JSONEncoder = json.dumps,
    ) -> None:
        await self.send_str(dumps(data), compress=compress)

    async def write_eof(self) -> None:  # type: ignore[override]
        if self._eof_sent:
            return
        if self._payload_writer is None:
            raise RuntimeError("Response has not been started")

        await self.close()
        self._eof_sent = True

    async def close(
        self, *, code: int = WSCloseCode.OK, message: bytes = b"", drain: bool = True
    ) -> bool:
        """Close websocket connection."""
        if self._writer is None:
            raise RuntimeError("Call .prepare() first")

        if self._closed:
            return False
        self._set_closed()

        try:
            await self._writer.close(code, message)
            writer = self._payload_writer
            assert writer is not None
            if drain:
                await writer.drain()
        except (asyncio.CancelledError, asyncio.TimeoutError):
            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
            raise
        except Exception as exc:
            self._exception = exc
            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
            return True

        reader = self._reader
        assert reader is not None
        # we need to break `receive()` cycle before we can call
        # `reader.read()` as `close()` may be called from different task
        if self._waiting:
            assert self._loop is not None
            assert self._close_wait is None
            self._close_wait = self._loop.create_future()
            reader.feed_data(WS_CLOSING_MESSAGE)
            await self._close_wait

        if self._closing:
            self._close_transport()
            return True

        try:
            async with async_timeout.timeout(self._timeout):
                msg = await reader.read()
        except asyncio.CancelledError:
            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
            raise
        except Exception as exc:
            self._exception = exc
            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
            return True

        if msg.type is WSMsgType.CLOSE:
            self._set_code_close_transport(msg.data)
            return True

        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
        self._exception = asyncio.TimeoutError()
        return True

    def _set_closing(self, code: int) -> None:
        """Set the close code and mark the connection as closing."""
        self._closing = True
        self._close_code = code
        self._cancel_heartbeat()

    def _set_code_close_transport(self, code: int) -> None:
        """Set the close code and close the transport."""
        self._close_code = code
        self._close_transport()

    def _close_transport(self) -> None:
        """Close the transport."""
        if self._req is not None and self._req.transport is not None:
            self._req.transport.close()

    async def receive(self, timeout: Optional[float] = None) -> WSMessage:
        if self._reader is None:
            raise RuntimeError("Call .prepare() first")

        loop = self._loop
        assert loop is not None
        receive_timeout = timeout or self._receive_timeout
        while True:
            if self._waiting:
                raise RuntimeError("Concurrent call to receive() is not allowed")

            if self._closed:
                self._conn_lost += 1
                if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS:
                    raise RuntimeError("WebSocket connection is closed.")
                return WS_CLOSED_MESSAGE
            elif self._closing:
                return WS_CLOSING_MESSAGE

            try:
                self._waiting = True
                try:
                    if receive_timeout:
                        # Entering the context manager and creating
                        # Timeout() object can take almost 50% of the
                        # run time in this loop so we avoid it if
                        # there is no read timeout.
                        async with async_timeout.timeout(receive_timeout):
                            msg = await self._reader.read()
                    else:
                        msg = await self._reader.read()
                    self._reset_heartbeat()
                finally:
                    self._waiting = False
                    if self._close_wait:
                        set_result(self._close_wait, None)
            except asyncio.TimeoutError:
                raise
            except EofStream:
                self._close_code = WSCloseCode.OK
                await self.close()
                return WS_CLOSED_MESSAGE
            except WebSocketError as exc:
                self._close_code = exc.code
                await self.close(code=exc.code)
                return WSMessageError(data=exc)
            except Exception as exc:
                self._exception = exc
                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)
                await self.close()
                return WSMessageError(data=exc)

            if msg.type is WSMsgType.CLOSE:
                self._set_closing(msg.data)
                # Could be closed while awaiting reader.
                if not self._closed and self._autoclose:  # type: ignore[redundant-expr]
                    # The client is likely going to close the
                    # connection out from under us so we do not
                    # want to drain any pending writes as it will
                    # likely result writing to a broken pipe.
                    await self.close(drain=False)
            elif msg.type is WSMsgType.CLOSING:
                self._set_closing(WSCloseCode.OK)
            elif msg.type is WSMsgType.PING and self._autoping:
                await self.pong(msg.data)
                continue
            elif msg.type is WSMsgType.PONG and self._autoping:
                continue

            return msg

    async def receive_str(self, *, timeout: Optional[float] = None) -> str:
        msg = await self.receive(timeout)
        if msg.type is not WSMsgType.TEXT:
            raise TypeError(
                "Received message {}:{!r} is not WSMsgType.TEXT".format(
                    msg.type, msg.data
                )
            )
        return msg.data

    async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:
        msg = await self.receive(timeout)
        if msg.type is not WSMsgType.BINARY:
            raise TypeError(f"Received message {msg.type}:{msg.data!r} is not bytes")
        return msg.data

    async def receive_json(
        self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None
    ) -> Any:
        data = await self.receive_str(timeout=timeout)
        return loads(data)

    async def write(self, data: bytes) -> None:
        raise RuntimeError("Cannot call .write() for websocket")

    def __aiter__(self) -> "WebSocketResponse":
        return self

    async def __anext__(self) -> WSMessage:
        msg = await self.receive()
        if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):
            raise StopAsyncIteration
        return msg

    def _cancel(self, exc: BaseException) -> None:
        # web_protocol calls this from connection_lost
        # or when the server is shutting down.
        self._closing = True
        self._cancel_heartbeat()
        if self._reader is not None:
            set_exception(self._reader, exc)

```
--- 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