Skip to content

Commit 130ca4d

Browse files
authored
[PR #9679/3f2f4a7 backport][3.11] Return early in WebSocket receive if there is no processing to do (#9683)
1 parent f769cb3 commit 130ca4d

File tree

4 files changed

+19
-1
lines changed

4 files changed

+19
-1
lines changed

CHANGES/9679.misc.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improved performance of calling ``receive`` for WebSockets for the most common message types -- by :user:`bdraco`.

aiohttp/client_ws.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
WSMessage,
1919
WSMsgType,
2020
)
21-
from .http_websocket import WebSocketWriter # WSMessage
21+
from .http_websocket import _INTERNAL_RECEIVE_TYPES, WebSocketWriter
2222
from .streams import EofStream, FlowControlDataQueue
2323
from .typedefs import (
2424
DEFAULT_JSON_DECODER,
@@ -359,6 +359,11 @@ async def receive(self, timeout: Optional[float] = None) -> WSMessage:
359359
await self.close()
360360
return WSMessage(WSMsgType.ERROR, exc, None)
361361

362+
if msg.type not in _INTERNAL_RECEIVE_TYPES:
363+
# If its not a close/closing/ping/pong message
364+
# we can return it immediately
365+
return msg
366+
362367
if msg.type is WSMsgType.CLOSE:
363368
self._set_closing()
364369
self._close_code = msg.data

aiohttp/http_websocket.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@
1313
from ._websocket.reader import WebSocketReader
1414
from ._websocket.writer import WebSocketWriter
1515

16+
# Messages that the WebSocketResponse.receive needs to handle internally
17+
_INTERNAL_RECEIVE_TYPES = frozenset(
18+
(WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.PING, WSMsgType.PONG)
19+
)
20+
21+
1622
__all__ = (
1723
"WS_CLOSED_MESSAGE",
1824
"WS_CLOSING_MESSAGE",

aiohttp/web_ws.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
ws_ext_gen,
2828
ws_ext_parse,
2929
)
30+
from .http_websocket import _INTERNAL_RECEIVE_TYPES
3031
from .log import ws_logger
3132
from .streams import EofStream, FlowControlDataQueue
3233
from .typedefs import JSONDecoder, JSONEncoder
@@ -555,6 +556,11 @@ async def receive(self, timeout: Optional[float] = None) -> WSMessage:
555556
await self.close()
556557
return WSMessage(WSMsgType.ERROR, exc, None)
557558

559+
if msg.type not in _INTERNAL_RECEIVE_TYPES:
560+
# If its not a close/closing/ping/pong message
561+
# we can return it immediately
562+
return msg
563+
558564
if msg.type is WSMsgType.CLOSE:
559565
self._set_closing(msg.data)
560566
# Could be closed while awaiting reader.

0 commit comments

Comments
 (0)