Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance of generating random WebSocket mask #8667

Merged
merged 3 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -94,6 +95,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 @@ -596,7 +598,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)
bdraco marked this conversation as resolved.
Show resolved Hide resolved
self.compress = compress
self.notakeover = notakeover
self._closing = False
Expand Down Expand Up @@ -652,8 +654,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())
bdraco marked this conversation as resolved.
Show resolved Hide resolved
message = bytearray(message)
_websocket_mask(mask, message)
self._write(header + mask + message)
Expand Down
Loading