{
    "file_diffs": [
        {
            "old_file_content": "",
            "new_file_content": "Fixed :py:meth:`WebSocketResponse.close() <aiohttp.web.WebSocketResponse.close>` to discard non-close messages within its timeout window after sending close -- by :user:`lenard-mosys`.\n",
            "header": {
                "file": {
                    "path": "CHANGES/9506.bugfix.rst"
                },
                "misc_line": "new file mode 100644"
            },
            "index_line": {
                "old_commit_hash": "00000000",
                "new_commit_hash": "05ad6a59",
                "mode": ""
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "/dev/null"
            },
            "plus_file": {
                "path": "b/CHANGES/9506.bugfix.rst"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 0,
                            "length": 0
                        },
                        "new_range": {
                            "start": 1,
                            "length": null
                        },
                        "section": ""
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "Fixed :py:meth:`WebSocketResponse.close() <aiohttp.web.WebSocketResponse.close>` to discard non-close messages within its timeout window after sending close -- by :user:`lenard-mosys`.",
                                "type": "added"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "- Contributors -\n----------------\nA. Jesse Jiryu Davis\nAbdur Rehman Ali\nAdam Bannister\nAdam Cooper\nAdam Horacek\nAdam Mills\nAdrian Krupa\nAdrián Chaves\nAhmed Tahri\nAlan Tse\nAlec Hanefeld\nAlejandro Gómez\nAleksandr Danshyn\nAleksey Kutepov\nAlex Hayes\nAlex Key\nAlex Khomchenko\nAlex Kuzmenko\nAlex Lisovoy\nAlexander Bayandin\nAlexander Karpinsky\nAlexander Koshevoy\nAlexander Malev\nAlexander Mohr\nAlexander Shorin\nAlexander Travov\nAlexandru Mihai\nAlexey Firsov\nAlexey Nikitin\nAlexey Popravka\nAlexey Stepanov\nAmin Etesamian\nAmit Tulshyan\nAmy Boyle\nAnas El Amraoui\nAnders Melchiorsen\nAndrei Ursulenko\nAndrej Antonov\nAndrew Leech\nAndrew Lytvyn\nAndrew Svetlov\nAndrew Zhou\nAndrii Soldatenko\nAnes Abismail\nAntoine Pietri\nAnton Kasyanov\nAnton Zhdan-Pushkin\nArcadiy Ivanov\nArseny Timoniq\nArtem Yushkovskiy\nArthur Darcet\nAustin Scola\nBen Bader\nBen Greiner\nBen Kallus\nBen Timby\nBenedikt Reinartz\nBob Haddleton\nBoris Feld\nBoyi Chen\nBrett Cannon\nBrett Higgins\nBrian Bouterse\nBrian C. Lane\nBrian Muller\nBruce Merry\nBruno Souza Cabral\nBryan Kok\nBryce Drennan\nCarl George\nCecile Tonglet\nChien-Wei Huang\nChih-Yuan Chen\nChris AtLee\nChris Laws\nChris Moore\nChris Shucksmith\nChristopher Schmitt\nClaudiu Popa\nColin Dunklau\nCong Xu\nDamien Nadé\nDan King\nDan Xu\nDaniel García\nDaniel Golding\nDaniel Grossmann-Kavanagh\nDaniel Nelson\nDanny Song\nDavid Bibb\nDavid Michael Brown\nDenilson Amorim\nDenis Matiychuk\nDenis Moshensky\nDennis Kliban\nDima Veselov\nDimitar Dimitrov\nDiogo Dutra da Mata\nDmitriy Safonov\nDmitry Doroshev\nDmitry Erlikh\nDmitry Lukashin\nDmitry Marakasov\nDmitry Shamov\nDmitry Trofimov\nDmytro Bohomiakov\nDmytro Kuznetsov\nDustin J. Mitchell\nEduard Iskandarov\nEli Ribble\nElizabeth Leddy\nEnrique Saez\nEric Sheng\nErich Healy\nErik Peterson\nEugene Chernyshov\nEugene Naydenov\nEugene Nikolaiev\nEugene Tolmachev\nEvan Kepner\nEvert Lammerts\nFelix Yan\nFernanda Guimarães\nFichteFoll\nFlorian Scheffler\nFranek Magiera\nFrederik Gladhorn\nFrederik Peter Aalund\nGabriel Tremblay\nGang Ji\nGary Wilson Jr.\nGennady Andreyev\nGeorges Dubus\nGreg Holt\nGregory Haynes\nGus Goulart\nGustavo Carneiro\nGünther Jena\nHans Adema\nHarmon Y.\nHarry Liu\nHiroshi Ogawa\nHrishikesh Paranjape\nHu Bo\nHugh Young\nHugo Herter\nHugo Hromic\nHugo van Kemenade\nHynek Schlawack\nIgor Alexandrov\nIgor Bolshakov\nIgor Davydenko\nIgor Mozharovsky\nIgor Pavlov\nIllia Volochii\nIlya Chichak\nIlya Gruzinov\nIngmar Steen\nIvan Lakovic\nIvan Larin\nJ. Nick Koston\nJacob Champion\nJaesung Lee\nJake Davis\nJakob Ackermann\nJakub Wilk\nJan Buchar\nJan Gosmann\nJarno Elonen\nJashandeep Sohi\nJean-Baptiste Estival\nJens Steinhauser\nJeonghun Lee\nJeongkyu Shin\nJeroen van der Heijden\nJesus Cea\nJian Zeng\nJinkyu Yi\nJoel Watts\nJohn Parton\nJon Nabozny\nJonas Krüger Svensson\nJonas Obrist\nJonathan Ballet\nJonathan Wright\nJonny Tan\nJoongi Kim\nJordan Borean\nJosep Cugat\nJosh Junon\nJoshu Coats\nJulia Tsemusheva\nJulien Duponchelle\nJungkook Park\nJunjie Tao\nJunyeong Jeong\nJustas Trimailovas\nJustin Foo\nJustin Turner Arthur\nKay Zheng\nKevin Samuel\nKimmo Parviainen-Jalanko\nKirill Klenov\nKirill Malovitsa\nKonstantin Shutkin\nKonstantin Valetov\nKrzysztof Blazewicz\nKyrylo Perevozchikov\nKyungmin Lee\nLars P. Søndergaard\nLee LieWhite\nLiu Hua\nLouis-Philippe Huberdeau\nLoïc Lajeanne\nLu Gong\nLubomir Gelo\nLudovic Gasc\nLuis Pedrosa\nLukasz Marcin Dobrzanski\nMakc Belousow\nManuel Miranda\nMarat Sharafutdinov\nMarc Mueller\nMarco Paolini\nMarcus Stojcevich\nMariano Anaya\nMariusz Masztalerczuk\nMarko Kohtala\nMartijn Pieters\nMartin Melka\nMartin Richard\nMartin Sucha\nMathias Fröjdman\nMathieu Dugré\nMatt VanEseltine\nMatthias Marquardt\nMatthieu Hauglustaine\nMatthieu Rigal\nMatvey Tingaev\nMeet Mangukiya\nMeshya\nMichael Ihnatenko\nMichał Górny\nMikhail Burshteyn\nMikhail Kashkin\nMikhail Lukyanchenko\nMikhail Nacharov\nMisha Behersky\nMitchell Ferree\nMorgan Delahaye-Prat\nMoss Collum\nMun Gwan-gyeong\nNavid Sheikhol\nNicolas Braem\nNikolay Kim\nNikolay Novik\nNikolay Tiunov\nNándor Mátravölgyi\nOisin Aylward\nOlaf Conradi\nPahaz Blinov\nPanagiotis Kolokotronis\nPankaj Pandey\nParag Jain\nPau Freixes\nPaul Colomiets\nPaul J. Dorn\nPaulius Šileikis\nPaulus Schoutsen\nPavel Kamaev\nPavel Polyakov\nPavel Sapezhko\nPavol Vargovčík\nPawel Kowalski\nPawel Miech\nPepe Osca\nPhilipp A.\nPierre-Louis Peeters\nPieter van Beek\nQiao Han\nRafael Viotti\nRahul Nahata\nRaphael Bialon\nRaúl Cumplido\nRequired Field\nRobert Lu\nRobert Nikolich\nRoman Podoliaka\nRong Zhang\nSamir Akarioh\nSamuel Colvin\nSean Hunt\nSebastian Acuna\nSebastian Hanula\nSebastian Hüther\nSebastien Geffroy\nSeongSoo Cho\nSergey Ninua\nSergey Skripnick\nSerhii Charykov\nSerhii Kostel\nSerhiy Storchaka\nShubh Agarwal\nSimon Kennedy\nSin-Woo Bang\nStanislas Plum\nStanislav Prokop\nStefan Tjarks\nStepan Pletnev\nStephan Jaensch\nStephen Cirelli\nStephen Granade\nSteve Repsher\nSteven Seguin\nSunghyun Hwang\nSunit Deshpande\nSviatoslav Bulbakha\nSviatoslav Sydorenko\nTaha Jahangir\nTaras Voinarovskyi\nTerence Honles\nThanos Lefteris\nThijs Vermeir\nThomas Forbes\nThomas Grainger\nTolga Tezel\nTomasz Trebski\nToshiaki Tanaka\nTrinh Hoang Nhu\nTymofii Tsiapa\nVadim Suharnikov\nVaibhav Sagar\nVamsi Krishna Avula\nVasiliy Faronov\nVasyl Baran\nViacheslav Greshilov\nVictor Collod\nVictor Kovtun\nVikas Kawadia\nViktor Danyliuk\nVille Skyttä\nVincent Maillol\nVitalik Verhovodov\nVitaly Haritonsky\nVitaly Magerya\nVladimir Kamarzin\nVladimir Kozlovski\nVladimir Rutsky\nVladimir Shulyak\nVladimir Zakharov\nVladyslav Bohaichuk\nVladyslav Bondar\nW. Trevor King\nWei Lin\nWeiwei Wang\nWill Fatherley\nWill McGugan\nWillem de Groot\nWilliam Grzybowski\nWilliam S.\nWilson Ong\nwouter bolsterlee\nXavier Halloran\nXiang Li\nYang Zhou\nYannick Koechlin\nYannick Péroux\nYe Cao\nYegor Roganov\nYifei Kong\nYoung-Ho Cha\nYuriy Shatrov\nYury Pliner\nYury Selivanov\nYusuke Tsutsumi\nYuval Ofir\nYuvi Panda\nZainab Lawal\nZeal Wierslee\nZlatan Sičanica\nŁukasz Setla\nМарк Коренберг\nСемён Марьясин\n",
            "new_file_content": "- Contributors -\n----------------\nA. Jesse Jiryu Davis\nAbdur Rehman Ali\nAdam Bannister\nAdam Cooper\nAdam Horacek\nAdam Mills\nAdrian Krupa\nAdrián Chaves\nAhmed Tahri\nAlan Tse\nAlec Hanefeld\nAlejandro Gómez\nAleksandr Danshyn\nAleksey Kutepov\nAlex Hayes\nAlex Key\nAlex Khomchenko\nAlex Kuzmenko\nAlex Lisovoy\nAlexander Bayandin\nAlexander Karpinsky\nAlexander Koshevoy\nAlexander Malev\nAlexander Mohr\nAlexander Shorin\nAlexander Travov\nAlexandru Mihai\nAlexey Firsov\nAlexey Nikitin\nAlexey Popravka\nAlexey Stepanov\nAmin Etesamian\nAmit Tulshyan\nAmy Boyle\nAnas El Amraoui\nAnders Melchiorsen\nAndrei Ursulenko\nAndrej Antonov\nAndrew Leech\nAndrew Lytvyn\nAndrew Svetlov\nAndrew Zhou\nAndrii Soldatenko\nAnes Abismail\nAntoine Pietri\nAnton Kasyanov\nAnton Zhdan-Pushkin\nArcadiy Ivanov\nArseny Timoniq\nArtem Yushkovskiy\nArthur Darcet\nAustin Scola\nBen Bader\nBen Greiner\nBen Kallus\nBen Timby\nBenedikt Reinartz\nBob Haddleton\nBoris Feld\nBoyi Chen\nBrett Cannon\nBrett Higgins\nBrian Bouterse\nBrian C. Lane\nBrian Muller\nBruce Merry\nBruno Souza Cabral\nBryan Kok\nBryce Drennan\nCarl George\nCecile Tonglet\nChien-Wei Huang\nChih-Yuan Chen\nChris AtLee\nChris Laws\nChris Moore\nChris Shucksmith\nChristopher Schmitt\nClaudiu Popa\nColin Dunklau\nCong Xu\nDamien Nadé\nDan King\nDan Xu\nDaniel García\nDaniel Golding\nDaniel Grossmann-Kavanagh\nDaniel Nelson\nDanny Song\nDavid Bibb\nDavid Michael Brown\nDenilson Amorim\nDenis Matiychuk\nDenis Moshensky\nDennis Kliban\nDima Veselov\nDimitar Dimitrov\nDiogo Dutra da Mata\nDmitriy Safonov\nDmitry Doroshev\nDmitry Erlikh\nDmitry Lukashin\nDmitry Marakasov\nDmitry Shamov\nDmitry Trofimov\nDmytro Bohomiakov\nDmytro Kuznetsov\nDustin J. Mitchell\nEduard Iskandarov\nEli Ribble\nElizabeth Leddy\nEnrique Saez\nEric Sheng\nErich Healy\nErik Peterson\nEugene Chernyshov\nEugene Naydenov\nEugene Nikolaiev\nEugene Tolmachev\nEvan Kepner\nEvert Lammerts\nFelix Yan\nFernanda Guimarães\nFichteFoll\nFlorian Scheffler\nFranek Magiera\nFrederik Gladhorn\nFrederik Peter Aalund\nGabriel Tremblay\nGang Ji\nGary Wilson Jr.\nGennady Andreyev\nGeorges Dubus\nGreg Holt\nGregory Haynes\nGus Goulart\nGustavo Carneiro\nGünther Jena\nHans Adema\nHarmon Y.\nHarry Liu\nHiroshi Ogawa\nHrishikesh Paranjape\nHu Bo\nHugh Young\nHugo Herter\nHugo Hromic\nHugo van Kemenade\nHynek Schlawack\nIgor Alexandrov\nIgor Bolshakov\nIgor Davydenko\nIgor Mozharovsky\nIgor Pavlov\nIllia Volochii\nIlya Chichak\nIlya Gruzinov\nIngmar Steen\nIvan Lakovic\nIvan Larin\nJ. Nick Koston\nJacob Champion\nJaesung Lee\nJake Davis\nJakob Ackermann\nJakub Wilk\nJan Buchar\nJan Gosmann\nJarno Elonen\nJashandeep Sohi\nJean-Baptiste Estival\nJens Steinhauser\nJeonghun Lee\nJeongkyu Shin\nJeroen van der Heijden\nJesus Cea\nJian Zeng\nJinkyu Yi\nJoel Watts\nJohn Parton\nJon Nabozny\nJonas Krüger Svensson\nJonas Obrist\nJonathan Ballet\nJonathan Wright\nJonny Tan\nJoongi Kim\nJordan Borean\nJosep Cugat\nJosh Junon\nJoshu Coats\nJulia Tsemusheva\nJulien Duponchelle\nJungkook Park\nJunjie Tao\nJunyeong Jeong\nJustas Trimailovas\nJustin Foo\nJustin Turner Arthur\nKay Zheng\nKevin Samuel\nKimmo Parviainen-Jalanko\nKirill Klenov\nKirill Malovitsa\nKonstantin Shutkin\nKonstantin Valetov\nKrzysztof Blazewicz\nKyrylo Perevozchikov\nKyungmin Lee\nLars P. Søndergaard\nLee LieWhite\nLiu Hua\nLouis-Philippe Huberdeau\nLoïc Lajeanne\nLu Gong\nLubomir Gelo\nLudovic Gasc\nLuis Pedrosa\nLukasz Marcin Dobrzanski\nLénárd Szolnoki\nMakc Belousow\nManuel Miranda\nMarat Sharafutdinov\nMarc Mueller\nMarco Paolini\nMarcus Stojcevich\nMariano Anaya\nMariusz Masztalerczuk\nMarko Kohtala\nMartijn Pieters\nMartin Melka\nMartin Richard\nMartin Sucha\nMathias Fröjdman\nMathieu Dugré\nMatt VanEseltine\nMatthias Marquardt\nMatthieu Hauglustaine\nMatthieu Rigal\nMatvey Tingaev\nMeet Mangukiya\nMeshya\nMichael Ihnatenko\nMichał Górny\nMikhail Burshteyn\nMikhail Kashkin\nMikhail Lukyanchenko\nMikhail Nacharov\nMisha Behersky\nMitchell Ferree\nMorgan Delahaye-Prat\nMoss Collum\nMun Gwan-gyeong\nNavid Sheikhol\nNicolas Braem\nNikolay Kim\nNikolay Novik\nNikolay Tiunov\nNándor Mátravölgyi\nOisin Aylward\nOlaf Conradi\nPahaz Blinov\nPanagiotis Kolokotronis\nPankaj Pandey\nParag Jain\nPau Freixes\nPaul Colomiets\nPaul J. Dorn\nPaulius Šileikis\nPaulus Schoutsen\nPavel Kamaev\nPavel Polyakov\nPavel Sapezhko\nPavol Vargovčík\nPawel Kowalski\nPawel Miech\nPepe Osca\nPhilipp A.\nPierre-Louis Peeters\nPieter van Beek\nQiao Han\nRafael Viotti\nRahul Nahata\nRaphael Bialon\nRaúl Cumplido\nRequired Field\nRobert Lu\nRobert Nikolich\nRoman Podoliaka\nRong Zhang\nSamir Akarioh\nSamuel Colvin\nSean Hunt\nSebastian Acuna\nSebastian Hanula\nSebastian Hüther\nSebastien Geffroy\nSeongSoo Cho\nSergey Ninua\nSergey Skripnick\nSerhii Charykov\nSerhii Kostel\nSerhiy Storchaka\nShubh Agarwal\nSimon Kennedy\nSin-Woo Bang\nStanislas Plum\nStanislav Prokop\nStefan Tjarks\nStepan Pletnev\nStephan Jaensch\nStephen Cirelli\nStephen Granade\nSteve Repsher\nSteven Seguin\nSunghyun Hwang\nSunit Deshpande\nSviatoslav Bulbakha\nSviatoslav Sydorenko\nTaha Jahangir\nTaras Voinarovskyi\nTerence Honles\nThanos Lefteris\nThijs Vermeir\nThomas Forbes\nThomas Grainger\nTolga Tezel\nTomasz Trebski\nToshiaki Tanaka\nTrinh Hoang Nhu\nTymofii Tsiapa\nVadim Suharnikov\nVaibhav Sagar\nVamsi Krishna Avula\nVasiliy Faronov\nVasyl Baran\nViacheslav Greshilov\nVictor Collod\nVictor Kovtun\nVikas Kawadia\nViktor Danyliuk\nVille Skyttä\nVincent Maillol\nVitalik Verhovodov\nVitaly Haritonsky\nVitaly Magerya\nVladimir Kamarzin\nVladimir Kozlovski\nVladimir Rutsky\nVladimir Shulyak\nVladimir Zakharov\nVladyslav Bohaichuk\nVladyslav Bondar\nW. Trevor King\nWei Lin\nWeiwei Wang\nWill Fatherley\nWill McGugan\nWillem de Groot\nWilliam Grzybowski\nWilliam S.\nWilson Ong\nwouter bolsterlee\nXavier Halloran\nXiang Li\nYang Zhou\nYannick Koechlin\nYannick Péroux\nYe Cao\nYegor Roganov\nYifei Kong\nYoung-Ho Cha\nYuriy Shatrov\nYury Pliner\nYury Selivanov\nYusuke Tsutsumi\nYuval Ofir\nYuvi Panda\nZainab Lawal\nZeal Wierslee\nZlatan Sičanica\nŁukasz Setla\nМарк Коренберг\nСемён Марьясин\n",
            "header": {
                "file": {
                    "path": "CONTRIBUTORS.txt"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "60ff22d1",
                "new_commit_hash": "6adb3b97",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/CONTRIBUTORS.txt"
            },
            "plus_file": {
                "path": "b/CONTRIBUTORS.txt"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 219,
                            "length": 6
                        },
                        "new_range": {
                            "start": 219,
                            "length": 7
                        },
                        "section": "Lubomir Gelo"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "Ludovic Gasc",
                                "type": "context"
                            },
                            {
                                "content": "Luis Pedrosa",
                                "type": "context"
                            },
                            {
                                "content": "Lukasz Marcin Dobrzanski",
                                "type": "context"
                            },
                            {
                                "content": "Lénárd Szolnoki",
                                "type": "added"
                            },
                            {
                                "content": "Makc Belousow",
                                "type": "context"
                            },
                            {
                                "content": "Manuel Miranda",
                                "type": "context"
                            },
                            {
                                "content": "Marat Sharafutdinov",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import asyncio\nimport base64\nimport binascii\nimport hashlib\nimport json\nimport sys\nfrom typing import Any, Final, Iterable, Optional, Tuple, cast\n\nimport attr\nfrom multidict import CIMultiDict\n\nfrom . import hdrs\nfrom ._websocket.writer import DEFAULT_LIMIT\nfrom .abc import AbstractStreamWriter\nfrom .client_exceptions import WSMessageTypeError\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 as WSMsgType,\n    ws_ext_gen,\n    ws_ext_parse,\n)\nfrom .http_websocket import _INTERNAL_RECEIVE_TYPES\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@attr.s(auto_attribs=True, frozen=True, slots=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\n    _length_check = False\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._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(WSMessage(WSMsgType.ERROR, exc, 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: WSCloseCode) -> 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: WSCloseCode) -> 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        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 WSMessage(WSMsgType.CLOSED, None, None)\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessage(WSMsgType.ERROR, exc, None)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessage(WSMsgType.ERROR, exc, None)\n\n            if msg.type not in _INTERNAL_RECEIVE_TYPES:\n                # If its not a close/closing/ping/pong message\n                # we can return it immediately\n                return msg\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:\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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT\"\n            )\n        return cast(str, 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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY\"\n            )\n        return cast(bytes, 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 hashlib\nimport json\nimport sys\nfrom typing import Any, Final, Iterable, Optional, Tuple, cast\n\nimport attr\nfrom multidict import CIMultiDict\n\nfrom . import hdrs\nfrom ._websocket.writer import DEFAULT_LIMIT\nfrom .abc import AbstractStreamWriter\nfrom .client_exceptions import WSMessageTypeError\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 as WSMsgType,\n    ws_ext_gen,\n    ws_ext_parse,\n)\nfrom .http_websocket import _INTERNAL_RECEIVE_TYPES\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@attr.s(auto_attribs=True, frozen=True, slots=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\n    _length_check = False\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._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(WSMessage(WSMsgType.ERROR, exc, 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                while True:\n                    msg = await reader.read()\n                    if msg.type is WSMsgType.CLOSE:\n                        self._set_code_close_transport(msg.data)\n                        return True\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    def _set_closing(self, code: WSCloseCode) -> 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: WSCloseCode) -> 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        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 WSMessage(WSMsgType.CLOSED, None, None)\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessage(WSMsgType.ERROR, exc, None)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessage(WSMsgType.ERROR, exc, None)\n\n            if msg.type not in _INTERNAL_RECEIVE_TYPES:\n                # If its not a close/closing/ping/pong message\n                # we can return it immediately\n                return msg\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:\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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT\"\n            )\n        return cast(str, 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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY\"\n            )\n        return cast(bytes, 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": "932cd0db",
                "new_commit_hash": "bf93e188",
                "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": 473,
                            "length": 7
                        },
                        "new_range": {
                            "start": 473,
                            "length": 11
                        },
                        "section": "class WebSocketResponse(StreamResponse):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        try:",
                                "type": "context"
                            },
                            {
                                "content": "            async with async_timeout.timeout(self._timeout):",
                                "type": "context"
                            },
                            {
                                "content": "                msg = await reader.read()",
                                "type": "deleted"
                            },
                            {
                                "content": "                while True:",
                                "type": "added"
                            },
                            {
                                "content": "                    msg = await reader.read()",
                                "type": "added"
                            },
                            {
                                "content": "                    if msg.type is WSMsgType.CLOSE:",
                                "type": "added"
                            },
                            {
                                "content": "                        self._set_code_close_transport(msg.data)",
                                "type": "added"
                            },
                            {
                                "content": "                        return True",
                                "type": "added"
                            },
                            {
                                "content": "        except asyncio.CancelledError:",
                                "type": "context"
                            },
                            {
                                "content": "            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)",
                                "type": "context"
                            },
                            {
                                "content": "            raise",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "class",
                            "name": "WebSocketResponse",
                            "content": "class WebSocketResponse(StreamResponse):\n\n    _length_check = False\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._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(WSMessage(WSMsgType.ERROR, exc, 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: WSCloseCode) -> 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: WSCloseCode) -> 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        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 WSMessage(WSMsgType.CLOSED, None, None)\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessage(WSMsgType.ERROR, exc, None)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessage(WSMsgType.ERROR, exc, None)\n\n            if msg.type not in _INTERNAL_RECEIVE_TYPES:\n                # If its not a close/closing/ping/pong message\n                # we can return it immediately\n                return msg\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:\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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT\"\n            )\n        return cast(str, 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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY\"\n            )\n        return cast(bytes, 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": 61,
                            "end_lineno": 623,
                            "parent": null
                        },
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "method",
                            "name": "WebSocketResponse.close",
                            "content": "class WebSocketResponse(StreamResponse):\n\n    _length_check = False\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._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(WSMessage(WSMsgType.ERROR, exc, 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: WSCloseCode) -> 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: WSCloseCode) -> 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        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 WSMessage(WSMsgType.CLOSED, None, None)\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessage(WSMsgType.ERROR, exc, None)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessage(WSMsgType.ERROR, exc, None)\n\n            if msg.type not in _INTERNAL_RECEIVE_TYPES:\n                # If its not a close/closing/ping/pong message\n                # we can return it immediately\n                return msg\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:\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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT\"\n            )\n        return cast(str, 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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY\"\n            )\n        return cast(bytes, 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": 434,
                            "end_lineno": 491,
                            "parent": {
                                "file_name": "aiohttp/web_ws.py",
                                "type": "class",
                                "name": "WebSocketResponse",
                                "content": "class WebSocketResponse(StreamResponse):\n\n    _length_check = False\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._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(WSMessage(WSMsgType.ERROR, exc, 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: WSCloseCode) -> 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: WSCloseCode) -> 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        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 WSMessage(WSMsgType.CLOSED, None, None)\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessage(WSMsgType.ERROR, exc, None)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessage(WSMsgType.ERROR, exc, None)\n\n            if msg.type not in _INTERNAL_RECEIVE_TYPES:\n                # If its not a close/closing/ping/pong message\n                # we can return it immediately\n                return msg\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:\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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT\"\n            )\n        return cast(str, 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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY\"\n            )\n        return cast(bytes, 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": 61,
                                "end_lineno": 623,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 482,
                            "length": 14
                        },
                        "new_range": {
                            "start": 486,
                            "length": 6
                        },
                        "section": "class WebSocketResponse(StreamResponse):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)",
                                "type": "context"
                            },
                            {
                                "content": "            return True",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        if msg.type is WSMsgType.CLOSE:",
                                "type": "deleted"
                            },
                            {
                                "content": "            self._set_code_close_transport(msg.data)",
                                "type": "deleted"
                            },
                            {
                                "content": "            return True",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "        self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)",
                                "type": "deleted"
                            },
                            {
                                "content": "        self._exception = asyncio.TimeoutError()",
                                "type": "deleted"
                            },
                            {
                                "content": "        return True",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "    def _set_closing(self, code: WSCloseCode) -> None:",
                                "type": "context"
                            },
                            {
                                "content": "        \"\"\"Set the close code and mark the connection as closing.\"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "        self._closing = True",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "class",
                            "name": "WebSocketResponse",
                            "content": "class WebSocketResponse(StreamResponse):\n\n    _length_check = False\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._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(WSMessage(WSMsgType.ERROR, exc, 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: WSCloseCode) -> 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: WSCloseCode) -> 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        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 WSMessage(WSMsgType.CLOSED, None, None)\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessage(WSMsgType.ERROR, exc, None)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessage(WSMsgType.ERROR, exc, None)\n\n            if msg.type not in _INTERNAL_RECEIVE_TYPES:\n                # If its not a close/closing/ping/pong message\n                # we can return it immediately\n                return msg\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:\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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT\"\n            )\n        return cast(str, 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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY\"\n            )\n        return cast(bytes, 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": 61,
                            "end_lineno": 623,
                            "parent": null
                        },
                        {
                            "file_name": "aiohttp/web_ws.py",
                            "type": "method",
                            "name": "WebSocketResponse.close",
                            "content": "class WebSocketResponse(StreamResponse):\n\n    _length_check = False\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._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(WSMessage(WSMsgType.ERROR, exc, 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: WSCloseCode) -> 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: WSCloseCode) -> 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        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 WSMessage(WSMsgType.CLOSED, None, None)\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessage(WSMsgType.ERROR, exc, None)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessage(WSMsgType.ERROR, exc, None)\n\n            if msg.type not in _INTERNAL_RECEIVE_TYPES:\n                # If its not a close/closing/ping/pong message\n                # we can return it immediately\n                return msg\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:\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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT\"\n            )\n        return cast(str, 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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY\"\n            )\n        return cast(bytes, 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": 434,
                            "end_lineno": 491,
                            "parent": {
                                "file_name": "aiohttp/web_ws.py",
                                "type": "class",
                                "name": "WebSocketResponse",
                                "content": "class WebSocketResponse(StreamResponse):\n\n    _length_check = False\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._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(WSMessage(WSMsgType.ERROR, exc, 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: WSCloseCode) -> 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: WSCloseCode) -> 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        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 WSMessage(WSMsgType.CLOSED, None, None)\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessage(WSMsgType.ERROR, exc, None)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessage(WSMsgType.ERROR, exc, None)\n\n            if msg.type not in _INTERNAL_RECEIVE_TYPES:\n                # If its not a close/closing/ping/pong message\n                # we can return it immediately\n                return msg\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:\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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT\"\n            )\n        return cast(str, 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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY\"\n            )\n        return cast(bytes, 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": 61,
                                "end_lineno": 623,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "# HTTP websocket server functional tests\n\nimport asyncio\nimport contextlib\nimport sys\nimport weakref\nfrom typing import Any, NoReturn, Optional\nfrom unittest import mock\n\nimport pytest\n\nimport aiohttp\nfrom aiohttp import web\nfrom aiohttp.http import WSCloseCode, WSMsgType\nfrom aiohttp.pytest_plugin import AiohttpClient\n\n\nasync def test_websocket_can_prepare(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        if not ws.can_prepare(request):\n            raise web.HTTPUpgradeRequired()\n\n        return web.Response()\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    resp = await client.get(\"/\")\n    assert resp.status == 426\n\n\nasync def test_websocket_json(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        if not ws.can_prepare(request):\n            return web.HTTPUpgradeRequired()\n\n        await ws.prepare(request)\n        msg = await ws.receive()\n\n        msg_json = msg.json()\n        answer = msg_json[\"test\"]\n        await ws.send_str(answer)\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    expected_value = \"value\"\n    payload = '{\"test\": \"%s\"}' % expected_value\n    await ws.send_str(payload)\n\n    resp = await ws.receive()\n    assert resp.data == expected_value\n\n\nasync def test_websocket_json_invalid_message(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        try:\n            await ws.receive_json()\n        except ValueError:\n            await ws.send_str(\"ValueError was raised\")\n        else:\n            raise Exception(\"No Exception\")\n        finally:\n            await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    payload = \"NOT A VALID JSON STRING\"\n    await ws.send_str(payload)\n\n    data = await ws.receive_str()\n    assert \"ValueError was raised\" in data\n\n\nasync def test_websocket_send_json(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        data = await ws.receive_json()\n        await ws.send_json(data)\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    expected_value = \"value\"\n    await ws.send_json({\"test\": expected_value})\n\n    data = await ws.receive_json()\n    assert data[\"test\"] == expected_value\n\n\nasync def test_websocket_receive_json(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        data = await ws.receive_json()\n        answer = data[\"test\"]\n        await ws.send_str(answer)\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    expected_value = \"value\"\n    payload = '{\"test\": \"%s\"}' % expected_value\n    await ws.send_str(payload)\n\n    resp = await ws.receive()\n    assert resp.data == expected_value\n\n\nasync def test_send_recv_text(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        msg = await ws.receive_str()\n        await ws.send_str(msg + \"/answer\")\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_str(\"ask\")\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.TEXT\n    assert \"ask/answer\" == msg.data\n\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.CLOSE\n    assert msg.data == WSCloseCode.OK\n    assert msg.extra == \"\"\n\n    assert ws.closed\n    assert ws.close_code == WSCloseCode.OK\n\n    await closed\n\n\nasync def test_send_recv_bytes(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        msg = await ws.receive_bytes()\n        await ws.send_bytes(msg + b\"/answer\")\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_bytes(b\"ask\")\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.BINARY\n    assert b\"ask/answer\" == msg.data\n\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.CLOSE\n    assert msg.data == WSCloseCode.OK\n    assert msg.extra == \"\"\n\n    assert ws.closed\n    assert ws.close_code == WSCloseCode.OK\n\n    await closed\n\n\nasync def test_send_recv_json(loop, aiohttp_client) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        data = await ws.receive_json()\n        await ws.send_json({\"response\": data[\"request\"]})\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n\n    await ws.send_str('{\"request\": \"test\"}')\n    msg = await ws.receive()\n    data = msg.json()\n    assert msg.type == aiohttp.WSMsgType.TEXT\n    assert data[\"response\"] == \"test\"\n\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.CLOSE\n    assert msg.data == WSCloseCode.OK\n    assert msg.extra == \"\"\n\n    await ws.close()\n\n    await closed\n\n\nasync def test_close_timeout(loop, aiohttp_client) -> None:\n    aborted = loop.create_future()\n    elapsed = 1e10  # something big\n\n    async def handler(request):\n        nonlocal elapsed\n        ws = web.WebSocketResponse(timeout=0.1)\n        await ws.prepare(request)\n        assert \"request\" == (await ws.receive_str())\n        await ws.send_str(\"reply\")\n        begin = ws._loop.time()\n        assert await ws.close()\n        elapsed = ws._loop.time() - begin\n        assert ws.close_code == WSCloseCode.ABNORMAL_CLOSURE\n        assert isinstance(ws.exception(), asyncio.TimeoutError)\n        aborted.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_str(\"request\")\n    assert \"reply\" == (await ws.receive_str())\n\n    # The server closes here.  Then the client sends bogus messages with an\n    # interval shorter than server-side close timeout, to make the server\n    # hanging indefinitely.\n    await asyncio.sleep(0.08)\n    msg = await ws._reader.read()\n    assert msg.type == WSMsgType.CLOSE\n\n    await asyncio.sleep(0.08)\n    assert await aborted\n\n    assert elapsed < 0.25, \"close() should have returned before at most 2x timeout.\"\n\n    await ws.close()\n\n\nasync def test_concurrent_close(loop, aiohttp_client) -> None:\n\n    srv_ws = None\n\n    async def handler(request):\n        nonlocal srv_ws\n        ws = srv_ws = web.WebSocketResponse(autoclose=False, protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        await asyncio.sleep(0)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSED\n\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    await srv_ws.close(code=WSCloseCode.INVALID_TEXT)\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await asyncio.sleep(0)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n\n\nasync def test_concurrent_close_multiple_tasks(loop: Any, aiohttp_client: Any) -> None:\n    srv_ws = None\n\n    async def handler(request):\n        nonlocal srv_ws\n        ws = srv_ws = web.WebSocketResponse(autoclose=False, protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        await asyncio.sleep(0)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSED\n\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    task1 = asyncio.create_task(srv_ws.close(code=WSCloseCode.INVALID_TEXT))\n    task2 = asyncio.create_task(srv_ws.close(code=WSCloseCode.INVALID_TEXT))\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await task1\n    await task2\n\n    await asyncio.sleep(0)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n\n\nasync def test_close_op_code_from_client(loop: Any, aiohttp_client: Any) -> None:\n    srv_ws: Optional[web.WebSocketResponse] = None\n\n    async def handler(request):\n        nonlocal srv_ws\n        ws = srv_ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        await asyncio.sleep(0)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws: web.WebSocketResponse = await client.ws_connect(\"/\", protocols=(\"eggs\", \"bar\"))\n\n    await ws._writer.send_frame(b\"\", WSMsgType.CLOSE)\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await asyncio.sleep(0)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n\n\nasync def test_auto_pong_with_closing_by_peer(loop: Any, aiohttp_client: Any) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        await ws.receive()\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, autoping=False)\n    await ws.ping()\n    await ws.send_str(\"ask\")\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n    await closed\n\n\nasync def test_ping(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        await ws.ping(b\"data\")\n        await ws.receive()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PING\n    assert msg.data == b\"data\"\n    await ws.pong()\n    await ws.close()\n    await closed\n\n\nasync def aiohttp_client_ping(loop, aiohttp_client):\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        await ws.receive()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await ws.ping(b\"data\")\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n    await ws.pong()\n    await ws.close()\n\n\nasync def test_pong(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoping=False)\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.PING\n        await ws.pong(b\"data\")\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await ws.ping(b\"data\")\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n\n    await closed\n\n\nasync def test_change_status(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        ws.set_status(200)\n        assert 200 == ws.status\n        await ws.prepare(request)\n        assert 101 == ws.status\n        await ws.close()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await ws.close()\n    await closed\n    await ws.close()\n\n\nasync def test_handle_protocol(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n        await ws.close()\n        assert \"bar\" == ws.ws_protocol\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", protocols=(\"eggs\", \"bar\"))\n\n    await ws.close()\n    await closed\n\n\nasync def test_server_close_handshake(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n        await ws.close()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n    await ws.close()\n    await closed\n\n\nasync def aiohttp_client_close_handshake(loop, aiohttp_client):\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoclose=False, protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert not ws.closed\n        await ws.close()\n        assert ws.closed\n        assert ws.close_code == WSCloseCode.INVALID_TEXT\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSED\n\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    await ws.close(code=WSCloseCode.INVALID_TEXT)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n    await closed\n\n\nasync def test_server_close_handshake_server_eats_client_messages(loop, aiohttp_client):\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n        await ws.close()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\n        \"/\", autoclose=False, autoping=False, protocols=(\"eggs\", \"bar\")\n    )\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await ws.send_str(\"text\")\n    await ws.send_bytes(b\"bytes\")\n    await ws.ping()\n\n    await ws.close()\n    await closed\n\n\nasync def test_receive_timeout(loop, aiohttp_client) -> None:\n    raised = False\n\n    async def handler(request):\n        ws = web.WebSocketResponse(receive_timeout=0.1)\n        await ws.prepare(request)\n\n        try:\n            await ws.receive()\n        except asyncio.TimeoutError:\n            nonlocal raised\n            raised = True\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.receive()\n    await ws.close()\n    assert raised\n\n\nasync def test_custom_receive_timeout(loop, aiohttp_client) -> None:\n    raised = False\n\n    async def handler(request):\n        ws = web.WebSocketResponse(receive_timeout=None)\n        await ws.prepare(request)\n\n        try:\n            await ws.receive(0.1)\n        except asyncio.TimeoutError:\n            nonlocal raised\n            raised = True\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.receive()\n    await ws.close()\n    assert raised\n\n\nasync def test_heartbeat(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n        await ws.receive()\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n\n    assert msg.type == aiohttp.WSMsgType.ping\n\n    await ws.close()\n\n\nasync def test_heartbeat_no_pong(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n\n        await ws.receive()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.ping\n    await ws.close()\n\n\nasync def test_heartbeat_connection_closed(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    \"\"\"Test that the connection is closed while ping is in progress.\"\"\"\n    ping_count = 0\n\n    async def handler(request: web.Request) -> NoReturn:\n        nonlocal ping_count\n        ws_server = web.WebSocketResponse(heartbeat=0.05)\n        await ws_server.prepare(request)\n        # We patch write here to simulate a connection reset error\n        # since if we closed the connection normally, the server would\n        # would cancel the heartbeat task and we wouldn't get a ping\n        with mock.patch.object(\n            ws_server._req.transport, \"write\", side_effect=ConnectionResetError\n        ), mock.patch.object(\n            ws_server._writer, \"send_frame\", wraps=ws_server._writer.send_frame\n        ) as send_frame:\n            try:\n                await ws_server.receive()\n            finally:\n                ping_count = send_frame.call_args_list.count(\n                    mock.call(b\"\", WSMsgType.PING)\n                )\n        assert False\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSED\n    assert msg.extra is None\n    assert ws.close_code == WSCloseCode.ABNORMAL_CLOSURE\n    assert ping_count == 1\n    await ws.close()\n\n\nasync def test_heartbeat_failure_ends_receive(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    \"\"\"Test that no heartbeat response to the server ends the receive call.\"\"\"\n    ws_server_close_code = None\n    ws_server_exception = None\n\n    async def handler(request: web.Request) -> NoReturn:\n        nonlocal ws_server_close_code, ws_server_exception\n        ws_server = web.WebSocketResponse(heartbeat=0.05)\n        await ws_server.prepare(request)\n        try:\n            await ws_server.receive()\n        finally:\n            ws_server_close_code = ws_server.close_code\n            ws_server_exception = ws_server.exception()\n        assert False\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.PING\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSED\n    assert ws.close_code == WSCloseCode.ABNORMAL_CLOSURE\n    assert ws_server_close_code == WSCloseCode.ABNORMAL_CLOSURE\n    assert isinstance(ws_server_exception, asyncio.TimeoutError)\n    await ws.close()\n\n\nasync def test_heartbeat_no_pong_send_many_messages(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    \"\"\"Test no pong after sending many messages.\"\"\"\n\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n        for _ in range(10):\n            await ws.send_str(\"test\")\n\n        await ws.receive()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    for _ in range(10):\n        msg = await ws.receive()\n        assert msg.type is aiohttp.WSMsgType.TEXT\n        assert msg.data == \"test\"\n\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.PING\n    await ws.close()\n\n\nasync def test_heartbeat_no_pong_receive_many_messages(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    \"\"\"Test no pong after receiving many messages.\"\"\"\n\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n        for _ in range(10):\n            server_msg = await ws.receive()\n            assert server_msg.type is aiohttp.WSMsgType.TEXT\n\n        await ws.receive()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    for _ in range(10):\n        await ws.send_str(\"test\")\n\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.PING\n    await ws.close()\n\n\nasync def test_server_ws_async_for(loop: Any, aiohttp_server: Any) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        async for msg in ws:\n            assert msg.type == aiohttp.WSMsgType.TEXT\n            s = msg.data\n            await ws.send_str(s + \"/answer\")\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    server = await aiohttp_server(app)\n\n    async with aiohttp.ClientSession() as sm:\n        async with sm.ws_connect(server.make_url(\"/\")) as resp:\n\n            items = [\"q1\", \"q2\", \"q3\"]\n            for item in items:\n                await resp.send_str(item)\n                msg = await resp.receive()\n                assert msg.type == aiohttp.WSMsgType.TEXT\n                assert item + \"/answer\" == msg.data\n\n            await resp.close()\n            await closed\n\n\nasync def test_closed_async_for(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        messages = []\n        async for msg in ws:\n            messages.append(msg)\n            if \"stop\" == msg.data:\n                await ws.send_str(\"stopping\")\n                await ws.close()\n\n        assert 1 == len(messages)\n        assert messages[0].type == WSMsgType.TEXT\n        assert messages[0].data == \"stop\"\n\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_str(\"stop\")\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.TEXT\n    assert msg.data == \"stopping\"\n\n    await ws.close()\n    await closed\n\n\nasync def test_websocket_disable_keepalive(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        if not ws.can_prepare(request):\n            return web.Response(text=\"OK\")\n        assert request.protocol._keepalive\n        await ws.prepare(request)\n        assert not request.protocol._keepalive\n        assert not request.protocol._keepalive_handle\n\n        await ws.send_str(\"OK\")\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    resp = await client.get(\"/\")\n    txt = await resp.text()\n    assert txt == \"OK\"\n\n    ws = await client.ws_connect(\"/\")\n    data = await ws.receive_str()\n    assert data == \"OK\"\n\n\nasync def test_receive_str_nonstring(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        ws = web.WebSocketResponse()\n        assert ws.can_prepare(request)\n\n        await ws.prepare(request)\n        await ws.send_bytes(b\"answer\")\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    with pytest.raises(TypeError):\n        await ws.receive_str()\n\n\nasync def test_receive_bytes_nonbytes(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    async def handler(request: web.Request) -> NoReturn:\n        ws = web.WebSocketResponse()\n        assert ws.can_prepare(request)\n\n        await ws.prepare(request)\n        await ws.send_str(\"answer\")\n        assert False\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    with pytest.raises(TypeError):\n        await ws.receive_bytes()\n\n\nasync def test_bug3380(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    async def handle_null(request):\n        return aiohttp.web.json_response({\"err\": None})\n\n    async def ws_handler(request: web.Request) -> web.Response:\n        return web.Response(status=401)\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/ws\", ws_handler)\n    app.router.add_route(\"GET\", \"/api/null\", handle_null)\n\n    client = await aiohttp_client(app)\n\n    resp = await client.get(\"/api/null\")\n    assert (await resp.json()) == {\"err\": None}\n    resp.close()\n\n    with pytest.raises(aiohttp.WSServerHandshakeError):\n        await client.ws_connect(\"/ws\")\n\n    resp = await client.get(\"/api/null\", timeout=1)\n    assert (await resp.json()) == {\"err\": None}\n    resp.close()\n\n\nasync def test_receive_being_cancelled_keeps_connection_open(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoping=False)\n        await ws.prepare(request)\n\n        task = asyncio.create_task(ws.receive())\n        await asyncio.sleep(0)\n        task.cancel()\n        with contextlib.suppress(asyncio.CancelledError):\n            await task\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.PING\n        await asyncio.sleep(0)\n        await ws.pong(b\"data\")\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await asyncio.sleep(0)\n    await ws.ping(b\"data\")\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n\n    await closed\n\n\nasync def test_receive_timeout_keeps_connection_open(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    closed = loop.create_future()\n    timed_out = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoping=False)\n        await ws.prepare(request)\n\n        task = asyncio.create_task(ws.receive(sys.float_info.min))\n        with contextlib.suppress(asyncio.TimeoutError):\n            await task\n\n        timed_out.set_result(None)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.PING\n        await asyncio.sleep(0)\n        await ws.pong(b\"data\")\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await timed_out\n    await ws.ping(b\"data\")\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n\n    await closed\n\n\nasync def test_websocket_shutdown(aiohttp_client: AiohttpClient) -> None:\n    \"\"\"Test that the client websocket gets the close message when the server is shutting down.\"\"\"\n    url = \"/ws\"\n    app = web.Application()\n    websockets = web.AppKey(\"websockets\", weakref.WeakSet)\n    app[websockets] = weakref.WeakSet()\n\n    # need for send signal shutdown server\n    shutdown_websockets = web.AppKey(\"shutdown_websockets\", weakref.WeakSet)\n    app[shutdown_websockets] = weakref.WeakSet()\n\n    async def websocket_handler(request: web.Request) -> web.WebSocketResponse:\n        websocket = web.WebSocketResponse()\n        await websocket.prepare(request)\n        request.app[websockets].add(websocket)\n        request.app[shutdown_websockets].add(websocket)\n\n        try:\n            async for message in websocket:\n                await websocket.send_json({\"ok\": True, \"message\": message.json()})\n        finally:\n            request.app[websockets].discard(websocket)\n\n        return websocket\n\n    async def on_shutdown(app: web.Application) -> None:\n        while app[shutdown_websockets]:\n            websocket = app[shutdown_websockets].pop()\n            await websocket.close(\n                code=aiohttp.WSCloseCode.GOING_AWAY,\n                message=\"Server shutdown\",\n            )\n\n    app.router.add_get(url, websocket_handler)\n    app.on_shutdown.append(on_shutdown)\n\n    client = await aiohttp_client(app)\n\n    websocket = await client.ws_connect(url)\n\n    message = {\"message\": \"hi\"}\n    await websocket.send_json(message)\n    reply = await websocket.receive_json()\n    assert reply == {\"ok\": True, \"message\": message}\n\n    await app.shutdown()\n\n    assert websocket.closed is False\n\n    reply = await websocket.receive()\n\n    assert reply.type is aiohttp.http.WSMsgType.CLOSE\n    assert reply.data == aiohttp.WSCloseCode.GOING_AWAY\n    assert reply.extra == \"Server shutdown\"\n\n    assert websocket.closed is True\n\n\nasync def test_ws_close_return_code(aiohttp_client: AiohttpClient) -> None:\n    \"\"\"Test that the close code is returned when the server closes the connection.\"\"\"\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        await ws.receive()\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    resp = await client.ws_connect(\"/\")\n    await resp.send_str(\"some data\")\n    msg = await resp.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSE\n    assert resp.close_code == WSCloseCode.OK\n\n\nasync def test_abnormal_closure_when_server_does_not_receive(\n    aiohttp_client: AiohttpClient,\n) -> None:\n    \"\"\"Test abnormal closure when the server closes and a message is pending.\"\"\"\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    resp = await client.ws_connect(\"/\")\n    await resp.send_str(\"some data\")\n    await asyncio.sleep(0.1)\n    msg = await resp.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSE\n    assert resp.close_code == WSCloseCode.ABNORMAL_CLOSURE\n",
            "new_file_content": "# HTTP websocket server functional tests\n\nimport asyncio\nimport contextlib\nimport sys\nimport weakref\nfrom typing import Any, NoReturn, Optional\nfrom unittest import mock\n\nimport pytest\n\nimport aiohttp\nfrom aiohttp import web\nfrom aiohttp.http import WSCloseCode, WSMsgType\nfrom aiohttp.pytest_plugin import AiohttpClient\n\n\nasync def test_websocket_can_prepare(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        if not ws.can_prepare(request):\n            raise web.HTTPUpgradeRequired()\n\n        return web.Response()\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    resp = await client.get(\"/\")\n    assert resp.status == 426\n\n\nasync def test_websocket_json(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        if not ws.can_prepare(request):\n            return web.HTTPUpgradeRequired()\n\n        await ws.prepare(request)\n        msg = await ws.receive()\n\n        msg_json = msg.json()\n        answer = msg_json[\"test\"]\n        await ws.send_str(answer)\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    expected_value = \"value\"\n    payload = '{\"test\": \"%s\"}' % expected_value\n    await ws.send_str(payload)\n\n    resp = await ws.receive()\n    assert resp.data == expected_value\n\n\nasync def test_websocket_json_invalid_message(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        try:\n            await ws.receive_json()\n        except ValueError:\n            await ws.send_str(\"ValueError was raised\")\n        else:\n            raise Exception(\"No Exception\")\n        finally:\n            await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    payload = \"NOT A VALID JSON STRING\"\n    await ws.send_str(payload)\n\n    data = await ws.receive_str()\n    assert \"ValueError was raised\" in data\n\n\nasync def test_websocket_send_json(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        data = await ws.receive_json()\n        await ws.send_json(data)\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    expected_value = \"value\"\n    await ws.send_json({\"test\": expected_value})\n\n    data = await ws.receive_json()\n    assert data[\"test\"] == expected_value\n\n\nasync def test_websocket_receive_json(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        data = await ws.receive_json()\n        answer = data[\"test\"]\n        await ws.send_str(answer)\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    expected_value = \"value\"\n    payload = '{\"test\": \"%s\"}' % expected_value\n    await ws.send_str(payload)\n\n    resp = await ws.receive()\n    assert resp.data == expected_value\n\n\nasync def test_send_recv_text(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        msg = await ws.receive_str()\n        await ws.send_str(msg + \"/answer\")\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_str(\"ask\")\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.TEXT\n    assert \"ask/answer\" == msg.data\n\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.CLOSE\n    assert msg.data == WSCloseCode.OK\n    assert msg.extra == \"\"\n\n    assert ws.closed\n    assert ws.close_code == WSCloseCode.OK\n\n    await closed\n\n\nasync def test_send_recv_bytes(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        msg = await ws.receive_bytes()\n        await ws.send_bytes(msg + b\"/answer\")\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_bytes(b\"ask\")\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.BINARY\n    assert b\"ask/answer\" == msg.data\n\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.CLOSE\n    assert msg.data == WSCloseCode.OK\n    assert msg.extra == \"\"\n\n    assert ws.closed\n    assert ws.close_code == WSCloseCode.OK\n\n    await closed\n\n\nasync def test_send_recv_json(loop, aiohttp_client) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        data = await ws.receive_json()\n        await ws.send_json({\"response\": data[\"request\"]})\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n\n    await ws.send_str('{\"request\": \"test\"}')\n    msg = await ws.receive()\n    data = msg.json()\n    assert msg.type == aiohttp.WSMsgType.TEXT\n    assert data[\"response\"] == \"test\"\n\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.CLOSE\n    assert msg.data == WSCloseCode.OK\n    assert msg.extra == \"\"\n\n    await ws.close()\n\n    await closed\n\n\nasync def test_close_timeout(loop, aiohttp_client) -> None:\n    aborted = loop.create_future()\n    elapsed = 1e10  # something big\n\n    async def handler(request):\n        nonlocal elapsed\n        ws = web.WebSocketResponse(timeout=0.1)\n        await ws.prepare(request)\n        assert \"request\" == (await ws.receive_str())\n        await ws.send_str(\"reply\")\n        begin = ws._loop.time()\n        assert await ws.close()\n        elapsed = ws._loop.time() - begin\n        assert ws.close_code == WSCloseCode.ABNORMAL_CLOSURE\n        assert isinstance(ws.exception(), asyncio.TimeoutError)\n        aborted.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_str(\"request\")\n    assert \"reply\" == (await ws.receive_str())\n\n    # The server closes here.  Then the client sends bogus messages with an\n    # interval shorter than server-side close timeout, to make the server\n    # hanging indefinitely.\n    await asyncio.sleep(0.08)\n    msg = await ws._reader.read()\n    assert msg.type == WSMsgType.CLOSE\n\n    await asyncio.sleep(0.08)\n    assert await aborted\n\n    assert elapsed < 0.25, \"close() should have returned before at most 2x timeout.\"\n\n    await ws.close()\n\n\nasync def test_concurrent_close(loop, aiohttp_client) -> None:\n\n    srv_ws = None\n\n    async def handler(request):\n        nonlocal srv_ws\n        ws = srv_ws = web.WebSocketResponse(autoclose=False, protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        await asyncio.sleep(0)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSED\n\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    await srv_ws.close(code=WSCloseCode.INVALID_TEXT)\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await asyncio.sleep(0)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n\n\nasync def test_concurrent_close_multiple_tasks(loop: Any, aiohttp_client: Any) -> None:\n    srv_ws = None\n\n    async def handler(request):\n        nonlocal srv_ws\n        ws = srv_ws = web.WebSocketResponse(autoclose=False, protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        await asyncio.sleep(0)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSED\n\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    task1 = asyncio.create_task(srv_ws.close(code=WSCloseCode.INVALID_TEXT))\n    task2 = asyncio.create_task(srv_ws.close(code=WSCloseCode.INVALID_TEXT))\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await task1\n    await task2\n\n    await asyncio.sleep(0)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n\n\nasync def test_close_op_code_from_client(loop: Any, aiohttp_client: Any) -> None:\n    srv_ws: Optional[web.WebSocketResponse] = None\n\n    async def handler(request):\n        nonlocal srv_ws\n        ws = srv_ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        await asyncio.sleep(0)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws: web.WebSocketResponse = await client.ws_connect(\"/\", protocols=(\"eggs\", \"bar\"))\n\n    await ws._writer.send_frame(b\"\", WSMsgType.CLOSE)\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await asyncio.sleep(0)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n\n\nasync def test_auto_pong_with_closing_by_peer(loop: Any, aiohttp_client: Any) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        await ws.receive()\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, autoping=False)\n    await ws.ping()\n    await ws.send_str(\"ask\")\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n    await closed\n\n\nasync def test_ping(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        await ws.ping(b\"data\")\n        await ws.receive()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PING\n    assert msg.data == b\"data\"\n    await ws.pong()\n    await ws.close()\n    await closed\n\n\nasync def aiohttp_client_ping(loop, aiohttp_client):\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        await ws.receive()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await ws.ping(b\"data\")\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n    await ws.pong()\n    await ws.close()\n\n\nasync def test_pong(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoping=False)\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.PING\n        await ws.pong(b\"data\")\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await ws.ping(b\"data\")\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n\n    await closed\n\n\nasync def test_change_status(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        ws.set_status(200)\n        assert 200 == ws.status\n        await ws.prepare(request)\n        assert 101 == ws.status\n        await ws.close()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await ws.close()\n    await closed\n    await ws.close()\n\n\nasync def test_handle_protocol(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n        await ws.close()\n        assert \"bar\" == ws.ws_protocol\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", protocols=(\"eggs\", \"bar\"))\n\n    await ws.close()\n    await closed\n\n\nasync def test_server_close_handshake(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n        await ws.close()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n    await ws.close()\n    await closed\n\n\nasync def aiohttp_client_close_handshake(loop, aiohttp_client):\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoclose=False, protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert not ws.closed\n        await ws.close()\n        assert ws.closed\n        assert ws.close_code == WSCloseCode.INVALID_TEXT\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSED\n\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    await ws.close(code=WSCloseCode.INVALID_TEXT)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n    await closed\n\n\nasync def test_server_close_handshake_server_eats_client_messages(loop, aiohttp_client):\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n        await ws.close()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\n        \"/\", autoclose=False, autoping=False, protocols=(\"eggs\", \"bar\")\n    )\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await ws.send_str(\"text\")\n    await ws.send_bytes(b\"bytes\")\n    await ws.ping()\n\n    await ws.close()\n    await closed\n\n\nasync def test_receive_timeout(loop, aiohttp_client) -> None:\n    raised = False\n\n    async def handler(request):\n        ws = web.WebSocketResponse(receive_timeout=0.1)\n        await ws.prepare(request)\n\n        try:\n            await ws.receive()\n        except asyncio.TimeoutError:\n            nonlocal raised\n            raised = True\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.receive()\n    await ws.close()\n    assert raised\n\n\nasync def test_custom_receive_timeout(loop, aiohttp_client) -> None:\n    raised = False\n\n    async def handler(request):\n        ws = web.WebSocketResponse(receive_timeout=None)\n        await ws.prepare(request)\n\n        try:\n            await ws.receive(0.1)\n        except asyncio.TimeoutError:\n            nonlocal raised\n            raised = True\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.receive()\n    await ws.close()\n    assert raised\n\n\nasync def test_heartbeat(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n        await ws.receive()\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n\n    assert msg.type == aiohttp.WSMsgType.ping\n\n    await ws.close()\n\n\nasync def test_heartbeat_no_pong(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n\n        await ws.receive()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.ping\n    await ws.close()\n\n\nasync def test_heartbeat_connection_closed(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    \"\"\"Test that the connection is closed while ping is in progress.\"\"\"\n    ping_count = 0\n\n    async def handler(request: web.Request) -> NoReturn:\n        nonlocal ping_count\n        ws_server = web.WebSocketResponse(heartbeat=0.05)\n        await ws_server.prepare(request)\n        # We patch write here to simulate a connection reset error\n        # since if we closed the connection normally, the server would\n        # would cancel the heartbeat task and we wouldn't get a ping\n        with mock.patch.object(\n            ws_server._req.transport, \"write\", side_effect=ConnectionResetError\n        ), mock.patch.object(\n            ws_server._writer, \"send_frame\", wraps=ws_server._writer.send_frame\n        ) as send_frame:\n            try:\n                await ws_server.receive()\n            finally:\n                ping_count = send_frame.call_args_list.count(\n                    mock.call(b\"\", WSMsgType.PING)\n                )\n        assert False\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSED\n    assert msg.extra is None\n    assert ws.close_code == WSCloseCode.ABNORMAL_CLOSURE\n    assert ping_count == 1\n    await ws.close()\n\n\nasync def test_heartbeat_failure_ends_receive(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    \"\"\"Test that no heartbeat response to the server ends the receive call.\"\"\"\n    ws_server_close_code = None\n    ws_server_exception = None\n\n    async def handler(request: web.Request) -> NoReturn:\n        nonlocal ws_server_close_code, ws_server_exception\n        ws_server = web.WebSocketResponse(heartbeat=0.05)\n        await ws_server.prepare(request)\n        try:\n            await ws_server.receive()\n        finally:\n            ws_server_close_code = ws_server.close_code\n            ws_server_exception = ws_server.exception()\n        assert False\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.PING\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSED\n    assert ws.close_code == WSCloseCode.ABNORMAL_CLOSURE\n    assert ws_server_close_code == WSCloseCode.ABNORMAL_CLOSURE\n    assert isinstance(ws_server_exception, asyncio.TimeoutError)\n    await ws.close()\n\n\nasync def test_heartbeat_no_pong_send_many_messages(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    \"\"\"Test no pong after sending many messages.\"\"\"\n\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n        for _ in range(10):\n            await ws.send_str(\"test\")\n\n        await ws.receive()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    for _ in range(10):\n        msg = await ws.receive()\n        assert msg.type is aiohttp.WSMsgType.TEXT\n        assert msg.data == \"test\"\n\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.PING\n    await ws.close()\n\n\nasync def test_heartbeat_no_pong_receive_many_messages(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    \"\"\"Test no pong after receiving many messages.\"\"\"\n\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n        for _ in range(10):\n            server_msg = await ws.receive()\n            assert server_msg.type is aiohttp.WSMsgType.TEXT\n\n        await ws.receive()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    for _ in range(10):\n        await ws.send_str(\"test\")\n\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.PING\n    await ws.close()\n\n\nasync def test_server_ws_async_for(loop: Any, aiohttp_server: Any) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        async for msg in ws:\n            assert msg.type == aiohttp.WSMsgType.TEXT\n            s = msg.data\n            await ws.send_str(s + \"/answer\")\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    server = await aiohttp_server(app)\n\n    async with aiohttp.ClientSession() as sm:\n        async with sm.ws_connect(server.make_url(\"/\")) as resp:\n\n            items = [\"q1\", \"q2\", \"q3\"]\n            for item in items:\n                await resp.send_str(item)\n                msg = await resp.receive()\n                assert msg.type == aiohttp.WSMsgType.TEXT\n                assert item + \"/answer\" == msg.data\n\n            await resp.close()\n            await closed\n\n\nasync def test_closed_async_for(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        messages = []\n        async for msg in ws:\n            messages.append(msg)\n            if \"stop\" == msg.data:\n                await ws.send_str(\"stopping\")\n                await ws.close()\n\n        assert 1 == len(messages)\n        assert messages[0].type == WSMsgType.TEXT\n        assert messages[0].data == \"stop\"\n\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_str(\"stop\")\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.TEXT\n    assert msg.data == \"stopping\"\n\n    await ws.close()\n    await closed\n\n\nasync def test_websocket_disable_keepalive(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        if not ws.can_prepare(request):\n            return web.Response(text=\"OK\")\n        assert request.protocol._keepalive\n        await ws.prepare(request)\n        assert not request.protocol._keepalive\n        assert not request.protocol._keepalive_handle\n\n        await ws.send_str(\"OK\")\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    resp = await client.get(\"/\")\n    txt = await resp.text()\n    assert txt == \"OK\"\n\n    ws = await client.ws_connect(\"/\")\n    data = await ws.receive_str()\n    assert data == \"OK\"\n\n\nasync def test_receive_str_nonstring(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        ws = web.WebSocketResponse()\n        assert ws.can_prepare(request)\n\n        await ws.prepare(request)\n        await ws.send_bytes(b\"answer\")\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    with pytest.raises(TypeError):\n        await ws.receive_str()\n\n\nasync def test_receive_bytes_nonbytes(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    async def handler(request: web.Request) -> NoReturn:\n        ws = web.WebSocketResponse()\n        assert ws.can_prepare(request)\n\n        await ws.prepare(request)\n        await ws.send_str(\"answer\")\n        assert False\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    with pytest.raises(TypeError):\n        await ws.receive_bytes()\n\n\nasync def test_bug3380(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    async def handle_null(request):\n        return aiohttp.web.json_response({\"err\": None})\n\n    async def ws_handler(request: web.Request) -> web.Response:\n        return web.Response(status=401)\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/ws\", ws_handler)\n    app.router.add_route(\"GET\", \"/api/null\", handle_null)\n\n    client = await aiohttp_client(app)\n\n    resp = await client.get(\"/api/null\")\n    assert (await resp.json()) == {\"err\": None}\n    resp.close()\n\n    with pytest.raises(aiohttp.WSServerHandshakeError):\n        await client.ws_connect(\"/ws\")\n\n    resp = await client.get(\"/api/null\", timeout=1)\n    assert (await resp.json()) == {\"err\": None}\n    resp.close()\n\n\nasync def test_receive_being_cancelled_keeps_connection_open(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoping=False)\n        await ws.prepare(request)\n\n        task = asyncio.create_task(ws.receive())\n        await asyncio.sleep(0)\n        task.cancel()\n        with contextlib.suppress(asyncio.CancelledError):\n            await task\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.PING\n        await asyncio.sleep(0)\n        await ws.pong(b\"data\")\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await asyncio.sleep(0)\n    await ws.ping(b\"data\")\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n\n    await closed\n\n\nasync def test_receive_timeout_keeps_connection_open(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    closed = loop.create_future()\n    timed_out = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoping=False)\n        await ws.prepare(request)\n\n        task = asyncio.create_task(ws.receive(sys.float_info.min))\n        with contextlib.suppress(asyncio.TimeoutError):\n            await task\n\n        timed_out.set_result(None)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.PING\n        await asyncio.sleep(0)\n        await ws.pong(b\"data\")\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await timed_out\n    await ws.ping(b\"data\")\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n\n    await closed\n\n\nasync def test_websocket_shutdown(aiohttp_client: AiohttpClient) -> None:\n    \"\"\"Test that the client websocket gets the close message when the server is shutting down.\"\"\"\n    url = \"/ws\"\n    app = web.Application()\n    websockets = web.AppKey(\"websockets\", weakref.WeakSet)\n    app[websockets] = weakref.WeakSet()\n\n    # need for send signal shutdown server\n    shutdown_websockets = web.AppKey(\"shutdown_websockets\", weakref.WeakSet)\n    app[shutdown_websockets] = weakref.WeakSet()\n\n    async def websocket_handler(request: web.Request) -> web.WebSocketResponse:\n        websocket = web.WebSocketResponse()\n        await websocket.prepare(request)\n        request.app[websockets].add(websocket)\n        request.app[shutdown_websockets].add(websocket)\n\n        try:\n            async for message in websocket:\n                await websocket.send_json({\"ok\": True, \"message\": message.json()})\n        finally:\n            request.app[websockets].discard(websocket)\n\n        return websocket\n\n    async def on_shutdown(app: web.Application) -> None:\n        while app[shutdown_websockets]:\n            websocket = app[shutdown_websockets].pop()\n            await websocket.close(\n                code=aiohttp.WSCloseCode.GOING_AWAY,\n                message=\"Server shutdown\",\n            )\n\n    app.router.add_get(url, websocket_handler)\n    app.on_shutdown.append(on_shutdown)\n\n    client = await aiohttp_client(app)\n\n    websocket = await client.ws_connect(url)\n\n    message = {\"message\": \"hi\"}\n    await websocket.send_json(message)\n    reply = await websocket.receive_json()\n    assert reply == {\"ok\": True, \"message\": message}\n\n    await app.shutdown()\n\n    assert websocket.closed is False\n\n    reply = await websocket.receive()\n\n    assert reply.type is aiohttp.http.WSMsgType.CLOSE\n    assert reply.data == aiohttp.WSCloseCode.GOING_AWAY\n    assert reply.extra == \"Server shutdown\"\n\n    assert websocket.closed is True\n\n\nasync def test_ws_close_return_code(aiohttp_client: AiohttpClient) -> None:\n    \"\"\"Test that the close code is returned when the server closes the connection.\"\"\"\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        await ws.receive()\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    resp = await client.ws_connect(\"/\")\n    await resp.send_str(\"some data\")\n    msg = await resp.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSE\n    assert resp.close_code == WSCloseCode.OK\n\n\nasync def test_abnormal_closure_when_server_does_not_receive(\n    aiohttp_client: AiohttpClient,\n) -> None:\n    \"\"\"Test abnormal closure when the server closes and a message is pending.\"\"\"\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        # Setting close timeout to 0, otherwise the server waits for a\n        # close response for 10 seconds by default.\n        # This would make the client's autoclose in resp.receive() to succeed,\n        # closing the connection cleanly from both sides.\n        ws = web.WebSocketResponse(timeout=0)\n        await ws.prepare(request)\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    resp = await client.ws_connect(\"/\")\n    await resp.send_str(\"some data\")\n    await asyncio.sleep(0.1)\n    msg = await resp.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSE\n    assert resp.close_code == WSCloseCode.ABNORMAL_CLOSURE\n\n\nasync def test_abnormal_closure_when_client_does_not_close(\n    aiohttp_client: AiohttpClient,\n) -> None:\n    \"\"\"Test abnormal closure when the server closes and the client doesn't respond.\"\"\"\n    close_code: Optional[WSCloseCode] = None\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        # Setting a short close timeout\n        ws = web.WebSocketResponse(timeout=0.1)\n        await ws.prepare(request)\n        await ws.close()\n\n        nonlocal close_code\n        assert ws.close_code is not None\n        close_code = WSCloseCode(ws.close_code)\n\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    async with client.ws_connect(\"/\", autoclose=False):\n        await asyncio.sleep(0.2)\n    await client.server.close()\n    assert close_code == WSCloseCode.ABNORMAL_CLOSURE\n\n\nasync def test_normal_closure_while_client_sends_msg(\n    aiohttp_client: AiohttpClient,\n) -> None:\n    \"\"\"Test abnormal closure when the server closes and the client doesn't respond.\"\"\"\n    close_code: Optional[WSCloseCode] = None\n    got_close_code = asyncio.Event()\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        # Setting a short close timeout\n        ws = web.WebSocketResponse(timeout=0.2)\n        await ws.prepare(request)\n        await ws.close()\n\n        nonlocal close_code\n        assert ws.close_code is not None\n        close_code = WSCloseCode(ws.close_code)\n        got_close_code.set()\n\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    async with client.ws_connect(\"/\", autoclose=False) as ws:\n        # send text and close message during server close timeout\n        await asyncio.sleep(0.1)\n        await ws.send_str(\"Hello\")\n        await ws.close()\n    # wait for close code to be received by server\n    await asyncio.wait(\n        [\n            asyncio.create_task(asyncio.sleep(0.5)),\n            asyncio.create_task(got_close_code.wait()),\n        ],\n        return_when=asyncio.FIRST_COMPLETED,\n    )\n    await client.server.close()\n    assert close_code == WSCloseCode.OK\n",
            "header": {
                "file": {
                    "path": "tests/test_web_websocket_functional.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "188694c8",
                "new_commit_hash": "ebd94607",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tests/test_web_websocket_functional.py"
            },
            "plus_file": {
                "path": "b/tests/test_web_websocket_functional.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1192,
                            "length": 7
                        },
                        "new_range": {
                            "start": 1192,
                            "length": 11
                        },
                        "section": "async def test_abnormal_closure_when_server_does_not_receive("
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    \"\"\"Test abnormal closure when the server closes and a message is pending.\"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    async def handler(request: web.Request) -> web.WebSocketResponse:",
                                "type": "context"
                            },
                            {
                                "content": "        ws = web.WebSocketResponse()",
                                "type": "deleted"
                            },
                            {
                                "content": "        # Setting close timeout to 0, otherwise the server waits for a",
                                "type": "added"
                            },
                            {
                                "content": "        # close response for 10 seconds by default.",
                                "type": "added"
                            },
                            {
                                "content": "        # This would make the client's autoclose in resp.receive() to succeed,",
                                "type": "added"
                            },
                            {
                                "content": "        # closing the connection cleanly from both sides.",
                                "type": "added"
                            },
                            {
                                "content": "        ws = web.WebSocketResponse(timeout=0)",
                                "type": "added"
                            },
                            {
                                "content": "        await ws.prepare(request)",
                                "type": "context"
                            },
                            {
                                "content": "        await ws.close()",
                                "type": "context"
                            },
                            {
                                "content": "        return ws",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_web_websocket_functional.py",
                            "type": "function",
                            "name": "test_abnormal_closure_when_server_does_not_receive",
                            "content": "async def test_abnormal_closure_when_server_does_not_receive(\n    aiohttp_client: AiohttpClient,\n) -> None:\n    \"\"\"Test abnormal closure when the server closes and a message is pending.\"\"\"\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    resp = await client.ws_connect(\"/\")\n    await resp.send_str(\"some data\")\n    await asyncio.sleep(0.1)\n    msg = await resp.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSE\n    assert resp.close_code == WSCloseCode.ABNORMAL_CLOSURE",
                            "ast_type_str": "AsyncFunctionDef",
                            "start_lineno": 1189,
                            "end_lineno": 1208,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1206,
                            "length": 3
                        },
                        "new_range": {
                            "start": 1210,
                            "length": 70
                        },
                        "section": "async def test_abnormal_closure_when_server_does_not_receive("
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    msg = await resp.receive()",
                                "type": "context"
                            },
                            {
                                "content": "    assert msg.type is aiohttp.WSMsgType.CLOSE",
                                "type": "context"
                            },
                            {
                                "content": "    assert resp.close_code == WSCloseCode.ABNORMAL_CLOSURE",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "async def test_abnormal_closure_when_client_does_not_close(",
                                "type": "added"
                            },
                            {
                                "content": "    aiohttp_client: AiohttpClient,",
                                "type": "added"
                            },
                            {
                                "content": ") -> None:",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"Test abnormal closure when the server closes and the client doesn't respond.\"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "    close_code: Optional[WSCloseCode] = None",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    async def handler(request: web.Request) -> web.WebSocketResponse:",
                                "type": "added"
                            },
                            {
                                "content": "        # Setting a short close timeout",
                                "type": "added"
                            },
                            {
                                "content": "        ws = web.WebSocketResponse(timeout=0.1)",
                                "type": "added"
                            },
                            {
                                "content": "        await ws.prepare(request)",
                                "type": "added"
                            },
                            {
                                "content": "        await ws.close()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        nonlocal close_code",
                                "type": "added"
                            },
                            {
                                "content": "        assert ws.close_code is not None",
                                "type": "added"
                            },
                            {
                                "content": "        close_code = WSCloseCode(ws.close_code)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        return ws",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    app = web.Application()",
                                "type": "added"
                            },
                            {
                                "content": "    app.router.add_route(\"GET\", \"/\", handler)",
                                "type": "added"
                            },
                            {
                                "content": "    client = await aiohttp_client(app)",
                                "type": "added"
                            },
                            {
                                "content": "    async with client.ws_connect(\"/\", autoclose=False):",
                                "type": "added"
                            },
                            {
                                "content": "        await asyncio.sleep(0.2)",
                                "type": "added"
                            },
                            {
                                "content": "    await client.server.close()",
                                "type": "added"
                            },
                            {
                                "content": "    assert close_code == WSCloseCode.ABNORMAL_CLOSURE",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "async def test_normal_closure_while_client_sends_msg(",
                                "type": "added"
                            },
                            {
                                "content": "    aiohttp_client: AiohttpClient,",
                                "type": "added"
                            },
                            {
                                "content": ") -> None:",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"Test abnormal closure when the server closes and the client doesn't respond.\"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "    close_code: Optional[WSCloseCode] = None",
                                "type": "added"
                            },
                            {
                                "content": "    got_close_code = asyncio.Event()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    async def handler(request: web.Request) -> web.WebSocketResponse:",
                                "type": "added"
                            },
                            {
                                "content": "        # Setting a short close timeout",
                                "type": "added"
                            },
                            {
                                "content": "        ws = web.WebSocketResponse(timeout=0.2)",
                                "type": "added"
                            },
                            {
                                "content": "        await ws.prepare(request)",
                                "type": "added"
                            },
                            {
                                "content": "        await ws.close()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        nonlocal close_code",
                                "type": "added"
                            },
                            {
                                "content": "        assert ws.close_code is not None",
                                "type": "added"
                            },
                            {
                                "content": "        close_code = WSCloseCode(ws.close_code)",
                                "type": "added"
                            },
                            {
                                "content": "        got_close_code.set()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        return ws",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    app = web.Application()",
                                "type": "added"
                            },
                            {
                                "content": "    app.router.add_route(\"GET\", \"/\", handler)",
                                "type": "added"
                            },
                            {
                                "content": "    client = await aiohttp_client(app)",
                                "type": "added"
                            },
                            {
                                "content": "    async with client.ws_connect(\"/\", autoclose=False) as ws:",
                                "type": "added"
                            },
                            {
                                "content": "        # send text and close message during server close timeout",
                                "type": "added"
                            },
                            {
                                "content": "        await asyncio.sleep(0.1)",
                                "type": "added"
                            },
                            {
                                "content": "        await ws.send_str(\"Hello\")",
                                "type": "added"
                            },
                            {
                                "content": "        await ws.close()",
                                "type": "added"
                            },
                            {
                                "content": "    # wait for close code to be received by server",
                                "type": "added"
                            },
                            {
                                "content": "    await asyncio.wait(",
                                "type": "added"
                            },
                            {
                                "content": "        [",
                                "type": "added"
                            },
                            {
                                "content": "            asyncio.create_task(asyncio.sleep(0.5)),",
                                "type": "added"
                            },
                            {
                                "content": "            asyncio.create_task(got_close_code.wait()),",
                                "type": "added"
                            },
                            {
                                "content": "        ],",
                                "type": "added"
                            },
                            {
                                "content": "        return_when=asyncio.FIRST_COMPLETED,",
                                "type": "added"
                            },
                            {
                                "content": "    )",
                                "type": "added"
                            },
                            {
                                "content": "    await client.server.close()",
                                "type": "added"
                            },
                            {
                                "content": "    assert close_code == WSCloseCode.OK",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tests/test_web_websocket_functional.py",
                            "type": "function",
                            "name": "test_abnormal_closure_when_client_does_not_close",
                            "content": "async def test_abnormal_closure_when_client_does_not_close(\n    aiohttp_client: AiohttpClient,\n) -> None:\n    \"\"\"Test abnormal closure when the server closes and the client doesn't respond.\"\"\"\n    close_code: Optional[WSCloseCode] = None\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        # Setting a short close timeout\n        ws = web.WebSocketResponse(timeout=0.1)\n        await ws.prepare(request)\n        await ws.close()\n\n        nonlocal close_code\n        assert ws.close_code is not None\n        close_code = WSCloseCode(ws.close_code)\n\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    async with client.ws_connect(\"/\", autoclose=False):\n        await asyncio.sleep(0.2)\n    await client.server.close()\n    assert close_code == WSCloseCode.ABNORMAL_CLOSURE",
                            "ast_type_str": "AsyncFunctionDef",
                            "start_lineno": 1215,
                            "end_lineno": 1239,
                            "parent": null
                        },
                        {
                            "file_name": "tests/test_web_websocket_functional.py",
                            "type": "function",
                            "name": "test_normal_closure_while_client_sends_msg",
                            "content": "async def test_normal_closure_while_client_sends_msg(\n    aiohttp_client: AiohttpClient,\n) -> None:\n    \"\"\"Test abnormal closure when the server closes and the client doesn't respond.\"\"\"\n    close_code: Optional[WSCloseCode] = None\n    got_close_code = asyncio.Event()\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        # Setting a short close timeout\n        ws = web.WebSocketResponse(timeout=0.2)\n        await ws.prepare(request)\n        await ws.close()\n\n        nonlocal close_code\n        assert ws.close_code is not None\n        close_code = WSCloseCode(ws.close_code)\n        got_close_code.set()\n\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    async with client.ws_connect(\"/\", autoclose=False) as ws:\n        # send text and close message during server close timeout\n        await asyncio.sleep(0.1)\n        await ws.send_str(\"Hello\")\n        await ws.close()\n    # wait for close code to be received by server\n    await asyncio.wait(\n        [\n            asyncio.create_task(asyncio.sleep(0.5)),\n            asyncio.create_task(got_close_code.wait()),\n        ],\n        return_when=asyncio.FIRST_COMPLETED,\n    )\n    await client.server.close()\n    assert close_code == WSCloseCode.OK",
                            "ast_type_str": "AsyncFunctionDef",
                            "start_lineno": 1242,
                            "end_lineno": 1279,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "74d9355b6cf9581361668ffd2d38a01b53b58297^",
    "new_commit_hash": "74d9355b6cf9581361668ffd2d38a01b53b58297",
    "commit_message": "[PR #9508/274c54e backport][3.11] Discard non-close messages in close timeout window (#9688)\n\nCo-authored-by: pre-commit-ci[bot]\r\nCo-authored-by: J. Nick Koston <nick@koston.org>\r\nCo-authored-by: lenard-mosys <lenard@mo-sys.com>",
    "commit_date": "2024-11-06T14:55:17-06:00",
    "metadata": {}
}
{
    "repo_name": "aiohttp",
    "new_commit_hash": "74d9355b6cf9581361668ffd2d38a01b53b58297",
    "test_file_codes": [
        "# HTTP websocket server functional tests\n\nimport asyncio\nimport contextlib\nimport sys\nimport weakref\nfrom typing import Any, NoReturn, Optional\nfrom unittest import mock\n\nimport pytest\n\nimport aiohttp\nfrom aiohttp import web\nfrom aiohttp.http import WSCloseCode, WSMsgType\nfrom aiohttp.pytest_plugin import AiohttpClient\n\n\nasync def test_websocket_can_prepare(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        if not ws.can_prepare(request):\n            raise web.HTTPUpgradeRequired()\n\n        return web.Response()\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    resp = await client.get(\"/\")\n    assert resp.status == 426\n\n\nasync def test_websocket_json(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        if not ws.can_prepare(request):\n            return web.HTTPUpgradeRequired()\n\n        await ws.prepare(request)\n        msg = await ws.receive()\n\n        msg_json = msg.json()\n        answer = msg_json[\"test\"]\n        await ws.send_str(answer)\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    expected_value = \"value\"\n    payload = '{\"test\": \"%s\"}' % expected_value\n    await ws.send_str(payload)\n\n    resp = await ws.receive()\n    assert resp.data == expected_value\n\n\nasync def test_websocket_json_invalid_message(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        try:\n            await ws.receive_json()\n        except ValueError:\n            await ws.send_str(\"ValueError was raised\")\n        else:\n            raise Exception(\"No Exception\")\n        finally:\n            await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    payload = \"NOT A VALID JSON STRING\"\n    await ws.send_str(payload)\n\n    data = await ws.receive_str()\n    assert \"ValueError was raised\" in data\n\n\nasync def test_websocket_send_json(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        data = await ws.receive_json()\n        await ws.send_json(data)\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    expected_value = \"value\"\n    await ws.send_json({\"test\": expected_value})\n\n    data = await ws.receive_json()\n    assert data[\"test\"] == expected_value\n\n\nasync def test_websocket_receive_json(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        data = await ws.receive_json()\n        answer = data[\"test\"]\n        await ws.send_str(answer)\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    expected_value = \"value\"\n    payload = '{\"test\": \"%s\"}' % expected_value\n    await ws.send_str(payload)\n\n    resp = await ws.receive()\n    assert resp.data == expected_value\n\n\nasync def test_send_recv_text(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        msg = await ws.receive_str()\n        await ws.send_str(msg + \"/answer\")\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_str(\"ask\")\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.TEXT\n    assert \"ask/answer\" == msg.data\n\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.CLOSE\n    assert msg.data == WSCloseCode.OK\n    assert msg.extra == \"\"\n\n    assert ws.closed\n    assert ws.close_code == WSCloseCode.OK\n\n    await closed\n\n\nasync def test_send_recv_bytes(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        msg = await ws.receive_bytes()\n        await ws.send_bytes(msg + b\"/answer\")\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_bytes(b\"ask\")\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.BINARY\n    assert b\"ask/answer\" == msg.data\n\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.CLOSE\n    assert msg.data == WSCloseCode.OK\n    assert msg.extra == \"\"\n\n    assert ws.closed\n    assert ws.close_code == WSCloseCode.OK\n\n    await closed\n\n\nasync def test_send_recv_json(loop, aiohttp_client) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        data = await ws.receive_json()\n        await ws.send_json({\"response\": data[\"request\"]})\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n\n    await ws.send_str('{\"request\": \"test\"}')\n    msg = await ws.receive()\n    data = msg.json()\n    assert msg.type == aiohttp.WSMsgType.TEXT\n    assert data[\"response\"] == \"test\"\n\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.CLOSE\n    assert msg.data == WSCloseCode.OK\n    assert msg.extra == \"\"\n\n    await ws.close()\n\n    await closed\n\n\nasync def test_close_timeout(loop, aiohttp_client) -> None:\n    aborted = loop.create_future()\n    elapsed = 1e10  # something big\n\n    async def handler(request):\n        nonlocal elapsed\n        ws = web.WebSocketResponse(timeout=0.1)\n        await ws.prepare(request)\n        assert \"request\" == (await ws.receive_str())\n        await ws.send_str(\"reply\")\n        begin = ws._loop.time()\n        assert await ws.close()\n        elapsed = ws._loop.time() - begin\n        assert ws.close_code == WSCloseCode.ABNORMAL_CLOSURE\n        assert isinstance(ws.exception(), asyncio.TimeoutError)\n        aborted.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_str(\"request\")\n    assert \"reply\" == (await ws.receive_str())\n\n    # The server closes here.  Then the client sends bogus messages with an\n    # interval shorter than server-side close timeout, to make the server\n    # hanging indefinitely.\n    await asyncio.sleep(0.08)\n    msg = await ws._reader.read()\n    assert msg.type == WSMsgType.CLOSE\n\n    await asyncio.sleep(0.08)\n    assert await aborted\n\n    assert elapsed < 0.25, \"close() should have returned before at most 2x timeout.\"\n\n    await ws.close()\n\n\nasync def test_concurrent_close(loop, aiohttp_client) -> None:\n\n    srv_ws = None\n\n    async def handler(request):\n        nonlocal srv_ws\n        ws = srv_ws = web.WebSocketResponse(autoclose=False, protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        await asyncio.sleep(0)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSED\n\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    await srv_ws.close(code=WSCloseCode.INVALID_TEXT)\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await asyncio.sleep(0)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n\n\nasync def test_concurrent_close_multiple_tasks(loop: Any, aiohttp_client: Any) -> None:\n    srv_ws = None\n\n    async def handler(request):\n        nonlocal srv_ws\n        ws = srv_ws = web.WebSocketResponse(autoclose=False, protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSING\n\n        await asyncio.sleep(0)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSED\n\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    task1 = asyncio.create_task(srv_ws.close(code=WSCloseCode.INVALID_TEXT))\n    task2 = asyncio.create_task(srv_ws.close(code=WSCloseCode.INVALID_TEXT))\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await task1\n    await task2\n\n    await asyncio.sleep(0)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n\n\nasync def test_close_op_code_from_client(loop: Any, aiohttp_client: Any) -> None:\n    srv_ws: Optional[web.WebSocketResponse] = None\n\n    async def handler(request):\n        nonlocal srv_ws\n        ws = srv_ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        await asyncio.sleep(0)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws: web.WebSocketResponse = await client.ws_connect(\"/\", protocols=(\"eggs\", \"bar\"))\n\n    await ws._writer.send_frame(b\"\", WSMsgType.CLOSE)\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await asyncio.sleep(0)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n\n\nasync def test_auto_pong_with_closing_by_peer(loop: Any, aiohttp_client: Any) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        await ws.receive()\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, autoping=False)\n    await ws.ping()\n    await ws.send_str(\"ask\")\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n    await closed\n\n\nasync def test_ping(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        await ws.ping(b\"data\")\n        await ws.receive()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PING\n    assert msg.data == b\"data\"\n    await ws.pong()\n    await ws.close()\n    await closed\n\n\nasync def aiohttp_client_ping(loop, aiohttp_client):\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        await ws.receive()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await ws.ping(b\"data\")\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n    await ws.pong()\n    await ws.close()\n\n\nasync def test_pong(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoping=False)\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.PING\n        await ws.pong(b\"data\")\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await ws.ping(b\"data\")\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n\n    await closed\n\n\nasync def test_change_status(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        ws.set_status(200)\n        assert 200 == ws.status\n        await ws.prepare(request)\n        assert 101 == ws.status\n        await ws.close()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await ws.close()\n    await closed\n    await ws.close()\n\n\nasync def test_handle_protocol(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n        await ws.close()\n        assert \"bar\" == ws.ws_protocol\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", protocols=(\"eggs\", \"bar\"))\n\n    await ws.close()\n    await closed\n\n\nasync def test_server_close_handshake(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n        await ws.close()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n    await ws.close()\n    await closed\n\n\nasync def aiohttp_client_close_handshake(loop, aiohttp_client):\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoclose=False, protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert not ws.closed\n        await ws.close()\n        assert ws.closed\n        assert ws.close_code == WSCloseCode.INVALID_TEXT\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSED\n\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoclose=False, protocols=(\"eggs\", \"bar\"))\n\n    await ws.close(code=WSCloseCode.INVALID_TEXT)\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSED\n    await closed\n\n\nasync def test_server_close_handshake_server_eats_client_messages(loop, aiohttp_client):\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(protocols=(\"foo\", \"bar\"))\n        await ws.prepare(request)\n        await ws.close()\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\n        \"/\", autoclose=False, autoping=False, protocols=(\"eggs\", \"bar\")\n    )\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.CLOSE\n\n    await ws.send_str(\"text\")\n    await ws.send_bytes(b\"bytes\")\n    await ws.ping()\n\n    await ws.close()\n    await closed\n\n\nasync def test_receive_timeout(loop, aiohttp_client) -> None:\n    raised = False\n\n    async def handler(request):\n        ws = web.WebSocketResponse(receive_timeout=0.1)\n        await ws.prepare(request)\n\n        try:\n            await ws.receive()\n        except asyncio.TimeoutError:\n            nonlocal raised\n            raised = True\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.receive()\n    await ws.close()\n    assert raised\n\n\nasync def test_custom_receive_timeout(loop, aiohttp_client) -> None:\n    raised = False\n\n    async def handler(request):\n        ws = web.WebSocketResponse(receive_timeout=None)\n        await ws.prepare(request)\n\n        try:\n            await ws.receive(0.1)\n        except asyncio.TimeoutError:\n            nonlocal raised\n            raised = True\n\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.receive()\n    await ws.close()\n    assert raised\n\n\nasync def test_heartbeat(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n        await ws.receive()\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n\n    assert msg.type == aiohttp.WSMsgType.ping\n\n    await ws.close()\n\n\nasync def test_heartbeat_no_pong(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n\n        await ws.receive()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n    assert msg.type == aiohttp.WSMsgType.ping\n    await ws.close()\n\n\nasync def test_heartbeat_connection_closed(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    \"\"\"Test that the connection is closed while ping is in progress.\"\"\"\n    ping_count = 0\n\n    async def handler(request: web.Request) -> NoReturn:\n        nonlocal ping_count\n        ws_server = web.WebSocketResponse(heartbeat=0.05)\n        await ws_server.prepare(request)\n        # We patch write here to simulate a connection reset error\n        # since if we closed the connection normally, the server would\n        # would cancel the heartbeat task and we wouldn't get a ping\n        with mock.patch.object(\n            ws_server._req.transport, \"write\", side_effect=ConnectionResetError\n        ), mock.patch.object(\n            ws_server._writer, \"send_frame\", wraps=ws_server._writer.send_frame\n        ) as send_frame:\n            try:\n                await ws_server.receive()\n            finally:\n                ping_count = send_frame.call_args_list.count(\n                    mock.call(b\"\", WSMsgType.PING)\n                )\n        assert False\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSED\n    assert msg.extra is None\n    assert ws.close_code == WSCloseCode.ABNORMAL_CLOSURE\n    assert ping_count == 1\n    await ws.close()\n\n\nasync def test_heartbeat_failure_ends_receive(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    \"\"\"Test that no heartbeat response to the server ends the receive call.\"\"\"\n    ws_server_close_code = None\n    ws_server_exception = None\n\n    async def handler(request: web.Request) -> NoReturn:\n        nonlocal ws_server_close_code, ws_server_exception\n        ws_server = web.WebSocketResponse(heartbeat=0.05)\n        await ws_server.prepare(request)\n        try:\n            await ws_server.receive()\n        finally:\n            ws_server_close_code = ws_server.close_code\n            ws_server_exception = ws_server.exception()\n        assert False\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.PING\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSED\n    assert ws.close_code == WSCloseCode.ABNORMAL_CLOSURE\n    assert ws_server_close_code == WSCloseCode.ABNORMAL_CLOSURE\n    assert isinstance(ws_server_exception, asyncio.TimeoutError)\n    await ws.close()\n\n\nasync def test_heartbeat_no_pong_send_many_messages(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    \"\"\"Test no pong after sending many messages.\"\"\"\n\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n        for _ in range(10):\n            await ws.send_str(\"test\")\n\n        await ws.receive()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    for _ in range(10):\n        msg = await ws.receive()\n        assert msg.type is aiohttp.WSMsgType.TEXT\n        assert msg.data == \"test\"\n\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.PING\n    await ws.close()\n\n\nasync def test_heartbeat_no_pong_receive_many_messages(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    \"\"\"Test no pong after receiving many messages.\"\"\"\n\n    async def handler(request):\n        ws = web.WebSocketResponse(heartbeat=0.05)\n        await ws.prepare(request)\n        for _ in range(10):\n            server_msg = await ws.receive()\n            assert server_msg.type is aiohttp.WSMsgType.TEXT\n\n        await ws.receive()\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n\n    client = await aiohttp_client(app)\n    ws = await client.ws_connect(\"/\", autoping=False)\n    for _ in range(10):\n        await ws.send_str(\"test\")\n\n    msg = await ws.receive()\n    assert msg.type is aiohttp.WSMsgType.PING\n    await ws.close()\n\n\nasync def test_server_ws_async_for(loop: Any, aiohttp_server: Any) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        async for msg in ws:\n            assert msg.type == aiohttp.WSMsgType.TEXT\n            s = msg.data\n            await ws.send_str(s + \"/answer\")\n        await ws.close()\n        closed.set_result(1)\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    server = await aiohttp_server(app)\n\n    async with aiohttp.ClientSession() as sm:\n        async with sm.ws_connect(server.make_url(\"/\")) as resp:\n\n            items = [\"q1\", \"q2\", \"q3\"]\n            for item in items:\n                await resp.send_str(item)\n                msg = await resp.receive()\n                assert msg.type == aiohttp.WSMsgType.TEXT\n                assert item + \"/answer\" == msg.data\n\n            await resp.close()\n            await closed\n\n\nasync def test_closed_async_for(loop, aiohttp_client) -> None:\n\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n\n        messages = []\n        async for msg in ws:\n            messages.append(msg)\n            if \"stop\" == msg.data:\n                await ws.send_str(\"stopping\")\n                await ws.close()\n\n        assert 1 == len(messages)\n        assert messages[0].type == WSMsgType.TEXT\n        assert messages[0].data == \"stop\"\n\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    await ws.send_str(\"stop\")\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.TEXT\n    assert msg.data == \"stopping\"\n\n    await ws.close()\n    await closed\n\n\nasync def test_websocket_disable_keepalive(loop, aiohttp_client) -> None:\n    async def handler(request):\n        ws = web.WebSocketResponse()\n        if not ws.can_prepare(request):\n            return web.Response(text=\"OK\")\n        assert request.protocol._keepalive\n        await ws.prepare(request)\n        assert not request.protocol._keepalive\n        assert not request.protocol._keepalive_handle\n\n        await ws.send_str(\"OK\")\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    resp = await client.get(\"/\")\n    txt = await resp.text()\n    assert txt == \"OK\"\n\n    ws = await client.ws_connect(\"/\")\n    data = await ws.receive_str()\n    assert data == \"OK\"\n\n\nasync def test_receive_str_nonstring(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        ws = web.WebSocketResponse()\n        assert ws.can_prepare(request)\n\n        await ws.prepare(request)\n        await ws.send_bytes(b\"answer\")\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    with pytest.raises(TypeError):\n        await ws.receive_str()\n\n\nasync def test_receive_bytes_nonbytes(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    async def handler(request: web.Request) -> NoReturn:\n        ws = web.WebSocketResponse()\n        assert ws.can_prepare(request)\n\n        await ws.prepare(request)\n        await ws.send_str(\"answer\")\n        assert False\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\")\n    with pytest.raises(TypeError):\n        await ws.receive_bytes()\n\n\nasync def test_bug3380(\n    loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient\n) -> None:\n    async def handle_null(request):\n        return aiohttp.web.json_response({\"err\": None})\n\n    async def ws_handler(request: web.Request) -> web.Response:\n        return web.Response(status=401)\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/ws\", ws_handler)\n    app.router.add_route(\"GET\", \"/api/null\", handle_null)\n\n    client = await aiohttp_client(app)\n\n    resp = await client.get(\"/api/null\")\n    assert (await resp.json()) == {\"err\": None}\n    resp.close()\n\n    with pytest.raises(aiohttp.WSServerHandshakeError):\n        await client.ws_connect(\"/ws\")\n\n    resp = await client.get(\"/api/null\", timeout=1)\n    assert (await resp.json()) == {\"err\": None}\n    resp.close()\n\n\nasync def test_receive_being_cancelled_keeps_connection_open(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    closed = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoping=False)\n        await ws.prepare(request)\n\n        task = asyncio.create_task(ws.receive())\n        await asyncio.sleep(0)\n        task.cancel()\n        with contextlib.suppress(asyncio.CancelledError):\n            await task\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.PING\n        await asyncio.sleep(0)\n        await ws.pong(b\"data\")\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await asyncio.sleep(0)\n    await ws.ping(b\"data\")\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n\n    await closed\n\n\nasync def test_receive_timeout_keeps_connection_open(\n    loop: Any, aiohttp_client: Any\n) -> None:\n    closed = loop.create_future()\n    timed_out = loop.create_future()\n\n    async def handler(request):\n        ws = web.WebSocketResponse(autoping=False)\n        await ws.prepare(request)\n\n        task = asyncio.create_task(ws.receive(sys.float_info.min))\n        with contextlib.suppress(asyncio.TimeoutError):\n            await task\n\n        timed_out.set_result(None)\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.PING\n        await asyncio.sleep(0)\n        await ws.pong(b\"data\")\n\n        msg = await ws.receive()\n        assert msg.type == WSMsgType.CLOSE\n        assert msg.data == WSCloseCode.OK\n        assert msg.extra == \"exit message\"\n        closed.set_result(None)\n        return ws\n\n    app = web.Application()\n    app.router.add_get(\"/\", handler)\n    client = await aiohttp_client(app)\n\n    ws = await client.ws_connect(\"/\", autoping=False)\n\n    await timed_out\n    await ws.ping(b\"data\")\n\n    msg = await ws.receive()\n    assert msg.type == WSMsgType.PONG\n    assert msg.data == b\"data\"\n\n    await ws.close(code=WSCloseCode.OK, message=\"exit message\")\n\n    await closed\n\n\nasync def test_websocket_shutdown(aiohttp_client: AiohttpClient) -> None:\n    \"\"\"Test that the client websocket gets the close message when the server is shutting down.\"\"\"\n    url = \"/ws\"\n    app = web.Application()\n    websockets = web.AppKey(\"websockets\", weakref.WeakSet)\n    app[websockets] = weakref.WeakSet()\n\n    # need for send signal shutdown server\n    shutdown_websockets = web.AppKey(\"shutdown_websockets\", weakref.WeakSet)\n    app[shutdown_websockets] = weakref.WeakSet()\n\n    async def websocket_handler(request: web.Request) -> web.WebSocketResponse:\n        websocket = web.WebSocketResponse()\n        await websocket.prepare(request)\n        request.app[websockets].add(websocket)\n        request.app[shutdown_websockets].add(websocket)\n\n        try:\n            async for message in websocket:\n                await websocket.send_json({\"ok\": True, \"message\": message.json()})\n        finally:\n            request.app[websockets].discard(websocket)\n\n        return websocket\n\n    async def on_shutdown(app: web.Application) -> None:\n        while app[shutdown_websockets]:\n            websocket = app[shutdown_websockets].pop()\n            await websocket.close(\n                code=aiohttp.WSCloseCode.GOING_AWAY,\n                message=\"Server shutdown\",\n            )\n\n    app.router.add_get(url, websocket_handler)\n    app.on_shutdown.append(on_shutdown)\n\n    client = await aiohttp_client(app)\n\n    websocket = await client.ws_connect(url)\n\n    message = {\"message\": \"hi\"}\n    await websocket.send_json(message)\n    reply = await websocket.receive_json()\n    assert reply == {\"ok\": True, \"message\": message}\n\n    await app.shutdown()\n\n    assert websocket.closed is False\n\n    reply = await websocket.receive()\n\n    assert reply.type is aiohttp.http.WSMsgType.CLOSE\n    assert reply.data == aiohttp.WSCloseCode.GOING_AWAY\n    assert reply.extra == \"Server shutdown\"\n\n    assert websocket.closed is True\n\n\nasync def test_ws_close_return_code(aiohttp_client: AiohttpClient) -> None:\n    \"\"\"Test that the close code is returned when the server closes the connection.\"\"\"\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        ws = web.WebSocketResponse()\n        await ws.prepare(request)\n        await ws.receive()\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    resp = await client.ws_connect(\"/\")\n    await resp.send_str(\"some data\")\n    msg = await resp.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSE\n    assert resp.close_code == WSCloseCode.OK\n\n\nasync def test_abnormal_closure_when_server_does_not_receive(\n    aiohttp_client: AiohttpClient,\n) -> None:\n    \"\"\"Test abnormal closure when the server closes and a message is pending.\"\"\"\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        # Setting close timeout to 0, otherwise the server waits for a\n        # close response for 10 seconds by default.\n        # This would make the client's autoclose in resp.receive() to succeed,\n        # closing the connection cleanly from both sides.\n        ws = web.WebSocketResponse(timeout=0)\n        await ws.prepare(request)\n        await ws.close()\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    resp = await client.ws_connect(\"/\")\n    await resp.send_str(\"some data\")\n    await asyncio.sleep(0.1)\n    msg = await resp.receive()\n    assert msg.type is aiohttp.WSMsgType.CLOSE\n    assert resp.close_code == WSCloseCode.ABNORMAL_CLOSURE\n\n\nasync def test_abnormal_closure_when_client_does_not_close(\n    aiohttp_client: AiohttpClient,\n) -> None:\n    \"\"\"Test abnormal closure when the server closes and the client doesn't respond.\"\"\"\n    close_code: Optional[WSCloseCode] = None\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        # Setting a short close timeout\n        ws = web.WebSocketResponse(timeout=0.1)\n        await ws.prepare(request)\n        await ws.close()\n\n        nonlocal close_code\n        assert ws.close_code is not None\n        close_code = WSCloseCode(ws.close_code)\n\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    async with client.ws_connect(\"/\", autoclose=False):\n        await asyncio.sleep(0.2)\n    await client.server.close()\n    assert close_code == WSCloseCode.ABNORMAL_CLOSURE\n\n\nasync def test_normal_closure_while_client_sends_msg(\n    aiohttp_client: AiohttpClient,\n) -> None:\n    \"\"\"Test abnormal closure when the server closes and the client doesn't respond.\"\"\"\n    close_code: Optional[WSCloseCode] = None\n    got_close_code = asyncio.Event()\n\n    async def handler(request: web.Request) -> web.WebSocketResponse:\n        # Setting a short close timeout\n        ws = web.WebSocketResponse(timeout=0.2)\n        await ws.prepare(request)\n        await ws.close()\n\n        nonlocal close_code\n        assert ws.close_code is not None\n        close_code = WSCloseCode(ws.close_code)\n        got_close_code.set()\n\n        return ws\n\n    app = web.Application()\n    app.router.add_route(\"GET\", \"/\", handler)\n    client = await aiohttp_client(app)\n    async with client.ws_connect(\"/\", autoclose=False) as ws:\n        # send text and close message during server close timeout\n        await asyncio.sleep(0.1)\n        await ws.send_str(\"Hello\")\n        await ws.close()\n    # wait for close code to be received by server\n    await asyncio.wait(\n        [\n            asyncio.create_task(asyncio.sleep(0.5)),\n            asyncio.create_task(got_close_code.wait()),\n        ],\n        return_when=asyncio.FIRST_COMPLETED,\n    )\n    await client.server.close()\n    assert close_code == WSCloseCode.OK\n",
        "import asyncio\nimport base64\nimport os\nimport socket\nimport ssl\nimport sys\nfrom hashlib import md5, sha1, sha256\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\nfrom typing import Any\nfrom unittest import mock\nfrom uuid import uuid4\n\nimport pytest\n\nfrom aiohttp.client_proto import ResponseHandler\nfrom aiohttp.http import WS_KEY\nfrom aiohttp.test_utils import loop_context\n\ntry:\n    import trustme\n\n    # Check if the CA is available in runtime, MacOS on Py3.10 fails somehow\n    trustme.CA()\n\n    TRUSTME: bool = True\nexcept ImportError:\n    TRUSTME = False\n\npytest_plugins = [\"aiohttp.pytest_plugin\", \"pytester\"]\n\nIS_HPUX = sys.platform.startswith(\"hp-ux\")\nIS_LINUX = sys.platform.startswith(\"linux\")\n\n\n@pytest.fixture\ndef tls_certificate_authority():\n    if not TRUSTME:\n        pytest.xfail(\"trustme is not supported\")\n    return trustme.CA()\n\n\n@pytest.fixture\ndef tls_certificate(tls_certificate_authority):\n    return tls_certificate_authority.issue_cert(\n        \"localhost\",\n        \"xn--prklad-4va.localhost\",\n        \"127.0.0.1\",\n        \"::1\",\n    )\n\n\n@pytest.fixture\ndef ssl_ctx(tls_certificate):\n    ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n    tls_certificate.configure_cert(ssl_ctx)\n    return ssl_ctx\n\n\n@pytest.fixture\ndef client_ssl_ctx(tls_certificate_authority):\n    ssl_ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)\n    tls_certificate_authority.configure_trust(ssl_ctx)\n    return ssl_ctx\n\n\n@pytest.fixture\ndef tls_ca_certificate_pem_path(tls_certificate_authority):\n    with tls_certificate_authority.cert_pem.tempfile() as ca_cert_pem:\n        yield ca_cert_pem\n\n\n@pytest.fixture\ndef tls_certificate_pem_path(tls_certificate):\n    with tls_certificate.private_key_and_cert_chain_pem.tempfile() as cert_pem:\n        yield cert_pem\n\n\n@pytest.fixture\ndef tls_certificate_pem_bytes(tls_certificate):\n    return tls_certificate.cert_chain_pems[0].bytes()\n\n\n@pytest.fixture\ndef tls_certificate_fingerprint_sha256(tls_certificate_pem_bytes):\n    tls_cert_der = ssl.PEM_cert_to_DER_cert(tls_certificate_pem_bytes.decode())\n    return sha256(tls_cert_der).digest()\n\n\n@pytest.fixture\ndef unix_sockname(tmp_path, tmp_path_factory):\n    \"\"\"Generate an fs path to the UNIX domain socket for testing.\n\n    N.B. Different OS kernels have different fs path length limitations\n    for it. For Linux, it's 108, for HP-UX it's 92 (or higher) depending\n    on its version. For for most of the BSDs (Open, Free, macOS) it's\n    mostly 104 but sometimes it can be down to 100.\n\n    Ref: https://github.com/aio-libs/aiohttp/issues/3572\n    \"\"\"\n    if not hasattr(socket, \"AF_UNIX\"):\n        pytest.skip(\"requires UNIX sockets\")\n\n    max_sock_len = 92 if IS_HPUX else 108 if IS_LINUX else 100\n    \"\"\"Amount of bytes allocated for the UNIX socket path by OS kernel.\n\n    Ref: https://unix.stackexchange.com/a/367012/27133\n    \"\"\"\n\n    sock_file_name = \"unix.sock\"\n    unique_prefix = f\"{uuid4()!s}-\"\n    unique_prefix_len = len(unique_prefix.encode())\n\n    root_tmp_dir = Path(\"/tmp\").resolve()\n    os_tmp_dir = Path(os.getenv(\"TMPDIR\", \"/tmp\")).resolve()\n    original_base_tmp_path = Path(\n        str(tmp_path_factory.getbasetemp()),\n    ).resolve()\n\n    original_base_tmp_path_hash = md5(\n        str(original_base_tmp_path).encode(),\n    ).hexdigest()\n\n    def make_tmp_dir(base_tmp_dir):\n        return TemporaryDirectory(\n            dir=str(base_tmp_dir),\n            prefix=\"pt-\",\n            suffix=f\"-{original_base_tmp_path_hash!s}\",\n        )\n\n    def assert_sock_fits(sock_path):\n        sock_path_len = len(sock_path.encode())\n        # exit-check to verify that it's correct and simplify debugging\n        # in the future\n        assert sock_path_len <= max_sock_len, (\n            \"Suggested UNIX socket ({sock_path}) is {sock_path_len} bytes \"\n            \"long but the current kernel only has {max_sock_len} bytes \"\n            \"allocated to hold it so it must be shorter. \"\n            \"See https://github.com/aio-libs/aiohttp/issues/3572 \"\n            \"for more info.\"\n        ).format_map(locals())\n\n    paths = original_base_tmp_path, os_tmp_dir, root_tmp_dir\n    unique_paths = [p for n, p in enumerate(paths) if p not in paths[:n]]\n    paths_num = len(unique_paths)\n\n    for num, tmp_dir_path in enumerate(paths, 1):\n        with make_tmp_dir(tmp_dir_path) as tmpd:\n            tmpd = Path(tmpd).resolve()\n            sock_path = str(tmpd / sock_file_name)\n            sock_path_len = len(sock_path.encode())\n\n            if num >= paths_num:\n                # exit-check to verify that it's correct and simplify\n                # debugging in the future\n                assert_sock_fits(sock_path)\n\n            if sock_path_len <= max_sock_len:\n                if max_sock_len - sock_path_len >= unique_prefix_len:\n                    # If we're lucky to have extra space in the path,\n                    # let's also make it more unique\n                    sock_path = str(tmpd / \"\".join((unique_prefix, sock_file_name)))\n                    # Double-checking it:\n                    assert_sock_fits(sock_path)\n                yield sock_path\n                return\n\n\n@pytest.fixture\ndef pipe_name():\n    name = rf\"\\\\.\\pipe\\{uuid4().hex}\"\n    return name\n\n\n@pytest.fixture\ndef create_mocked_conn(loop: Any):\n    def _proto_factory(conn_closing_result=None, **kwargs):\n        proto = mock.create_autospec(ResponseHandler, **kwargs)\n        proto.closed = loop.create_future()\n        proto.closed.set_result(conn_closing_result)\n        return proto\n\n    yield _proto_factory\n\n\n@pytest.fixture\ndef selector_loop():\n    policy = asyncio.WindowsSelectorEventLoopPolicy()\n    asyncio.set_event_loop_policy(policy)\n\n    with loop_context(policy.new_event_loop) as _loop:\n        asyncio.set_event_loop(_loop)\n        yield _loop\n\n\n@pytest.fixture\ndef netrc_contents(\n    tmp_path: Path,\n    monkeypatch: pytest.MonkeyPatch,\n    request: pytest.FixtureRequest,\n):\n    \"\"\"\n    Prepare :file:`.netrc` with given contents.\n\n    Monkey-patches :envvar:`NETRC` to point to created file.\n    \"\"\"\n    netrc_contents = getattr(request, \"param\", None)\n\n    netrc_file_path = tmp_path / \".netrc\"\n    if netrc_contents is not None:\n        netrc_file_path.write_text(netrc_contents)\n\n    monkeypatch.setenv(\"NETRC\", str(netrc_file_path))\n\n    return netrc_file_path\n\n\n@pytest.fixture\ndef start_connection():\n    with mock.patch(\n        \"aiohttp.connector.aiohappyeyeballs.start_connection\",\n        autospec=True,\n        spec_set=True,\n    ) as start_connection_mock:\n        yield start_connection_mock\n\n\n@pytest.fixture\ndef key_data():\n    return os.urandom(16)\n\n\n@pytest.fixture\ndef key(key_data: Any):\n    return base64.b64encode(key_data)\n\n\n@pytest.fixture\ndef ws_key(key: Any):\n    return base64.b64encode(sha1(key + WS_KEY).digest()).decode()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "conftest.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "re-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/requirements/cython.txt\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/tools/gen.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/hdrs.py\n./tools/gen.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_http_parser.pyx\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_http_writer.pyx\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_cparser.pxd\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_find_header.pxd\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_websocket/mask.pyx\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_websocket/mask.pxd\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/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_74d9355b6cf9581361668ffd2d38a01b53b58297/vendor/llhttp'\nnpx ts-node bin/generate.ts\nmake[1]: Leaving directory '/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/vendor/llhttp'\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/__init__.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/abc.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/base_protocol.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/client.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/client_exceptions.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/client_proto.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/client_reqrep.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/client_ws.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/compression_utils.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/connector.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/cookiejar.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/formdata.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/helpers.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/http.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/http_exceptions.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/http_parser.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/http_websocket.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/http_writer.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/log.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/multipart.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/payload.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/payload_streamer.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/pytest_plugin.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/resolver.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/streams.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/tcp_helpers.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/test_utils.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/tracing.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/typedefs.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_app.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_exceptions.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_fileresponse.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_log.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_middlewares.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_protocol.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_request.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_response.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_routedef.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_runner.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_server.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_urldispatcher.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_ws.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/worker.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_websocket/__init__.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_websocket/helpers.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_websocket/models.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_websocket/reader.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_websocket/reader_c.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/_websocket/reader_py.py\nre-hash /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/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 41ms\nPrepared 1 package in 0.26ms\nInstalled 1 package in 45ms\n + pip==24.3.1\nResolved 3 packages in 7ms\nInstalled 3 packages in 22ms\n + cython==3.0.11\n + multidict==6.1.0\n + typing-extensions==4.12.2\nResolved 97 packages in 49ms\nInstalled 94 packages in 100ms\n + aiodns==3.2.0\n + aiohappyeyeballs==2.4.3\n + aiohttp-theme==0.1.7\n + aiosignal==1.3.1\n + alabaster==0.7.13\n + annotated-types==0.7.0\n + async-timeout==4.0.3\n + attrs==24.2.0\n + babel==2.16.0\n + brotli==1.1.0\n + build==1.2.2.post1\n + certifi==2024.8.30\n + cffi==1.17.1\n + cfgv==3.4.0\n + charset-normalizer==3.4.0\n + cherry-picker==2.2.0\n + click==8.1.7\n + coverage==7.6.1\n + cryptography==43.0.3\n + distlib==0.3.9\n + docutils==0.20.1\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + freezegun==1.5.1\n + frozenlist==1.5.0\n + gidgethub==5.3.0\n + gunicorn==23.0.0\n + identify==2.6.1\n + idna==3.4\n + imagesize==1.4.1\n + importlib-metadata==8.5.0\n + importlib-resources==6.4.5\n + incremental==24.7.2\n + iniconfig==2.0.0\n + jinja2==3.1.4\n + markdown-it-py==3.0.0\n + markupsafe==2.1.5\n + mdurl==0.1.2\n + mypy==1.11.2\n + mypy-extensions==1.0.0\n + nodeenv==1.9.1\n + packaging==24.1\n + pip-tools==7.4.1\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pre-commit==3.5.0\n + propcache==0.2.0\n + proxy-py==2.4.9\n + pycares==4.4.0\n + pycparser==2.22\n + pydantic==2.9.2\n + pydantic-core==2.23.4\n + pygments==2.18.0\n + pyjwt==2.8.0\n + pyproject-hooks==1.2.0\n + pytest==8.3.3\n + pytest-codspeed==3.0.0\n + pytest-cov==5.0.0\n + pytest-mock==3.14.0\n + python-dateutil==2.9.0.post0\n + python-on-whales==0.73.0\n + pyyaml==6.0.2\n + re-assert==1.1.0\n + regex==2024.9.11\n + requests==2.32.3\n + rich==13.9.3\n + setuptools==75.2.0\n + setuptools-git==1.2\n + shellingham==1.5.4\n + six==1.16.0\n + slotscheck==0.19.1\n + snowballstemmer==2.2.0\n + sphinx==7.1.2\n + sphinxcontrib-applehelp==1.0.4\n + sphinxcontrib-devhelp==1.0.2\n + sphinxcontrib-htmlhelp==2.0.1\n + sphinxcontrib-jsmath==1.0.1\n + sphinxcontrib-qthelp==1.0.3\n + sphinxcontrib-serializinghtml==1.1.5\n + sphinxcontrib-towncrier==0.4.0a0\n + tomli==2.0.2\n + towncrier==23.11.0\n + tqdm==4.66.5\n + trustme==1.1.0\n + typer==0.12.5\n + uritemplate==4.1.1\n + urllib3==2.2.3\n + uvloop==0.21.0\n + valkey==6.0.2\n + virtualenv==20.27.0\n + wait-for-it==2.2.2\n + wheel==0.44.0\n + yarl==1.17.1\n + zipp==3.20.2\nResolved 11 packages in 1.64s\n  × Failed to build `aiohttp @ file:///home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297`\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/.tmpAM5NSC/.tmp-a_mj6hdl/aiohttp.egg-info\n      writing /home/gcpuser/.cache/uv/builds-v0/.tmpAM5NSC/.tmp-a_mj6hdl/aiohttp.egg-info/PKG-INFO\n      writing dependency_links to /home/gcpuser/.cache/uv/builds-v0/.tmpAM5NSC/.tmp-a_mj6hdl/aiohttp.egg-info/dependency_links.txt\n      writing requirements to /home/gcpuser/.cache/uv/builds-v0/.tmpAM5NSC/.tmp-a_mj6hdl/aiohttp.egg-info/requires.txt\n      writing top-level names to /home/gcpuser/.cache/uv/builds-v0/.tmpAM5NSC/.tmp-a_mj6hdl/aiohttp.egg-info/top_level.txt\n      writing manifest file '/home/gcpuser/.cache/uv/builds-v0/.tmpAM5NSC/.tmp-a_mj6hdl/aiohttp.egg-info/SOURCES.txt'\n      reading manifest file '/home/gcpuser/.cache/uv/builds-v0/.tmpAM5NSC/.tmp-a_mj6hdl/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/.tmpAM5NSC/.tmp-a_mj6hdl/aiohttp.egg-info/SOURCES.txt'\n      creating '/home/gcpuser/.cache/uv/builds-v0/.tmpAM5NSC/.tmp-a_mj6hdl/aiohttp-3.11.0b3.dist-info'\n      creating /home/gcpuser/.cache/uv/builds-v0/.tmpAM5NSC/.tmp-a_mj6hdl/aiohttp-3.11.0b3.dist-info/WHEEL\n      running build_py\n      running build_ext\n      building 'aiohttp._websocket.mask' extension\n      creating /tmp/tmpwtiywgj5.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/.tmpKLB7RO/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/tmpwtiywgj5.build-temp/aiohttp/_websocket/mask.o\n      creating /tmp/tmpqmxeoq75.build-lib/aiohttp/_websocket\n      cc -pthread -shared -Wl,--exclude-libs,ALL /tmp/tmpwtiywgj5.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/tmpqmxeoq75.build-lib/aiohttp/_websocket/mask.cpython-39-x86_64-linux-gnu.so\n      building 'aiohttp._http_parser' extension\n      creating /tmp/tmpwtiywgj5.build-temp/vendor/llhttp/build/c\n      creating /tmp/tmpwtiywgj5.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/.tmpKLB7RO/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/tmpwtiywgj5.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/.tmpKLB7RO/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/tmpwtiywgj5.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/.tmpKLB7RO/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/tmpwtiywgj5.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/.tmpKLB7RO/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/tmpwtiywgj5.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/.tmpKLB7RO/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/tmpwtiywgj5.build-temp/vendor/llhttp/src/native/http.o\n      cc -pthread -shared -Wl,--exclude-libs,ALL /tmp/tmpwtiywgj5.build-temp/aiohttp/_find_header.o /tmp/tmpwtiywgj5.build-temp/aiohttp/_http_parser.o\n      /tmp/tmpwtiywgj5.build-temp/vendor/llhttp/build/c/llhttp.o /tmp/tmpwtiywgj5.build-temp/vendor/llhttp/src/native/api.o\n      /tmp/tmpwtiywgj5.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/tmpqmxeoq75.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/.tmpKLB7RO/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/tmpwtiywgj5.build-temp/aiohttp/_http_writer.o\n      cc -pthread -shared -Wl,--exclude-libs,ALL /tmp/tmpwtiywgj5.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/tmpqmxeoq75.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/.tmpKLB7RO/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/tmpwtiywgj5.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/.tmpKLB7RO/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/.tmpKLB7RO/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/tmpwtiywgj5.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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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/.tmpKLB7RO/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 14ms\nInstalled 5 packages in 5ms\n + async-generator==1.10\n + brotlipy==0.7.0\n + chardet==5.2.0\n + multdict==0.0.5\n + pytest-asyncio==0.25.0\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.3, pluggy-1.5.0 -- /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/.venv/bin/python\ncodspeed: 3.0.0 (disabled, mode: walltime, timer_resolution: 1.0ns)\ncachedir: .pytest_cache\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297\nconfigfile: setup.cfg\nplugins: cov-5.0.0, asyncio-0.25.0, mock-3.14.0, codspeed-3.0.0\nasyncio: mode=strict, asyncio_default_fixture_loop_scope=None\ncollecting ... collected 40 items\n\nr2e_tests/test_1.py::test_websocket_can_prepare[pyloop] PASSED           [  2%]\nr2e_tests/test_1.py::test_websocket_json[pyloop] PASSED                  [  5%]\nr2e_tests/test_1.py::test_websocket_json_invalid_message[pyloop] PASSED  [  7%]\nr2e_tests/test_1.py::test_websocket_send_json[pyloop] PASSED             [ 10%]\nr2e_tests/test_1.py::test_websocket_receive_json[pyloop] PASSED          [ 12%]\nr2e_tests/test_1.py::test_send_recv_text[pyloop] PASSED                  [ 15%]\nr2e_tests/test_1.py::test_send_recv_bytes[pyloop] PASSED                 [ 17%]\nr2e_tests/test_1.py::test_send_recv_json[pyloop] PASSED                  [ 20%]\nr2e_tests/test_1.py::test_close_timeout[pyloop] PASSED                   [ 22%]\nr2e_tests/test_1.py::test_concurrent_close[pyloop] PASSED                [ 25%]\nr2e_tests/test_1.py::test_concurrent_close_multiple_tasks[pyloop] PASSED [ 27%]\nr2e_tests/test_1.py::test_close_op_code_from_client[pyloop] PASSED       [ 30%]\nr2e_tests/test_1.py::test_auto_pong_with_closing_by_peer[pyloop] PASSED  [ 32%]\nr2e_tests/test_1.py::test_ping[pyloop] PASSED                            [ 35%]\nr2e_tests/test_1.py::test_pong[pyloop] PASSED                            [ 37%]\nr2e_tests/test_1.py::test_change_status[pyloop] PASSED                   [ 40%]\nr2e_tests/test_1.py::test_handle_protocol[pyloop] PASSED                 [ 42%]\nr2e_tests/test_1.py::test_server_close_handshake[pyloop] PASSED          [ 45%]\nr2e_tests/test_1.py::test_server_close_handshake_server_eats_client_messages[pyloop] PASSED [ 47%]\nr2e_tests/test_1.py::test_receive_timeout[pyloop] PASSED                 [ 50%]\nr2e_tests/test_1.py::test_custom_receive_timeout[pyloop] PASSED          [ 52%]\nr2e_tests/test_1.py::test_heartbeat[pyloop] PASSED                       [ 55%]\nr2e_tests/test_1.py::test_heartbeat_no_pong[pyloop] PASSED               [ 57%]\nr2e_tests/test_1.py::test_heartbeat_connection_closed[pyloop] PASSED     [ 60%]\nr2e_tests/test_1.py::test_heartbeat_failure_ends_receive[pyloop] PASSED  [ 62%]\nr2e_tests/test_1.py::test_heartbeat_no_pong_send_many_messages[pyloop] PASSED [ 65%]\nr2e_tests/test_1.py::test_heartbeat_no_pong_receive_many_messages[pyloop] PASSED [ 67%]\nr2e_tests/test_1.py::test_server_ws_async_for[pyloop] PASSED             [ 70%]\nr2e_tests/test_1.py::test_closed_async_for[pyloop] PASSED                [ 72%]\nr2e_tests/test_1.py::test_websocket_disable_keepalive[pyloop] PASSED     [ 75%]\nr2e_tests/test_1.py::test_receive_str_nonstring[pyloop] PASSED           [ 77%]\nr2e_tests/test_1.py::test_receive_bytes_nonbytes[pyloop] PASSED          [ 80%]\nr2e_tests/test_1.py::test_bug3380[pyloop] PASSED                         [ 82%]\nr2e_tests/test_1.py::test_receive_being_cancelled_keeps_connection_open[pyloop] PASSED [ 85%]\nr2e_tests/test_1.py::test_receive_timeout_keeps_connection_open[pyloop] PASSED [ 87%]\nr2e_tests/test_1.py::test_websocket_shutdown[pyloop] PASSED              [ 90%]\nr2e_tests/test_1.py::test_ws_close_return_code[pyloop] PASSED            [ 92%]\nr2e_tests/test_1.py::test_abnormal_closure_when_server_does_not_receive[pyloop] PASSED [ 95%]\nr2e_tests/test_1.py::test_abnormal_closure_when_client_does_not_close[pyloop] PASSED [ 97%]\nr2e_tests/test_1.py::test_normal_closure_while_client_sends_msg[pyloop] PASSED [100%]\n\n==================================== PASSES ====================================\n________________________ test_concurrent_close[pyloop] _________________________\n------------------------------ Captured log call -------------------------------\nERROR    aiohttp.server:web_protocol.py:449 Error handling request\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_protocol.py\", line 478, in _handle_request\n    resp = await request_handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_app.py\", line 559, in _handle\n    return await handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/r2e_tests/test_1.py\", line 294, in handler\n    assert msg.type == WSMsgType.CLOSING\nAssertionError: assert <WSMsgType.CLOSED: 257> == <WSMsgType.CLOSING: 256>\n +  where <WSMsgType.CLOSED: 257> = WSMessage(type=<WSMsgType.CLOSED: 257>, data=None, extra=None).type\n +  and   <WSMsgType.CLOSING: 256> = WSMsgType.CLOSING\n_________________ test_concurrent_close_multiple_tasks[pyloop] _________________\n------------------------------ Captured log call -------------------------------\nERROR    aiohttp.server:web_protocol.py:449 Error handling request\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_protocol.py\", line 478, in _handle_request\n    resp = await request_handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_app.py\", line 559, in _handle\n    return await handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/r2e_tests/test_1.py\", line 331, in handler\n    assert msg.type == WSMsgType.CLOSING\nAssertionError: assert <WSMsgType.CLOSED: 257> == <WSMsgType.CLOSING: 256>\n +  where <WSMsgType.CLOSED: 257> = WSMessage(type=<WSMsgType.CLOSED: 257>, data=None, extra=None).type\n +  and   <WSMsgType.CLOSING: 256> = WSMsgType.CLOSING\n_____________________ test_receive_bytes_nonbytes[pyloop] ______________________\n------------------------------ Captured log call -------------------------------\nERROR    aiohttp.server:web_protocol.py:449 Error handling request\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_protocol.py\", line 478, in _handle_request\n    resp = await request_handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_app.py\", line 559, in _handle\n    return await handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/r2e_tests/test_1.py\", line 982, in handler\n    assert False\nAssertionError: assert False\n---------------------------- Captured log teardown -----------------------------\nERROR    asyncio:base_events.py:1753 Task was destroyed but it is pending!\ntask: <Task pending name='Task-264' coro=<sleep() done, defined at /home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/asyncio/tasks.py:633> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7fe3cdbb26a0>()]>>\n\n---------- coverage: platform linux, python 3.9.21-final-0 -----------\nName                                      Stmts   Miss Branch BrPart  Cover\n---------------------------------------------------------------------------\naiohttp/__init__.py                          27      8      2      1    69%\naiohttp/_websocket/__init__.py                0      0      0      0   100%\naiohttp/_websocket/helpers.py                77     40     38      1    38%\naiohttp/_websocket/models.py                 51      3      0      0    94%\naiohttp/_websocket/reader.py                  5      0      0      0   100%\naiohttp/_websocket/reader_py.py             208     55     92     25    67%\naiohttp/_websocket/writer.py                 75     21     24      5    66%\naiohttp/abc.py                               98      2      0      0    98%\naiohttp/base_protocol.py                     68     36     22      3    39%\naiohttp/client.py                           561    210    210     67    57%\naiohttp/client_exceptions.py                156     57     20      3    58%\naiohttp/client_proto.py                     164     36     56     11    73%\naiohttp/client_reqrep.py                    703    280    298     74    52%\naiohttp/client_ws.py                        274    110     84     20    56%\naiohttp/compression_utils.py                 70     36     14      0    40%\naiohttp/connector.py                        761    419    332     50    38%\naiohttp/cookiejar.py                        274    203    130      2    18%\naiohttp/formdata.py                          97     79     46      0    13%\naiohttp/hdrs.py                              90      0      0      0   100%\naiohttp/helpers.py                          470    200    168     23    50%\naiohttp/http.py                              11      0      2      0   100%\naiohttp/http_exceptions.py                   50     20      4      0    56%\naiohttp/http_parser.py                      508    211    210     50    52%\naiohttp/http_websocket.py                     6      0      0      0   100%\naiohttp/http_writer.py                      119     42     50     13    56%\naiohttp/log.py                                7      0      0      0   100%\naiohttp/multipart.py                        623    508    266      1    13%\naiohttp/payload.py                          237    113     58      1    44%\naiohttp/payload_streamer.py                  31     11      4      0    69%\naiohttp/pytest_plugin.py                    163     54     42      9    63%\naiohttp/resolver.py                          79     55     26      2    25%\naiohttp/streams.py                          413    196    152     28    45%\naiohttp/tcp_helpers.py                       19      2      6      3    80%\naiohttp/test_utils.py                       324    116     54     13    60%\naiohttp/tracing.py                          191     69     32      0    69%\naiohttp/typedefs.py                          24      0      0      0   100%\naiohttp/web.py                              126     88     54      0    22%\naiohttp/web_app.py                          292    105     82     20    57%\naiohttp/web_exceptions.py                   157     20      8      1    85%\naiohttp/web_fileresponse.py                 160    126     52      0    18%\naiohttp/web_log.py                          102     37     20      1    59%\naiohttp/web_middlewares.py                   59     41     22      0    22%\naiohttp/web_protocol.py                     367    105    158     51    64%\naiohttp/web_request.py                      445    247    140     10    37%\naiohttp/web_response.py                     485    207    226     38    48%\naiohttp/web_routedef.py                     100     44     10      0    55%\naiohttp/web_runner.py                       213     72     36     11    62%\naiohttp/web_server.py                        42      5     12      1    85%\naiohttp/web_urldispatcher.py                740    377    163     21    43%\naiohttp/web_ws.py                           388     66    136     34    79%\naiohttp/worker.py                           126    126     30      0     0%\ntests/conftest.py                           131    131     16      0     0%\ntests/test_base_protocol.py                 198    198      2      0     0%\ntests/test_benchmarks_client.py              18     18      2      0     0%\ntests/test_benchmarks_client_request.py      24     24      0      0     0%\ntests/test_benchmarks_client_ws.py           66     66     12      0     0%\ntests/test_benchmarks_cookiejar.py           14     14      0      0     0%\ntests/test_benchmarks_http_websocket.py      49     49      8      0     0%\ntests/test_benchmarks_http_writer.py         11     11      2      0     0%\ntests/test_circular_imports.py               29     29     13      0     0%\ntests/test_classbasedview.py                 39     39      0      0     0%\ntests/test_client_connection.py              94     94      2      0     0%\ntests/test_client_exceptions.py             199    199     14      0     0%\ntests/test_client_fingerprint.py             59     59      0      0     0%\ntests/test_client_functional.py            2616   2616     88      0     0%\ntests/test_client_proto.py                   99     99      0      0     0%\ntests/test_client_request.py                827    827     18      0     0%\ntests/test_client_response.py               480    480      6      0     0%\ntests/test_client_session.py                593    593     29      0     0%\ntests/test_client_ws.py                     489    489      2      0     0%\ntests/test_client_ws_functional.py          831    831     32      0     0%\ntests/test_connector.py                    2050   2050    106      0     0%\ntests/test_cookiejar.py                     461    461     32      0     0%\ntests/test_flowcontrol_streams.py            96     96      0      0     0%\ntests/test_formdata.py                       86     86      6      0     0%\ntests/test_helpers.py                       454    454     22      0     0%\ntests/test_http_exceptions.py               109    109     10      0     0%\ntests/test_http_parser.py                  1092   1092     66      0     0%\ntests/test_http_writer.py                   182    182     10      0     0%\ntests/test_imports.py                        34     34      6      0     0%\ntests/test_loop.py                           36     36      0      0     0%\ntests/test_multipart.py                     826    826     32      0     0%\ntests/test_multipart_helpers.py             446    446      0      0     0%\ntests/test_payload.py                        95     95      0      0     0%\ntests/test_proxy.py                         324    324      2      0     0%\ntests/test_proxy_functional.py              459    459     18      0     0%\ntests/test_pytest_plugin.py                  27     27      0      0     0%\ntests/test_resolver.py                      231    231     20      0     0%\ntests/test_route_def.py                     210    210      0      0     0%\ntests/test_run_app.py                       563    563     30      0     0%\ntests/test_streams.py                      1077   1077     38      0     0%\ntests/test_tcp_helpers.py                    52     52      2      0     0%\ntests/test_test_utils.py                    273    273     12      0     0%\ntests/test_tracing.py                        48     48      0      0     0%\ntests/test_urldispatch.py                   859    859     24      0     0%\ntests/test_web_app.py                       454    454      6      0     0%\ntests/test_web_cli.py                        94     94      0      0     0%\ntests/test_web_exceptions.py                179    179     22      0     0%\ntests/test_web_functional.py               1605   1605     36      0     0%\ntests/test_web_log.py                       116    116      2      0     0%\ntests/test_web_middleware.py                268    268     16      0     0%\ntests/test_web_request.py                   513    513      8      0     0%\ntests/test_web_request_handler.py            42     42      0      0     0%\ntests/test_web_response.py                  905    905      6      0     0%\ntests/test_web_runner.py                    151    151      4      0     0%\ntests/test_web_sendfile.py                   84     84      0      0     0%\ntests/test_web_sendfile_functional.py       673    673     18      0     0%\ntests/test_web_server.py                    162    162      0      0     0%\ntests/test_web_urldispatcher.py             524    524     24      0     0%\ntests/test_web_websocket.py                 444    444      8      0     0%\ntests/test_web_websocket_functional.py      862    862     28      0     0%\ntests/test_websocket_handshake.py           152    152     12      0     0%\ntests/test_websocket_parser.py              332    332     12      0     0%\ntests/test_websocket_writer.py               95     95      6      0     0%\ntests/test_worker.py                        191    191      2      0     0%\n---------------------------------------------------------------------------\nTOTAL                                     35638  29660   4483    593    17%\n\n============================= slowest 10 durations =============================\n0.20s call     r2e_tests/test_1.py::test_abnormal_closure_when_client_does_not_close[pyloop]\n0.16s call     r2e_tests/test_1.py::test_close_timeout[pyloop]\n0.10s call     r2e_tests/test_1.py::test_normal_closure_while_client_sends_msg[pyloop]\n0.10s call     r2e_tests/test_1.py::test_receive_timeout[pyloop]\n0.10s call     r2e_tests/test_1.py::test_custom_receive_timeout[pyloop]\n0.10s call     r2e_tests/test_1.py::test_abnormal_closure_when_server_does_not_receive[pyloop]\n0.08s call     r2e_tests/test_1.py::test_heartbeat_failure_ends_receive[pyloop]\n0.05s call     r2e_tests/test_1.py::test_heartbeat_no_pong_receive_many_messages[pyloop]\n0.05s call     r2e_tests/test_1.py::test_heartbeat_no_pong_send_many_messages[pyloop]\n0.05s call     r2e_tests/test_1.py::test_heartbeat[pyloop]\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_websocket_can_prepare[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_json[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_json_invalid_message[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_send_json[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_receive_json[pyloop]\nPASSED r2e_tests/test_1.py::test_send_recv_text[pyloop]\nPASSED r2e_tests/test_1.py::test_send_recv_bytes[pyloop]\nPASSED r2e_tests/test_1.py::test_send_recv_json[pyloop]\nPASSED r2e_tests/test_1.py::test_close_timeout[pyloop]\nPASSED r2e_tests/test_1.py::test_concurrent_close[pyloop]\nPASSED r2e_tests/test_1.py::test_concurrent_close_multiple_tasks[pyloop]\nPASSED r2e_tests/test_1.py::test_close_op_code_from_client[pyloop]\nPASSED r2e_tests/test_1.py::test_auto_pong_with_closing_by_peer[pyloop]\nPASSED r2e_tests/test_1.py::test_ping[pyloop]\nPASSED r2e_tests/test_1.py::test_pong[pyloop]\nPASSED r2e_tests/test_1.py::test_change_status[pyloop]\nPASSED r2e_tests/test_1.py::test_handle_protocol[pyloop]\nPASSED r2e_tests/test_1.py::test_server_close_handshake[pyloop]\nPASSED r2e_tests/test_1.py::test_server_close_handshake_server_eats_client_messages[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_timeout[pyloop]\nPASSED r2e_tests/test_1.py::test_custom_receive_timeout[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat_no_pong[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat_connection_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat_failure_ends_receive[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat_no_pong_send_many_messages[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat_no_pong_receive_many_messages[pyloop]\nPASSED r2e_tests/test_1.py::test_server_ws_async_for[pyloop]\nPASSED r2e_tests/test_1.py::test_closed_async_for[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_disable_keepalive[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_str_nonstring[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_bytes_nonbytes[pyloop]\nPASSED r2e_tests/test_1.py::test_bug3380[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_being_cancelled_keeps_connection_open[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_timeout_keeps_connection_open[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_shutdown[pyloop]\nPASSED r2e_tests/test_1.py::test_ws_close_return_code[pyloop]\nPASSED r2e_tests/test_1.py::test_abnormal_closure_when_server_does_not_receive[pyloop]\nPASSED r2e_tests/test_1.py::test_abnormal_closure_when_client_does_not_close[pyloop]\nPASSED r2e_tests/test_1.py::test_normal_closure_while_client_sends_msg[pyloop]\n============================== 40 passed in 6.30s ==============================\n",
    "new_commit_res_stderr": "/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/.venv/lib/python3.9/site-packages/pytest_asyncio/plugin.py:207: PytestDeprecationWarning: The configuration option \"asyncio_default_fixture_loop_scope\" is unset.\nThe event loop scope for asynchronous fixtures will default to the fixture caching scope. Future versions of pytest-asyncio will default the loop scope for asynchronous fixtures to function scope. Set the default fixture loop scope explicitly in order to avoid unexpected behavior in the future. Valid fixture loop scopes are: \"function\", \"class\", \"module\", \"package\", \"session\"\n\n  warnings.warn(PytestDeprecationWarning(_DEFAULT_FIXTURE_LOOP_SCOPE_UNSET))\n",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.3, pluggy-1.5.0 -- /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/.venv/bin/python\ncodspeed: 3.0.0 (disabled, mode: walltime, timer_resolution: 1.0ns)\ncachedir: .pytest_cache\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297\nconfigfile: setup.cfg\nplugins: cov-5.0.0, asyncio-0.25.0, mock-3.14.0, codspeed-3.0.0\nasyncio: mode=strict, asyncio_default_fixture_loop_scope=None\ncollecting ... collected 40 items\n\nr2e_tests/test_1.py::test_websocket_can_prepare[pyloop] PASSED           [  2%]\nr2e_tests/test_1.py::test_websocket_json[pyloop] PASSED                  [  5%]\nr2e_tests/test_1.py::test_websocket_json_invalid_message[pyloop] PASSED  [  7%]\nr2e_tests/test_1.py::test_websocket_send_json[pyloop] PASSED             [ 10%]\nr2e_tests/test_1.py::test_websocket_receive_json[pyloop] PASSED          [ 12%]\nr2e_tests/test_1.py::test_send_recv_text[pyloop] PASSED                  [ 15%]\nr2e_tests/test_1.py::test_send_recv_bytes[pyloop] PASSED                 [ 17%]\nr2e_tests/test_1.py::test_send_recv_json[pyloop] PASSED                  [ 20%]\nr2e_tests/test_1.py::test_close_timeout[pyloop] PASSED                   [ 22%]\nr2e_tests/test_1.py::test_concurrent_close[pyloop] PASSED                [ 25%]\nr2e_tests/test_1.py::test_concurrent_close_multiple_tasks[pyloop] PASSED [ 27%]\nr2e_tests/test_1.py::test_close_op_code_from_client[pyloop] PASSED       [ 30%]\nr2e_tests/test_1.py::test_auto_pong_with_closing_by_peer[pyloop] PASSED  [ 32%]\nr2e_tests/test_1.py::test_ping[pyloop] PASSED                            [ 35%]\nr2e_tests/test_1.py::test_pong[pyloop] PASSED                            [ 37%]\nr2e_tests/test_1.py::test_change_status[pyloop] PASSED                   [ 40%]\nr2e_tests/test_1.py::test_handle_protocol[pyloop] PASSED                 [ 42%]\nr2e_tests/test_1.py::test_server_close_handshake[pyloop] PASSED          [ 45%]\nr2e_tests/test_1.py::test_server_close_handshake_server_eats_client_messages[pyloop] PASSED [ 47%]\nr2e_tests/test_1.py::test_receive_timeout[pyloop] PASSED                 [ 50%]\nr2e_tests/test_1.py::test_custom_receive_timeout[pyloop] PASSED          [ 52%]\nr2e_tests/test_1.py::test_heartbeat[pyloop] PASSED                       [ 55%]\nr2e_tests/test_1.py::test_heartbeat_no_pong[pyloop] PASSED               [ 57%]\nr2e_tests/test_1.py::test_heartbeat_connection_closed[pyloop] PASSED     [ 60%]\nr2e_tests/test_1.py::test_heartbeat_failure_ends_receive[pyloop] PASSED  [ 62%]\nr2e_tests/test_1.py::test_heartbeat_no_pong_send_many_messages[pyloop] PASSED [ 65%]\nr2e_tests/test_1.py::test_heartbeat_no_pong_receive_many_messages[pyloop] PASSED [ 67%]\nr2e_tests/test_1.py::test_server_ws_async_for[pyloop] PASSED             [ 70%]\nr2e_tests/test_1.py::test_closed_async_for[pyloop] PASSED                [ 72%]\nr2e_tests/test_1.py::test_websocket_disable_keepalive[pyloop] PASSED     [ 75%]\nr2e_tests/test_1.py::test_receive_str_nonstring[pyloop] PASSED           [ 77%]\nr2e_tests/test_1.py::test_receive_bytes_nonbytes[pyloop] PASSED          [ 80%]\nr2e_tests/test_1.py::test_bug3380[pyloop] PASSED                         [ 82%]\nr2e_tests/test_1.py::test_receive_being_cancelled_keeps_connection_open[pyloop] PASSED [ 85%]\nr2e_tests/test_1.py::test_receive_timeout_keeps_connection_open[pyloop] PASSED [ 87%]\nr2e_tests/test_1.py::test_websocket_shutdown[pyloop] PASSED              [ 90%]\nr2e_tests/test_1.py::test_ws_close_return_code[pyloop] PASSED            [ 92%]\nr2e_tests/test_1.py::test_abnormal_closure_when_server_does_not_receive[pyloop] PASSED [ 95%]\nr2e_tests/test_1.py::test_abnormal_closure_when_client_does_not_close[pyloop] PASSED [ 97%]\nr2e_tests/test_1.py::test_normal_closure_while_client_sends_msg[pyloop] FAILED [100%]\n\n=================================== FAILURES ===================================\n______________ test_normal_closure_while_client_sends_msg[pyloop] ______________\n\naiohttp_client = <function aiohttp_client.<locals>.go at 0x7550488763a0>\n\n    async def test_normal_closure_while_client_sends_msg(\n        aiohttp_client: AiohttpClient,\n    ) -> None:\n        \"\"\"Test abnormal closure when the server closes and the client doesn't respond.\"\"\"\n        close_code: Optional[WSCloseCode] = None\n        got_close_code = asyncio.Event()\n    \n        async def handler(request: web.Request) -> web.WebSocketResponse:\n            # Setting a short close timeout\n            ws = web.WebSocketResponse(timeout=0.2)\n            await ws.prepare(request)\n            await ws.close()\n    \n            nonlocal close_code\n            assert ws.close_code is not None\n            close_code = WSCloseCode(ws.close_code)\n            got_close_code.set()\n    \n            return ws\n    \n        app = web.Application()\n        app.router.add_route(\"GET\", \"/\", handler)\n        client = await aiohttp_client(app)\n        async with client.ws_connect(\"/\", autoclose=False) as ws:\n            # send text and close message during server close timeout\n            await asyncio.sleep(0.1)\n            await ws.send_str(\"Hello\")\n            await ws.close()\n        # wait for close code to be received by server\n        await asyncio.wait(\n            [\n                asyncio.create_task(asyncio.sleep(0.5)),\n                asyncio.create_task(got_close_code.wait()),\n            ],\n            return_when=asyncio.FIRST_COMPLETED,\n        )\n        await client.server.close()\n>       assert close_code == WSCloseCode.OK\nE       assert <WSCloseCode.ABNORMAL_CLOSURE: 1006> == <WSCloseCode.OK: 1000>\nE        +  where <WSCloseCode.OK: 1000> = WSCloseCode.OK\n\naiohttp_client = <function aiohttp_client.<locals>.go at 0x7550488763a0>\napp        = <Application 0x7550488f19d0>\nclient     = <aiohttp.test_utils.TestClient object at 0x7550488f1ac0>\nclose_code = <WSCloseCode.ABNORMAL_CLOSURE: 1006>\ngot_close_code = <asyncio.locks.Event object at 0x7550488f1a90 [set]>\nhandler    = <function test_normal_closure_while_client_sends_msg.<locals>.handler at 0x755048876940>\nws         = <aiohttp.client_ws.ClientWebSocketResponse object at 0x755048898d90>\n\nr2e_tests/test_1.py:1279: AssertionError\n---------------------------- Captured log teardown -----------------------------\nERROR    asyncio:base_events.py:1753 Task was destroyed but it is pending!\ntask: <Task pending name='Task-264' coro=<sleep() running at /home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/asyncio/tasks.py:652> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x755048898ac0>()]>>\n==================================== PASSES ====================================\n________________________ test_concurrent_close[pyloop] _________________________\n------------------------------ Captured log call -------------------------------\nERROR    aiohttp.server:web_protocol.py:449 Error handling request\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_protocol.py\", line 478, in _handle_request\n    resp = await request_handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_app.py\", line 559, in _handle\n    return await handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/r2e_tests/test_1.py\", line 294, in handler\n    assert msg.type == WSMsgType.CLOSING\nAssertionError: assert <WSMsgType.CLOSED: 257> == <WSMsgType.CLOSING: 256>\n +  where <WSMsgType.CLOSED: 257> = WSMessage(type=<WSMsgType.CLOSED: 257>, data=None, extra=None).type\n +  and   <WSMsgType.CLOSING: 256> = WSMsgType.CLOSING\n_________________ test_concurrent_close_multiple_tasks[pyloop] _________________\n------------------------------ Captured log call -------------------------------\nERROR    aiohttp.server:web_protocol.py:449 Error handling request\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_protocol.py\", line 478, in _handle_request\n    resp = await request_handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_app.py\", line 559, in _handle\n    return await handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/r2e_tests/test_1.py\", line 331, in handler\n    assert msg.type == WSMsgType.CLOSING\nAssertionError: assert <WSMsgType.CLOSED: 257> == <WSMsgType.CLOSING: 256>\n +  where <WSMsgType.CLOSED: 257> = WSMessage(type=<WSMsgType.CLOSED: 257>, data=None, extra=None).type\n +  and   <WSMsgType.CLOSING: 256> = WSMsgType.CLOSING\n_____________________ test_receive_bytes_nonbytes[pyloop] ______________________\n------------------------------ Captured log call -------------------------------\nERROR    aiohttp.server:web_protocol.py:449 Error handling request\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_protocol.py\", line 478, in _handle_request\n    resp = await request_handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/aiohttp/web_app.py\", line 559, in _handle\n    return await handler(request)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/r2e_tests/test_1.py\", line 982, in handler\n    assert False\nAssertionError: assert False\n\n---------- coverage: platform linux, python 3.9.21-final-0 -----------\nName                                      Stmts   Miss Branch BrPart  Cover\n---------------------------------------------------------------------------\naiohttp/__init__.py                          27      8      2      1    69%\naiohttp/_websocket/__init__.py                0      0      0      0   100%\naiohttp/_websocket/helpers.py                77     40     38      1    38%\naiohttp/_websocket/models.py                 51      3      0      0    94%\naiohttp/_websocket/reader.py                  5      0      0      0   100%\naiohttp/_websocket/reader_py.py             208     55     92     25    67%\naiohttp/_websocket/writer.py                 75     21     24      5    66%\naiohttp/abc.py                               98      2      0      0    98%\naiohttp/base_protocol.py                     68     36     22      3    39%\naiohttp/client.py                           561    210    210     67    57%\naiohttp/client_exceptions.py                156     57     20      3    58%\naiohttp/client_proto.py                     164     36     56     11    73%\naiohttp/client_reqrep.py                    703    280    298     74    52%\naiohttp/client_ws.py                        274    110     84     20    56%\naiohttp/compression_utils.py                 70     36     14      0    40%\naiohttp/connector.py                        761    419    332     50    38%\naiohttp/cookiejar.py                        274    203    130      2    18%\naiohttp/formdata.py                          97     79     46      0    13%\naiohttp/hdrs.py                              90      0      0      0   100%\naiohttp/helpers.py                          470    200    168     23    50%\naiohttp/http.py                              11      0      2      0   100%\naiohttp/http_exceptions.py                   50     20      4      0    56%\naiohttp/http_parser.py                      508    211    210     50    52%\naiohttp/http_websocket.py                     6      0      0      0   100%\naiohttp/http_writer.py                      119     42     50     13    56%\naiohttp/log.py                                7      0      0      0   100%\naiohttp/multipart.py                        623    508    266      1    13%\naiohttp/payload.py                          237    113     58      1    44%\naiohttp/payload_streamer.py                  31     11      4      0    69%\naiohttp/pytest_plugin.py                    163     53     42      9    64%\naiohttp/resolver.py                          79     55     26      2    25%\naiohttp/streams.py                          413    196    152     28    45%\naiohttp/tcp_helpers.py                       19      2      6      3    80%\naiohttp/test_utils.py                       324    116     54     13    60%\naiohttp/tracing.py                          191     69     32      0    69%\naiohttp/typedefs.py                          24      0      0      0   100%\naiohttp/web.py                              126     88     54      0    22%\naiohttp/web_app.py                          292    104     82     20    57%\naiohttp/web_exceptions.py                   157     20      8      1    85%\naiohttp/web_fileresponse.py                 160    126     52      0    18%\naiohttp/web_log.py                          102     37     20      1    59%\naiohttp/web_middlewares.py                   59     41     22      0    22%\naiohttp/web_protocol.py                     367    105    158     51    64%\naiohttp/web_request.py                      445    247    140     10    37%\naiohttp/web_response.py                     485    207    226     38    48%\naiohttp/web_routedef.py                     100     44     10      0    55%\naiohttp/web_runner.py                       213     72     36     11    62%\naiohttp/web_server.py                        42      5     12      1    85%\naiohttp/web_urldispatcher.py                740    377    163     21    43%\naiohttp/web_ws.py                           391     66    136     34    79%\naiohttp/worker.py                           126    126     30      0     0%\ntests/conftest.py                           131    131     16      0     0%\ntests/test_base_protocol.py                 198    198      2      0     0%\ntests/test_benchmarks_client.py              18     18      2      0     0%\ntests/test_benchmarks_client_request.py      24     24      0      0     0%\ntests/test_benchmarks_client_ws.py           66     66     12      0     0%\ntests/test_benchmarks_cookiejar.py           14     14      0      0     0%\ntests/test_benchmarks_http_websocket.py      49     49      8      0     0%\ntests/test_benchmarks_http_writer.py         11     11      2      0     0%\ntests/test_circular_imports.py               29     29     13      0     0%\ntests/test_classbasedview.py                 39     39      0      0     0%\ntests/test_client_connection.py              94     94      2      0     0%\ntests/test_client_exceptions.py             199    199     14      0     0%\ntests/test_client_fingerprint.py             59     59      0      0     0%\ntests/test_client_functional.py            2616   2616     88      0     0%\ntests/test_client_proto.py                   99     99      0      0     0%\ntests/test_client_request.py                827    827     18      0     0%\ntests/test_client_response.py               480    480      6      0     0%\ntests/test_client_session.py                593    593     29      0     0%\ntests/test_client_ws.py                     489    489      2      0     0%\ntests/test_client_ws_functional.py          831    831     32      0     0%\ntests/test_connector.py                    2050   2050    106      0     0%\ntests/test_cookiejar.py                     461    461     32      0     0%\ntests/test_flowcontrol_streams.py            96     96      0      0     0%\ntests/test_formdata.py                       86     86      6      0     0%\ntests/test_helpers.py                       454    454     22      0     0%\ntests/test_http_exceptions.py               109    109     10      0     0%\ntests/test_http_parser.py                  1092   1092     66      0     0%\ntests/test_http_writer.py                   182    182     10      0     0%\ntests/test_imports.py                        34     34      6      0     0%\ntests/test_loop.py                           36     36      0      0     0%\ntests/test_multipart.py                     826    826     32      0     0%\ntests/test_multipart_helpers.py             446    446      0      0     0%\ntests/test_payload.py                        95     95      0      0     0%\ntests/test_proxy.py                         324    324      2      0     0%\ntests/test_proxy_functional.py              459    459     18      0     0%\ntests/test_pytest_plugin.py                  27     27      0      0     0%\ntests/test_resolver.py                      231    231     20      0     0%\ntests/test_route_def.py                     210    210      0      0     0%\ntests/test_run_app.py                       563    563     30      0     0%\ntests/test_streams.py                      1077   1077     38      0     0%\ntests/test_tcp_helpers.py                    52     52      2      0     0%\ntests/test_test_utils.py                    273    273     12      0     0%\ntests/test_tracing.py                        48     48      0      0     0%\ntests/test_urldispatch.py                   859    859     24      0     0%\ntests/test_web_app.py                       454    454      6      0     0%\ntests/test_web_cli.py                        94     94      0      0     0%\ntests/test_web_exceptions.py                179    179     22      0     0%\ntests/test_web_functional.py               1605   1605     36      0     0%\ntests/test_web_log.py                       116    116      2      0     0%\ntests/test_web_middleware.py                268    268     16      0     0%\ntests/test_web_request.py                   513    513      8      0     0%\ntests/test_web_request_handler.py            42     42      0      0     0%\ntests/test_web_response.py                  905    905      6      0     0%\ntests/test_web_runner.py                    151    151      4      0     0%\ntests/test_web_sendfile.py                   84     84      0      0     0%\ntests/test_web_sendfile_functional.py       673    673     18      0     0%\ntests/test_web_server.py                    162    162      0      0     0%\ntests/test_web_urldispatcher.py             524    524     24      0     0%\ntests/test_web_websocket.py                 444    444      8      0     0%\ntests/test_web_websocket_functional.py      825    825     28      0     0%\ntests/test_websocket_handshake.py           152    152     12      0     0%\ntests/test_websocket_parser.py              332    332     12      0     0%\ntests/test_websocket_writer.py               95     95      6      0     0%\ntests/test_worker.py                        191    191      2      0     0%\n---------------------------------------------------------------------------\nTOTAL                                     35604  29621   4483    593    17%\n\n============================= slowest 10 durations =============================\n0.20s call     r2e_tests/test_1.py::test_abnormal_closure_when_client_does_not_close[pyloop]\n0.16s call     r2e_tests/test_1.py::test_close_timeout[pyloop]\n0.11s call     r2e_tests/test_1.py::test_custom_receive_timeout[pyloop]\n0.10s call     r2e_tests/test_1.py::test_normal_closure_while_client_sends_msg[pyloop]\n0.10s call     r2e_tests/test_1.py::test_receive_timeout[pyloop]\n0.10s call     r2e_tests/test_1.py::test_abnormal_closure_when_server_does_not_receive[pyloop]\n0.08s call     r2e_tests/test_1.py::test_heartbeat_failure_ends_receive[pyloop]\n0.06s call     r2e_tests/test_1.py::test_heartbeat_no_pong[pyloop]\n0.06s call     r2e_tests/test_1.py::test_heartbeat[pyloop]\n0.06s call     r2e_tests/test_1.py::test_heartbeat_connection_closed[pyloop]\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_websocket_can_prepare[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_json[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_json_invalid_message[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_send_json[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_receive_json[pyloop]\nPASSED r2e_tests/test_1.py::test_send_recv_text[pyloop]\nPASSED r2e_tests/test_1.py::test_send_recv_bytes[pyloop]\nPASSED r2e_tests/test_1.py::test_send_recv_json[pyloop]\nPASSED r2e_tests/test_1.py::test_close_timeout[pyloop]\nPASSED r2e_tests/test_1.py::test_concurrent_close[pyloop]\nPASSED r2e_tests/test_1.py::test_concurrent_close_multiple_tasks[pyloop]\nPASSED r2e_tests/test_1.py::test_close_op_code_from_client[pyloop]\nPASSED r2e_tests/test_1.py::test_auto_pong_with_closing_by_peer[pyloop]\nPASSED r2e_tests/test_1.py::test_ping[pyloop]\nPASSED r2e_tests/test_1.py::test_pong[pyloop]\nPASSED r2e_tests/test_1.py::test_change_status[pyloop]\nPASSED r2e_tests/test_1.py::test_handle_protocol[pyloop]\nPASSED r2e_tests/test_1.py::test_server_close_handshake[pyloop]\nPASSED r2e_tests/test_1.py::test_server_close_handshake_server_eats_client_messages[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_timeout[pyloop]\nPASSED r2e_tests/test_1.py::test_custom_receive_timeout[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat_no_pong[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat_connection_closed[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat_failure_ends_receive[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat_no_pong_send_many_messages[pyloop]\nPASSED r2e_tests/test_1.py::test_heartbeat_no_pong_receive_many_messages[pyloop]\nPASSED r2e_tests/test_1.py::test_server_ws_async_for[pyloop]\nPASSED r2e_tests/test_1.py::test_closed_async_for[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_disable_keepalive[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_str_nonstring[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_bytes_nonbytes[pyloop]\nPASSED r2e_tests/test_1.py::test_bug3380[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_being_cancelled_keeps_connection_open[pyloop]\nPASSED r2e_tests/test_1.py::test_receive_timeout_keeps_connection_open[pyloop]\nPASSED r2e_tests/test_1.py::test_websocket_shutdown[pyloop]\nPASSED r2e_tests/test_1.py::test_ws_close_return_code[pyloop]\nPASSED r2e_tests/test_1.py::test_abnormal_closure_when_server_does_not_receive[pyloop]\nPASSED r2e_tests/test_1.py::test_abnormal_closure_when_client_does_not_close[pyloop]\nFAILED r2e_tests/test_1.py::test_normal_closure_while_client_sends_msg[pyloop]\n========================= 1 failed, 39 passed in 6.36s =========================\n",
    "old_commit_res_stderr": "/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_74d9355b6cf9581361668ffd2d38a01b53b58297/.venv/lib/python3.9/site-packages/pytest_asyncio/plugin.py:207: PytestDeprecationWarning: The configuration option \"asyncio_default_fixture_loop_scope\" is unset.\nThe event loop scope for asynchronous fixtures will default to the fixture caching scope. Future versions of pytest-asyncio will default the loop scope for asynchronous fixtures to function scope. Set the default fixture loop scope explicitly in order to avoid unexpected behavior in the future. Valid fixture loop scopes are: \"function\", \"class\", \"module\", \"package\", \"session\"\n\n  warnings.warn(PytestDeprecationWarning(_DEFAULT_FIXTURE_LOOP_SCOPE_UNSET))\n"
}
CHANGES/9506.bugfix.rst CONTRIBUTORS.txt aiohttp/web_ws.py tests/test_web_websocket_functional.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]

**Title: WebSocket Closes with ABNORMAL_CLOSURE When Client Sends Message During Server Shutdown**

**Description:**
When the server initiates closing a WebSocket connection while the client sends a message, the connection unexpectedly closes with an `ABNORMAL_CLOSURE` code instead of the expected `OK` closure code.

**Example Code:**
```python
async def test_websocket_close_with_pending_message(aiohttp_client: AiohttpClient) -> None:
    close_code: Optional[WSCloseCode] = None

    async def handler(request: web.Request) -> web.WebSocketResponse:
        ws = web.WebSocketResponse(timeout=0.2)
        await ws.prepare(request)
        await ws.close()
        close_code = WSCloseCode(ws.close_code)
        return ws

    app = web.Application()
    app.router.add_route('GET', '/', handler)
    client = await aiohttp_client(app)
    async with client.ws_connect('/', autoclose=False) as ws:
        await asyncio.sleep(0.1)
        await ws.send_str('Hello')
        await ws.close()
    assert close_code == WSCloseCode.OK
```

**Expected Behavior:**
The WebSocket connection should close normally with the `OK` closure code (`WSCloseCode.OK`) when the client sends a message during the server's shutdown process.

**Actual Behavior:**
Instead of closing with the `OK` code, the connection closes with an `ABNORMAL_CLOSURE` code (`WSCloseCode.ABNORMAL_CLOSURE`) when the client sends a message during the server's shutdown.

[/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 hashlib
import json
import sys
from typing import Any, Final, Iterable, Optional, Tuple, cast

import attr
from multidict import CIMultiDict

from . import hdrs
from ._websocket.writer import DEFAULT_LIMIT
from .abc import AbstractStreamWriter
from .client_exceptions import WSMessageTypeError
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 as WSMsgType,
    ws_ext_gen,
    ws_ext_parse,
)
from .http_websocket import _INTERNAL_RECEIVE_TYPES
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


@attr.s(auto_attribs=True, frozen=True, slots=True)
class WebSocketReady:
    ok: bool
    protocol: Optional[str]

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


class WebSocketResponse(StreamResponse):

    _length_check = False

    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,
        writer_limit: int = DEFAULT_LIMIT,
    ) -> None:
        super().__init__(status=101)
        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
        self._writer_limit = writer_limit

    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(WSMessage(WSMsgType.ERROR, exc, 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,
            limit=self._writer_limit,
        )

        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: WSCloseCode) -> 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: WSCloseCode) -> 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")

        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 WSMessage(WSMsgType.CLOSED, None, None)
            except WebSocketError as exc:
                self._close_code = exc.code
                await self.close(code=exc.code)
                return WSMessage(WSMsgType.ERROR, exc, None)
            except Exception as exc:
                self._exception = exc
                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)
                await self.close()
                return WSMessage(WSMsgType.ERROR, exc, None)

            if msg.type not in _INTERNAL_RECEIVE_TYPES:
                # If its not a close/closing/ping/pong message
                # we can return it immediately
                return msg

            if msg.type is WSMsgType.CLOSE:
                self._set_closing(msg.data)
                # Could be closed while awaiting reader.
                if not self._closed and self._autoclose:
                    # 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 WSMessageTypeError(
                f"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT"
            )
        return cast(str, 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 WSMessageTypeError(
                f"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY"
            )
        return cast(bytes, 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: WebSocket Closes with ABNORMAL_CLOSURE When Client Sends Message During Server Shutdown**

**Description:**
When the server initiates closing a WebSocket connection while the client sends a message, the connection unexpectedly closes with an `ABNORMAL_CLOSURE` code instead of the expected `OK` closure code.

**Example Code:**
```python
async def test_websocket_close_with_pending_message(aiohttp_client: AiohttpClient) -> None:
    close_code: Optional[WSCloseCode] = None

    async def handler(request: web.Request) -> web.WebSocketResponse:
        ws = web.WebSocketResponse(timeout=0.2)
        await ws.prepare(request)
        await ws.close()
        close_code = WSCloseCode(ws.close_code)
        return ws

    app = web.Application()
    app.router.add_route('GET', '/', handler)
    client = await aiohttp_client(app)
    async with client.ws_connect('/', autoclose=False) as ws:
        await asyncio.sleep(0.1)
        await ws.send_str('Hello')
        await ws.close()
    assert close_code == WSCloseCode.OK
```

**Expected Behavior:**
The WebSocket connection should close normally with the `OK` closure code (`WSCloseCode.OK`) when the client sends a message during the server's shutdown process.

**Actual Behavior:**
Instead of closing with the `OK` code, the connection closes with an `ABNORMAL_CLOSURE` code (`WSCloseCode.ABNORMAL_CLOSURE`) when the client sends a message during the server's shutdown.

[/ISSUE]
{
    "test_websocket_can_prepare[pyloop]": "PASSED",
    "test_websocket_json[pyloop]": "PASSED",
    "test_websocket_json_invalid_message[pyloop]": "PASSED",
    "test_websocket_send_json[pyloop]": "PASSED",
    "test_websocket_receive_json[pyloop]": "PASSED",
    "test_send_recv_text[pyloop]": "PASSED",
    "test_send_recv_bytes[pyloop]": "PASSED",
    "test_send_recv_json[pyloop]": "PASSED",
    "test_close_timeout[pyloop]": "PASSED",
    "test_concurrent_close[pyloop]": "PASSED",
    "test_concurrent_close_multiple_tasks[pyloop]": "PASSED",
    "test_close_op_code_from_client[pyloop]": "PASSED",
    "test_auto_pong_with_closing_by_peer[pyloop]": "PASSED",
    "test_ping[pyloop]": "PASSED",
    "test_pong[pyloop]": "PASSED",
    "test_change_status[pyloop]": "PASSED",
    "test_handle_protocol[pyloop]": "PASSED",
    "test_server_close_handshake[pyloop]": "PASSED",
    "test_server_close_handshake_server_eats_client_messages[pyloop]": "PASSED",
    "test_receive_timeout[pyloop]": "PASSED",
    "test_custom_receive_timeout[pyloop]": "PASSED",
    "test_heartbeat[pyloop]": "PASSED",
    "test_heartbeat_no_pong[pyloop]": "PASSED",
    "test_heartbeat_connection_closed[pyloop]": "PASSED",
    "test_heartbeat_failure_ends_receive[pyloop]": "PASSED",
    "test_heartbeat_no_pong_send_many_messages[pyloop]": "PASSED",
    "test_heartbeat_no_pong_receive_many_messages[pyloop]": "PASSED",
    "test_server_ws_async_for[pyloop]": "PASSED",
    "test_closed_async_for[pyloop]": "PASSED",
    "test_websocket_disable_keepalive[pyloop]": "PASSED",
    "test_receive_str_nonstring[pyloop]": "PASSED",
    "test_receive_bytes_nonbytes[pyloop]": "PASSED",
    "test_bug3380[pyloop]": "PASSED",
    "test_receive_being_cancelled_keeps_connection_open[pyloop]": "PASSED",
    "test_receive_timeout_keeps_connection_open[pyloop]": "PASSED",
    "test_websocket_shutdown[pyloop]": "PASSED",
    "test_ws_close_return_code[pyloop]": "PASSED",
    "test_abnormal_closure_when_server_does_not_receive[pyloop]": "PASSED",
    "test_abnormal_closure_when_client_does_not_close[pyloop]": "PASSED",
    "test_normal_closure_while_client_sends_msg[pyloop]": "PASSED"
}
diff --git a/aiohttp/web_ws.py b/aiohttp/web_ws.py
index 932cd0db..bf93e188 100644
--- a/aiohttp/web_ws.py
+++ b/aiohttp/web_ws.py
@@ -473,7 +473,11 @@ class WebSocketResponse(StreamResponse):
 
         try:
             async with async_timeout.timeout(self._timeout):
-                msg = await reader.read()
+                while True:
+                    msg = await reader.read()
+                    if msg.type is WSMsgType.CLOSE:
+                        self._set_code_close_transport(msg.data)
+                        return True
         except asyncio.CancelledError:
             self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
             raise
@@ -482,14 +486,6 @@ class WebSocketResponse(StreamResponse):
             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: WSCloseCode) -> None:
         """Set the close code and mark the connection as closing."""
         self._closing = True

{"aiohttp/web_ws.py": "import asyncio\nimport base64\nimport binascii\nimport hashlib\nimport json\nimport sys\nfrom typing import Any, Final, Iterable, Optional, Tuple, cast\n\nimport attr\nfrom multidict import CIMultiDict\n\nfrom . import hdrs\nfrom ._websocket.writer import DEFAULT_LIMIT\nfrom .abc import AbstractStreamWriter\nfrom .client_exceptions import WSMessageTypeError\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 as WSMsgType,\n    ws_ext_gen,\n    ws_ext_parse,\n)\nfrom .http_websocket import _INTERNAL_RECEIVE_TYPES\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@attr.s(auto_attribs=True, frozen=True, slots=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\n    _length_check = False\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._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(WSMessage(WSMsgType.ERROR, exc, 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,\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: WSCloseCode) -> 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: WSCloseCode) -> 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        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 WSMessage(WSMsgType.CLOSED, None, None)\n            except WebSocketError as exc:\n                self._close_code = exc.code\n                await self.close(code=exc.code)\n                return WSMessage(WSMsgType.ERROR, exc, None)\n            except Exception as exc:\n                self._exception = exc\n                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)\n                await self.close()\n                return WSMessage(WSMsgType.ERROR, exc, None)\n\n            if msg.type not in _INTERNAL_RECEIVE_TYPES:\n                # If its not a close/closing/ping/pong message\n                # we can return it immediately\n                return msg\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:\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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT\"\n            )\n        return cast(str, 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 WSMessageTypeError(\n                f\"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY\"\n            )\n        return cast(bytes, 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: WebSocket Closes with ABNORMAL_CLOSURE When Client Sends Message During Server Shutdown**

**Description:**
When the server initiates closing a WebSocket connection while the client sends a message, the connection unexpectedly closes with an `ABNORMAL_CLOSURE` code instead of the expected `OK` closure code.

**Example Code:**
```python
async def test_websocket_close_with_pending_message(aiohttp_client: AiohttpClient) -> None:
    close_code: Optional[WSCloseCode] = None

    async def handler(request: web.Request) -> web.WebSocketResponse:
        ws = web.WebSocketResponse(timeout=0.2)
        await ws.prepare(request)
        await ws.close()
        close_code = WSCloseCode(ws.close_code)
        return ws

    app = web.Application()
    app.router.add_route('GET', '/', handler)
    client = await aiohttp_client(app)
    async with client.ws_connect('/', autoclose=False) as ws:
        await asyncio.sleep(0.1)
        await ws.send_str('Hello')
        await ws.close()
    assert close_code == WSCloseCode.OK
```

**Expected Behavior:**
The WebSocket connection should close normally with the `OK` closure code (`WSCloseCode.OK`) when the client sends a message during the server's shutdown process.

**Actual Behavior:**
Instead of closing with the `OK` code, the connection closes with an `ABNORMAL_CLOSURE` code (`WSCloseCode.ABNORMAL_CLOSURE`) when the client sends a message during the server's shutdown.

[/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 hashlib
import json
import sys
from typing import Any, Final, Iterable, Optional, Tuple, cast

import attr
from multidict import CIMultiDict

from . import hdrs
from ._websocket.writer import DEFAULT_LIMIT
from .abc import AbstractStreamWriter
from .client_exceptions import WSMessageTypeError
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 as WSMsgType,
    ws_ext_gen,
    ws_ext_parse,
)
from .http_websocket import _INTERNAL_RECEIVE_TYPES
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


@attr.s(auto_attribs=True, frozen=True, slots=True)
class WebSocketReady:
    ok: bool
    protocol: Optional[str]

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


class WebSocketResponse(StreamResponse):

    _length_check = False

    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,
        writer_limit: int = DEFAULT_LIMIT,
    ) -> None:
        super().__init__(status=101)
        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
        self._writer_limit = writer_limit

    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(WSMessage(WSMsgType.ERROR, exc, 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,
            limit=self._writer_limit,
        )

        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: WSCloseCode) -> 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: WSCloseCode) -> 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")

        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 WSMessage(WSMsgType.CLOSED, None, None)
            except WebSocketError as exc:
                self._close_code = exc.code
                await self.close(code=exc.code)
                return WSMessage(WSMsgType.ERROR, exc, None)
            except Exception as exc:
                self._exception = exc
                self._set_closing(WSCloseCode.ABNORMAL_CLOSURE)
                await self.close()
                return WSMessage(WSMsgType.ERROR, exc, None)

            if msg.type not in _INTERNAL_RECEIVE_TYPES:
                # If its not a close/closing/ping/pong message
                # we can return it immediately
                return msg

            if msg.type is WSMsgType.CLOSE:
                self._set_closing(msg.data)
                # Could be closed while awaiting reader.
                if not self._closed and self._autoclose:
                    # 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 WSMessageTypeError(
                f"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT"
            )
        return cast(str, 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 WSMessageTypeError(
                f"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY"
            )
        return cast(bytes, 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