Skip to content

Commit

Permalink
[PR #8667/406cd2c7 backport][3.10] Improve performance of generating …
Browse files Browse the repository at this point in the history
…random WebSocket mask (#8668)

Co-authored-by: J. Nick Koston <nick@koston.org>
  • Loading branch information
patchback[bot] and bdraco authored Aug 9, 2024
1 parent b4ad882 commit dbcdb16
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGES/8667.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved performance of generating random WebSocket mask -- by :user:`bdraco`.
7 changes: 4 additions & 3 deletions aiohttp/http_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import sys
import zlib
from enum import IntEnum
from functools import partial
from struct import Struct
from typing import (
Any,
Expand Down Expand Up @@ -103,6 +104,7 @@ class WSMsgType(IntEnum):
PACK_LEN2 = Struct("!BBH").pack
PACK_LEN3 = Struct("!BBQ").pack
PACK_CLOSE_CODE = Struct("!H").pack
PACK_RANDBITS = Struct("!L").pack
MSG_SIZE: Final[int] = 2**14
DEFAULT_LIMIT: Final[int] = 2**16

Expand Down Expand Up @@ -612,7 +614,7 @@ def __init__(
self.protocol = protocol
self.transport = transport
self.use_mask = use_mask
self.randrange = random.randrange
self.get_random_bits = partial(random.getrandbits, 32)
self.compress = compress
self.notakeover = notakeover
self._closing = False
Expand Down Expand Up @@ -668,8 +670,7 @@ async def _send_frame(
else:
header = PACK_LEN3(0x80 | rsv | opcode, 127 | mask_bit, msg_length)
if use_mask:
mask_int = self.randrange(0, 0xFFFFFFFF)
mask = mask_int.to_bytes(4, "big")
mask = PACK_RANDBITS(self.get_random_bits())
message = bytearray(message)
_websocket_mask(mask, message)
self._write(header + mask + message)
Expand Down

0 comments on commit dbcdb16

Please sign in to comment.