| 1 |
""" |
| 2 |
WebSocket - `RFC 6455 <https://www.rfc-editor.org/rfc/rfc6455>`_ |
| 3 |
|
| 4 |
Use the :func:`connect()` to establish a :class:`WebSocket` client connection. |
| 5 |
|
| 6 |
Note from the developer: This is a very low-level API, which forces the |
| 7 |
user to deal with things like data fragmentation. |
| 8 |
A higher-level API could easily be built on top of this. |
| 9 |
|
| 10 |
.. _authoring-callbacks: |
| 11 |
|
| 12 |
Authoring Callbacks |
| 13 |
------------------- |
| 14 |
All network operations in `awscrt.websocket` are asynchronous. |
| 15 |
Callbacks are always invoked on the WebSocket's networking thread. |
| 16 |
You MUST NOT perform blocking network operations from any callback, or you will cause a deadlock. |
| 17 |
For example: do not send a frame, and then wait for that frame to complete, |
| 18 |
within a callback. The WebSocket cannot do work until your callback returns, |
| 19 |
so the thread will be stuck. You can send the frame from within the callback, |
| 20 |
just don't wait for it to complete within the callback. |
| 21 |
|
| 22 |
If you want to do blocking waits, do it from a thread you control, like the main thread. |
| 23 |
It's fine for the main thread to send a frame, and wait until it completes. |
| 24 |
|
| 25 |
All functions and methods in `awscrt.websocket` are thread-safe. |
| 26 |
They can be called from any mix of threads. |
| 27 |
|
| 28 |
.. _flow-control-reading: |
| 29 |
|
| 30 |
Flow Control (reading) |
| 31 |
---------------------- |
| 32 |
By default, the WebSocket will read from the network as fast as it can hand you the data. |
| 33 |
You must prevent the WebSocket from reading data faster than you can process it, |
| 34 |
or memory usage could balloon until your application explodes. |
| 35 |
|
| 36 |
There are two ways to manage this. |
| 37 |
|
| 38 |
First, and simplest, is to process incoming data synchronously within the |
| 39 |
`on_incoming_frame` callbacks. Since callbacks are invoked on the WebSocket's |
| 40 |
networking thread, the WebSocket cannot read more data until the callback returns. |
| 41 |
Therefore, processing the data in a synchronous manner |
| 42 |
(i.e. writing to disk, printing to screen, etc) will naturally |
| 43 |
affect `TCP flow control <https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Flow_control>`_, |
| 44 |
and prevent data from arriving too fast. However, you MUST NOT perform a blocking |
| 45 |
network operation from within the callback or you risk deadlock (see :ref:`authoring-callbacks`). |
| 46 |
|
| 47 |
The second, more complex, way requires you to manage the size of the read window. |
| 48 |
Do this if you are processing the data asynchronously |
| 49 |
(i.e. sending the data along on another network connection). |
| 50 |
Create the WebSocket with `manage_read_window` set true, |
| 51 |
and set `initial_read_window` to the number of bytes you are ready to receive right away. |
| 52 |
Whenever the read window reaches 0, you will stop receiving anything. |
| 53 |
The read window shrinks as you receive the payload from "data" frames (TEXT, BINARY, CONTINUATION). |
| 54 |
Call :meth:`WebSocket.increment_read_window()` to increase the window again keep frames flowing in. |
| 55 |
You only need to worry about the payload from "data" frames. |
| 56 |
The WebSocket automatically increments its window to account for any |
| 57 |
other incoming bytes, including other parts of a frame (opcode, payload-length, etc) |
| 58 |
and the payload of other frame types (PING, PONG, CLOSE). |
| 59 |
You'll probably want to do it like this: |
| 60 |
Pick the max amount of memory to buffer, and set this as the `initial_read_window`. |
| 61 |
When data arrives, the window has shrunk by that amount. |
| 62 |
Send this data along on the other network connection. |
| 63 |
When that data is done sending, call `increment_read_window()` |
| 64 |
by the amount you just finished sending. |
| 65 |
If you don't want to receive any data at first, set the `initial_read_window` to 0, |
| 66 |
and `increment_read_window()` when you're ready. |
| 67 |
Maintaining a larger window is better for overall throughput. |
| 68 |
|
| 69 |
.. _flow-control-writing: |
| 70 |
|
| 71 |
Flow Control (writing) |
| 72 |
---------------------- |
| 73 |
You must also ensure that you do not continually send frames faster than the other |
| 74 |
side can read them, or memory usage could balloon until your application explodes. |
| 75 |
|
| 76 |
The simplest approach is to only send 1 frame at a time. |
| 77 |
Use the :meth:`WebSocket.send_frame()` `on_complete` callback to know when the send is complete. |
| 78 |
Then you can try and send another. |
| 79 |
|
| 80 |
A more complex, but higher throughput, way is to let multiple frames be in flight |
| 81 |
but have a cap. If the number of frames in flight, or bytes in flight, reaches |
| 82 |
your cap then wait until some frames complete before trying to send more. |
| 83 |
|
| 84 |
.. _api: |
| 85 |
|
| 86 |
API |
| 87 |
--- |
| 88 |
""" |
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
import _awscrt |
| 93 |
from awscrt import NativeResource |
| 94 |
import awscrt.exceptions |
| 95 |
from awscrt.http import HttpProxyOptions, HttpRequest |
| 96 |
from awscrt.io import ClientBootstrap, TlsConnectionOptions, SocketOptions |
| 97 |
from dataclasses import dataclass |
| 98 |
from enum import IntEnum |
| 99 |
import sys |
| 100 |
from typing import Callable, Optional, Sequence, Tuple, Union |
| 101 |
|
| 102 |
|
| 103 |
class Opcode(IntEnum): |
| 104 |
"""An opcode defines a frame's type. |
| 105 |
|
| 106 |
RFC 6455 classifies TEXT and BINARY as `data frames <https://www.rfc-editor.org/rfc/rfc6455#section-5.6>`_. |
| 107 |
A CONTINUATION frame "continues" the most recent data frame. |
| 108 |
All other opcodes are for `control frames <https://www.rfc-editor.org/rfc/rfc6455#section-5.5>`_. |
| 109 |
""" |
| 110 |
|
| 111 |
CONTINUATION = 0x0, |
| 112 |
"""Continues the most recent TEXT or BINARY data frame. |
| 113 |
|
| 114 |
See `RFC 6455 section 5.4 - Fragmentation <https://www.rfc-editor.org/rfc/rfc6455#section-5.4>`_. |
| 115 |
""" |
| 116 |
|
| 117 |
TEXT = 0x1 |
| 118 |
"""The data frame for sending text. |
| 119 |
|
| 120 |
The payload must contain UTF-8.""" |
| 121 |
|
| 122 |
BINARY = 0x2 |
| 123 |
"""The data frame for sending binary.""" |
| 124 |
|
| 125 |
CLOSE = 0x8 |
| 126 |
"""The control frame which is the final frame sent by an endpoint. |
| 127 |
|
| 128 |
The CLOSE frame may include a payload, but its format is very particular. |
| 129 |
See `RFC 6455 section 5.5.1 <https://www.rfc-editor.org/rfc/rfc6455#section-5.5.1>`_. |
| 130 |
""" |
| 131 |
|
| 132 |
PING = 0x9 |
| 133 |
"""A control frame that may serve as either a keepalive or as a means to verify |
| 134 |
that the remote endpoint is still responsive. |
| 135 |
|
| 136 |
DO NOT manually send a PONG frame in response to a PING, |
| 137 |
the implementation does this automatically. |
| 138 |
|
| 139 |
A PING frame may include a payload. |
| 140 |
See `RFC 6455 section 5.5.2 <https://www.rfc-editor.org/rfc/rfc6455#section-5.5.2>`_. |
| 141 |
""" |
| 142 |
|
| 143 |
PONG = 0xA |
| 144 |
"""The control frame that is the response to a PING frame. |
| 145 |
|
| 146 |
DO NOT manually send a PONG frame in response to a PING, |
| 147 |
the implementation does this automatically. |
| 148 |
|
| 149 |
See `RFC 6455 section 5.5.3 <https://www.rfc-editor.org/rfc/rfc6455#section-5.5.3>`_. |
| 150 |
""" |
| 151 |
|
| 152 |
def is_data_frame(self): |
| 153 |
"""True if this is a "data frame" opcode. |
| 154 |
|
| 155 |
TEXT, BINARY, and CONTINUATION are "data frames". The rest are "control" frames. |
| 156 |
|
| 157 |
If the WebSocket was created with `manage_read_window`, |
| 158 |
then the read window shrinks as "data frames" are received. |
| 159 |
See :ref:`flow-control-reading` for a thorough explanation. |
| 160 |
""" |
| 161 |
return self.value in (Opcode.TEXT, Opcode.BINARY, Opcode.CONTINUATION) |
| 162 |
|
| 163 |
|
| 164 |
MAX_PAYLOAD_LENGTH = 0x7FFFFFFFFFFFFFFF |
| 165 |
"""The maximum frame payload length allowed by RFC 6455""" |
| 166 |
|
| 167 |
|
| 168 |
@dataclass |
| 169 |
class OnConnectionSetupData: |
| 170 |
"""Data passed to the `on_connection_setup` callback""" |
| 171 |
|
| 172 |
exception: Optional[Exception] = None |
| 173 |
"""If the connection failed, this exception explains why. |
| 174 |
|
| 175 |
This is None if the connection succeeded.""" |
| 176 |
|
| 177 |
websocket: Optional['WebSocket'] = None |
| 178 |
"""If the connection succeeded, here's the WebSocket. |
| 179 |
|
| 180 |
You should store this WebSocket somewhere |
| 181 |
(the connection will shut down if the class is garbage collected). |
| 182 |
|
| 183 |
This is None if the connection failed. |
| 184 |
""" |
| 185 |
|
| 186 |
handshake_response_status: Optional[int] = None |
| 187 |
"""The HTTP response status-code, if you're interested. |
| 188 |
|
| 189 |
This is present if an HTTP response was received, regardless of whether |
| 190 |
the handshake was accepted or rejected. This always has the value 101 |
| 191 |
for successful connections. |
| 192 |
|
| 193 |
This is None if the connection failed before receiving an HTTP response. |
| 194 |
""" |
| 195 |
|
| 196 |
handshake_response_headers: Optional[Sequence[Tuple[str, str]]] = None |
| 197 |
"""The HTTP response headers, if you're interested. |
| 198 |
|
| 199 |
These are present if an HTTP response was received, regardless of whether |
| 200 |
the handshake was accepted or rejected. |
| 201 |
|
| 202 |
This is None if the connection failed before receiving an HTTP response. |
| 203 |
""" |
| 204 |
|
| 205 |
handshake_response_body: bytes = None |
| 206 |
"""The HTTP response body, if you're interested. |
| 207 |
|
| 208 |
This is only present if the server sent a full HTTP response rejecting the handshake. |
| 209 |
It is not present if the connection succeeded, |
| 210 |
or the connection failed for other reasons. |
| 211 |
""" |
| 212 |
|
| 213 |
|
| 214 |
@dataclass |
| 215 |
class OnConnectionShutdownData: |
| 216 |
"""Data passed to the `on_connection_shutdown` callback""" |
| 217 |
|
| 218 |
exception: Optional[Exception] = None |
| 219 |
"""If the connection shut down cleanly, this is None. |
| 220 |
|
| 221 |
If the connection shut down due to error, or an error occurs while |
| 222 |
shutting down, this exception explains why.""" |
| 223 |
|
| 224 |
|
| 225 |
@dataclass |
| 226 |
class IncomingFrame: |
| 227 |
"""Describes the frame you are receiving. |
| 228 |
|
| 229 |
Used in `on_incoming_frame` callbacks """ |
| 230 |
|
| 231 |
opcode: Opcode |
| 232 |
"""This frame's opcode.""" |
| 233 |
|
| 234 |
payload_length: int |
| 235 |
"""This frame's payload length (in bytes).""" |
| 236 |
|
| 237 |
fin: bool |
| 238 |
"""The FIN bit indicates whether this is the final fragment in a message. |
| 239 |
|
| 240 |
See `RFC 6455 section 5.4 - Fragmentation <https://www.rfc-editor.org/rfc/rfc6455#section-5.4>`_""" |
| 241 |
|
| 242 |
def is_data_frame(self): |
| 243 |
"""True if this is a "data frame". |
| 244 |
|
| 245 |
TEXT, BINARY, and CONTINUATION are "data frames". The rest are "control frames". |
| 246 |
|
| 247 |
If the WebSocket was created with `manage_read_window`, |
| 248 |
then the read window shrinks as "data frames" are received. |
| 249 |
See :ref:`flow-control-reading` for a thorough explanation. |
| 250 |
""" |
| 251 |
return self.opcode.is_data_frame() |
| 252 |
|
| 253 |
|
| 254 |
@dataclass |
| 255 |
class OnIncomingFrameBeginData: |
| 256 |
"""Data passed to the `on_incoming_frame_begin` callback. |
| 257 |
|
| 258 |
Each `on_incoming_frame_begin` call will be followed by |
| 259 |
0+ `on_incoming_frame_payload` calls, |
| 260 |
followed by one `on_incoming_frame_complete` call.""" |
| 261 |
|
| 262 |
frame: IncomingFrame |
| 263 |
"""Describes the frame you are starting to receive.""" |
| 264 |
|
| 265 |
|
| 266 |
@dataclass |
| 267 |
class OnIncomingFramePayloadData: |
| 268 |
"""Data passed to the `on_incoming_frame_payload` callback. |
| 269 |
|
| 270 |
This callback will be invoked 0+ times. |
| 271 |
Each time, `data` will contain a bit more of the payload. |
| 272 |
Once all `frame.payload_length` bytes have been received |
| 273 |
(or the network connection is lost), the `on_incoming_frame_complete` |
| 274 |
callback will be invoked. |
| 275 |
|
| 276 |
If the WebSocket was created with `manage_read_window`, |
| 277 |
and this is a "data frame" (TEXT, BINARY, CONTINUATION), |
| 278 |
then the read window shrinks by `len(data)`. |
| 279 |
See :ref:`flow-control-reading` for a thorough explanation. |
| 280 |
""" |
| 281 |
|
| 282 |
frame: IncomingFrame |
| 283 |
"""Describes the frame whose payload you are receiving.""" |
| 284 |
|
| 285 |
data: bytes |
| 286 |
"""The next chunk of this frame's payload.""" |
| 287 |
|
| 288 |
|
| 289 |
@dataclass |
| 290 |
class OnIncomingFrameCompleteData: |
| 291 |
"""Data passed to the `on_incoming_frame_complete` callback.""" |
| 292 |
|
| 293 |
frame: IncomingFrame |
| 294 |
"""Describes the frame you are done receiving.""" |
| 295 |
|
| 296 |
exception: Optional[Exception] = None |
| 297 |
"""If `exception` is set, then something went wrong processing the frame |
| 298 |
or the connection was lost before the frame was fully received.""" |
| 299 |
|
| 300 |
|
| 301 |
@dataclass |
| 302 |
class OnSendFrameCompleteData: |
| 303 |
"""Data passed to the :meth:`WebSocket.send_frame()` `on_complete` callback.""" |
| 304 |
|
| 305 |
exception: Optional[Exception] = None |
| 306 |
"""If `exception` is set, the connection was lost before this frame could be completely sent. |
| 307 |
|
| 308 |
If `exception` is None, the frame was successfully written to the OS socket. |
| 309 |
Note that this data may still be buffered in the OS, it has |
| 310 |
not necessarily left this machine or reached the other endpoint yet.""" |
| 311 |
|
| 312 |
|
| 313 |
class WebSocket(NativeResource): |
| 314 |
"""A WebSocket connection. |
| 315 |
|
| 316 |
Use :meth:`connect()` to establish a new client connection. |
| 317 |
""" |
| 318 |
|
| 319 |
def __init__(self, binding): |
| 320 |
|
| 321 |
super().__init__() |
| 322 |
self._binding = binding |
| 323 |
|
| 324 |
def close(self): |
| 325 |
"""Close the WebSocket asynchronously. |
| 326 |
|
| 327 |
You should call this when you are done with a healthy WebSocket, |
| 328 |
to ensure that it shuts down and cleans up. |
| 329 |
You don't need to call this on a WebSocket that has already shut |
| 330 |
down, or is in the middle of shutting down, but it is safe to do so. |
| 331 |
This function is idempotent. |
| 332 |
|
| 333 |
To determine when shutdown has completed, you can use the |
| 334 |
`on_shutdown_complete` callback (passed into :meth:`connect()`). |
| 335 |
""" |
| 336 |
_awscrt.websocket_close(self._binding) |
| 337 |
|
| 338 |
def send_frame( |
| 339 |
self, |
| 340 |
opcode: Opcode, |
| 341 |
payload: Optional[Union[str, bytes, bytearray, memoryview]] = None, |
| 342 |
*, |
| 343 |
fin: bool = True, |
| 344 |
on_complete: Optional[Callable[[OnSendFrameCompleteData], None]] = None, |
| 345 |
): |
| 346 |
"""Send a WebSocket frame asynchronously. |
| 347 |
|
| 348 |
See `RFC 6455 section 5 - Data Framing <https://www.rfc-editor.org/rfc/rfc6455#section-5>`_ |
| 349 |
for details on all frame types. |
| 350 |
|
| 351 |
This is a low-level API, which requires you to send the appropriate payload for each type of opcode. |
| 352 |
If you are not an expert, stick to sending :attr:`Opcode.TEXT` or :attr:`Opcode.BINARY` frames, |
| 353 |
and don't touch the FIN bit. |
| 354 |
|
| 355 |
See :ref:`flow-control-writing` to learn about limiting the amount of |
| 356 |
unsent data buffered in memory. |
| 357 |
|
| 358 |
Args: |
| 359 |
opcode: :class:`Opcode` for this frame. |
| 360 |
|
| 361 |
payload: Any `bytes-like object <https://docs.python.org/3/glossary.html#term-bytes-like-object>`_. |
| 362 |
`str` will always be encoded as UTF-8. It is fine to pass a `str` for a BINARY frame. |
| 363 |
None will result in an empty payload, the same as passing empty `bytes()` |
| 364 |
|
| 365 |
fin: The FIN bit indicates that this is the final fragment in a message. |
| 366 |
Do not set this False unless you understand |
| 367 |
`WebSocket fragmentation <https://www.rfc-editor.org/rfc/rfc6455#section-5.4>`_ |
| 368 |
|
| 369 |
on_complete: Optional callback, invoked when the frame has finished sending. |
| 370 |
Takes a single :class:`OnSendFrameCompleteData` argument. |
| 371 |
|
| 372 |
If :attr:`OnSendFrameCompleteData.exception` is set, the connection |
| 373 |
was lost before this frame could be completely sent. |
| 374 |
|
| 375 |
But if `exception` is None, the frame was successfully written to the OS socket. |
| 376 |
(This doesn't mean the other endpoint has received the data yet, |
| 377 |
or even guarantee that the data has left the machine yet, |
| 378 |
but it's on track to get there). |
| 379 |
|
| 380 |
Be sure to read about :ref:`authoring-callbacks`. |
| 381 |
""" |
| 382 |
def _on_complete(error_code): |
| 383 |
cbdata = OnSendFrameCompleteData() |
| 384 |
if error_code: |
| 385 |
cbdata.exception = awscrt.exceptions.from_code(error_code) |
| 386 |
|
| 387 |
|
| 388 |
try: |
| 389 |
if on_complete is not None: |
| 390 |
on_complete(cbdata) |
| 391 |
except BaseException: |
| 392 |
print("Exception in WebSocket.send_frame on_complete callback", file=sys.stderr) |
| 393 |
sys.excepthook(*sys.exc_info()) |
| 394 |
self.close() |
| 395 |
|
| 396 |
_awscrt.websocket_send_frame( |
| 397 |
self._binding, |
| 398 |
Opcode(opcode), |
| 399 |
payload, |
| 400 |
fin, |
| 401 |
_on_complete) |
| 402 |
|
| 403 |
def increment_read_window(self, size: int): |
| 404 |
"""Manually increment the read window by this many bytes, to continue receiving frames. |
| 405 |
|
| 406 |
See :ref:`flow-control-reading` for a thorough explanation. |
| 407 |
If the WebSocket was created without `manage_read_window`, this function does nothing. |
| 408 |
This function may be called from any thread. |
| 409 |
|
| 410 |
Args: |
| 411 |
size: in bytes |
| 412 |
""" |
| 413 |
if size < 0: |
| 414 |
raise ValueError("Increment size cannot be negative") |
| 415 |
|
| 416 |
_awscrt.websocket_increment_read_window(self._binding, size) |
| 417 |
|
| 418 |
|
| 419 |
class _WebSocketCore(NativeResource): |
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
def __init__(self, |
| 427 |
on_connection_setup, |
| 428 |
on_connection_shutdown, |
| 429 |
on_incoming_frame_begin, |
| 430 |
on_incoming_frame_payload, |
| 431 |
on_incoming_frame_complete): |
| 432 |
super().__init__() |
| 433 |
self._on_connection_setup_cb = on_connection_setup |
| 434 |
self._on_connection_shutdown_cb = on_connection_shutdown |
| 435 |
self._on_incoming_frame_begin_cb = on_incoming_frame_begin |
| 436 |
self._on_incoming_frame_payload_cb = on_incoming_frame_payload |
| 437 |
self._on_incoming_frame_complete_cb = on_incoming_frame_complete |
| 438 |
|
| 439 |
def _on_connection_setup( |
| 440 |
self, |
| 441 |
error_code, |
| 442 |
websocket_binding, |
| 443 |
handshake_response_status, |
| 444 |
handshake_response_headers, |
| 445 |
handshake_response_body): |
| 446 |
|
| 447 |
cbdata = OnConnectionSetupData() |
| 448 |
if error_code: |
| 449 |
cbdata.exception = awscrt.exceptions.from_code(error_code) |
| 450 |
else: |
| 451 |
cbdata.websocket = WebSocket(websocket_binding) |
| 452 |
|
| 453 |
cbdata.handshake_response_status = handshake_response_status |
| 454 |
cbdata.handshake_response_headers = handshake_response_headers |
| 455 |
cbdata.handshake_response_body = handshake_response_body |
| 456 |
|
| 457 |
|
| 458 |
try: |
| 459 |
self._on_connection_setup_cb(cbdata) |
| 460 |
except BaseException: |
| 461 |
print("Exception in WebSocket on_connection_setup callback", file=sys.stderr) |
| 462 |
sys.excepthook(*sys.exc_info()) |
| 463 |
if cbdata.websocket is not None: |
| 464 |
cbdata.websocket.close() |
| 465 |
|
| 466 |
def _on_connection_shutdown(self, error_code): |
| 467 |
cbdata = OnConnectionShutdownData() |
| 468 |
if error_code: |
| 469 |
cbdata.exception = awscrt.exceptions.from_code(error_code) |
| 470 |
|
| 471 |
|
| 472 |
try: |
| 473 |
if self._on_connection_shutdown_cb is not None: |
| 474 |
self._on_connection_shutdown_cb(cbdata) |
| 475 |
except BaseException: |
| 476 |
print("Exception in WebSocket on_connection_shutdown callback", file=sys.stderr) |
| 477 |
sys.excepthook(*sys.exc_info()) |
| 478 |
|
| 479 |
def _on_incoming_frame_begin(self, opcode_int, payload_length, fin): |
| 480 |
self._current_incoming_frame = IncomingFrame(Opcode(opcode_int), payload_length, fin) |
| 481 |
|
| 482 |
cbdata = OnIncomingFrameBeginData(self._current_incoming_frame) |
| 483 |
|
| 484 |
|
| 485 |
try: |
| 486 |
if self._on_incoming_frame_begin_cb is not None: |
| 487 |
self._on_incoming_frame_begin_cb(cbdata) |
| 488 |
except BaseException: |
| 489 |
print("Exception in WebSocket on_incoming_frame_begin callback", file=sys.stderr) |
| 490 |
sys.excepthook(*sys.exc_info()) |
| 491 |
return False |
| 492 |
|
| 493 |
return True |
| 494 |
|
| 495 |
def _on_incoming_frame_payload(self, data): |
| 496 |
cbdata = OnIncomingFramePayloadData(self._current_incoming_frame, data) |
| 497 |
|
| 498 |
|
| 499 |
try: |
| 500 |
if self._on_incoming_frame_payload_cb is not None: |
| 501 |
self._on_incoming_frame_payload_cb(cbdata) |
| 502 |
except BaseException: |
| 503 |
print("Exception in WebSocket on_incoming_frame_payload callback", file=sys.stderr) |
| 504 |
sys.excepthook(*sys.exc_info()) |
| 505 |
return False |
| 506 |
|
| 507 |
return True |
| 508 |
|
| 509 |
def _on_incoming_frame_complete(self, error_code): |
| 510 |
cbdata = OnIncomingFrameCompleteData(self._current_incoming_frame) |
| 511 |
if error_code: |
| 512 |
cbdata.exception = awscrt.exceptions.from_code(error_code) |
| 513 |
|
| 514 |
del self._current_incoming_frame |
| 515 |
|
| 516 |
|
| 517 |
try: |
| 518 |
if self._on_incoming_frame_complete_cb is not None: |
| 519 |
self._on_incoming_frame_complete_cb(cbdata) |
| 520 |
except BaseException: |
| 521 |
print("Exception in WebSocket on_incoming_frame_complete callback", file=sys.stderr) |
| 522 |
sys.excepthook(*sys.exc_info()) |
| 523 |
return False |
| 524 |
|
| 525 |
return True |
| 526 |
|
| 527 |
|
| 528 |
def connect( |
| 529 |
*, |
| 530 |
host: str, |
| 531 |
port: Optional[int] = None, |
| 532 |
handshake_request: HttpRequest, |
| 533 |
bootstrap: Optional[ClientBootstrap] = None, |
| 534 |
socket_options: Optional[SocketOptions] = None, |
| 535 |
tls_connection_options: Optional[TlsConnectionOptions] = None, |
| 536 |
proxy_options: Optional[HttpProxyOptions] = None, |
| 537 |
manage_read_window: bool = False, |
| 538 |
initial_read_window: Optional[int] = None, |
| 539 |
on_connection_setup: Callable[[OnConnectionSetupData], None], |
| 540 |
on_connection_shutdown: Optional[Callable[[OnConnectionShutdownData], None]] = None, |
| 541 |
on_incoming_frame_begin: Optional[Callable[[OnIncomingFrameBeginData], None]] = None, |
| 542 |
on_incoming_frame_payload: Optional[Callable[[OnIncomingFramePayloadData], None]] = None, |
| 543 |
on_incoming_frame_complete: Optional[Callable[[OnIncomingFrameCompleteData], None]] = None, |
| 544 |
): |
| 545 |
"""Asynchronously establish a client WebSocket connection. |
| 546 |
|
| 547 |
The `on_connection_setup` callback is invoked once the connection |
| 548 |
has succeeded or failed. |
| 549 |
|
| 550 |
If successful, a :class:`WebSocket` will be provided in the |
| 551 |
:class:`OnConnectionSetupData`. You should store this WebSocket somewhere, |
| 552 |
so that you can continue using it (the connection will shut down |
| 553 |
if the class is garbage collected). |
| 554 |
|
| 555 |
The WebSocket will shut down after one of these things occur: |
| 556 |
* You call :meth:`WebSocket.close()` |
| 557 |
* You, or the server, sends a CLOSE frame. |
| 558 |
* The underlying socket shuts down. |
| 559 |
* All references to the WebSocket are dropped, |
| 560 |
causing it to be garbage collected. However, you should NOT |
| 561 |
rely on this behavior. You should call :meth:`~WebSocket.close()` when you are |
| 562 |
done with a healthy WebSocket, to ensure that it shuts down and cleans up. |
| 563 |
It is very easy to accidentally keep a reference around without realizing it. |
| 564 |
|
| 565 |
Be sure to read about :ref:`authoring-callbacks`. |
| 566 |
|
| 567 |
Args: |
| 568 |
host: Hostname to connect to. |
| 569 |
|
| 570 |
port: Port to connect to. If not specified, it defaults to port 443 |
| 571 |
when `tls_connection_options` is present, and port 80 otherwise. |
| 572 |
|
| 573 |
handshake_request: HTTP request for the initial WebSocket handshake. |
| 574 |
|
| 575 |
The request's method MUST be "GET", and the following headers are |
| 576 |
required:: |
| 577 |
|
| 578 |
Host: <host> |
| 579 |
Upgrade: websocket |
| 580 |
Connection: Upgrade |
| 581 |
Sec-WebSocket-Key: <base64-encoding of 16 random bytes> |
| 582 |
Sec-WebSocket-Version: 13 |
| 583 |
|
| 584 |
You can use :meth:`create_handshake_request()` to make a valid WebSocket |
| 585 |
handshake request, modifying the path and headers to fit your needs, |
| 586 |
and then passing it here. |
| 587 |
|
| 588 |
bootstrap: Client bootstrap to use when initiating socket connection. |
| 589 |
If not specified, the default singleton is used. |
| 590 |
|
| 591 |
socket_options: Socket options. |
| 592 |
If not specified, default options are used. |
| 593 |
|
| 594 |
proxy_options: HTTP Proxy options. |
| 595 |
If not specified, no proxy is used. |
| 596 |
|
| 597 |
manage_read_window: Set true to manually manage the flow-control read window. |
| 598 |
If false (the default), data arrives as fast as possible. |
| 599 |
See :ref:`flow-control-reading` for a thorough explanation. |
| 600 |
|
| 601 |
initial_read_window: The initial size of the read window, in bytes. |
| 602 |
This must be set if `manage_read_window` is true, |
| 603 |
otherwise it is ignored. |
| 604 |
See :ref:`flow-control-reading` for a thorough explanation. |
| 605 |
An initial size of 0 will prevent any frames from arriving |
| 606 |
until :meth:`WebSocket.increment_read_window()` is called. |
| 607 |
|
| 608 |
on_connection_setup: Callback invoked when the connect completes. |
| 609 |
Takes a single :class:`OnConnectionSetupData` argument. |
| 610 |
|
| 611 |
If successful, :attr:`OnConnectionSetupData.websocket` will be set. |
| 612 |
You should store the :class:`WebSocket` somewhere, so you can |
| 613 |
use it to send data when you're ready. |
| 614 |
The other callbacks will be invoked as events occur, |
| 615 |
until the final `on_connection_shutdown` callback. |
| 616 |
|
| 617 |
If unsuccessful, :attr:`OnConnectionSetupData.exception` will be set, |
| 618 |
and no further callbacks will be invoked. |
| 619 |
|
| 620 |
If this callback raises an exception, the connection will shut down. |
| 621 |
|
| 622 |
on_connection_shutdown: Optional callback, invoked when a connection shuts down. |
| 623 |
Takes a single :class:`OnConnectionShutdownData` argument. |
| 624 |
|
| 625 |
This callback is never invoked if `on_connection_setup` reported an exception. |
| 626 |
|
| 627 |
on_incoming_frame_begin: Optional callback, invoked once at the start of each incoming frame. |
| 628 |
Takes a single :class:`OnIncomingFrameBeginData` argument. |
| 629 |
|
| 630 |
Each `on_incoming_frame_begin` call will be followed by 0+ |
| 631 |
`on_incoming_frame_payload` calls, followed by one |
| 632 |
`on_incoming_frame_complete` call. |
| 633 |
|
| 634 |
The "frame complete" callback is guaranteed to be invoked |
| 635 |
once for each "frame begin" callback, even if the connection |
| 636 |
is lost before the whole frame has been received. |
| 637 |
|
| 638 |
If this callback raises an exception, the connection will shut down. |
| 639 |
|
| 640 |
on_incoming_frame_payload: Optional callback, invoked 0+ times as payload data arrives. |
| 641 |
Takes a single :class:`OnIncomingFramePayloadData` argument. |
| 642 |
|
| 643 |
If `manage_read_window` is on, and this is a "data frame", |
| 644 |
then the read window shrinks accordingly. |
| 645 |
See :ref:`flow-control-reading` for a thorough explanation. |
| 646 |
|
| 647 |
If this callback raises an exception, the connection will shut down. |
| 648 |
|
| 649 |
on_incoming_frame_complete: Optional callback, invoked when the WebSocket |
| 650 |
is done processing an incoming frame. |
| 651 |
Takes a single :class:`OnIncomingFrameCompleteData` argument. |
| 652 |
|
| 653 |
If :attr:`OnIncomingFrameCompleteData.exception` is set, |
| 654 |
then something went wrong processing the frame |
| 655 |
or the connection was lost before the frame could be completed. |
| 656 |
|
| 657 |
If this callback raises an exception, the connection will shut down. |
| 658 |
""" |
| 659 |
if manage_read_window: |
| 660 |
if initial_read_window is None: |
| 661 |
raise ValueError("'initial_read_window' must be set if 'manage_read_window' is enabled") |
| 662 |
else: |
| 663 |
initial_read_window = 0 |
| 664 |
|
| 665 |
if initial_read_window < 0: |
| 666 |
raise ValueError("'initial_read_window' cannot be negative") |
| 667 |
|
| 668 |
if port is None: |
| 669 |
port = 0 |
| 670 |
|
| 671 |
if bootstrap is None: |
| 672 |
bootstrap = ClientBootstrap.get_or_create_static_default() |
| 673 |
|
| 674 |
if socket_options is None: |
| 675 |
socket_options = SocketOptions() |
| 676 |
|
| 677 |
core = _WebSocketCore( |
| 678 |
on_connection_setup, |
| 679 |
on_connection_shutdown, |
| 680 |
on_incoming_frame_begin, |
| 681 |
on_incoming_frame_payload, |
| 682 |
on_incoming_frame_complete) |
| 683 |
|
| 684 |
_awscrt.websocket_client_connect( |
| 685 |
host, |
| 686 |
port, |
| 687 |
handshake_request, |
| 688 |
bootstrap, |
| 689 |
socket_options, |
| 690 |
tls_connection_options, |
| 691 |
proxy_options, |
| 692 |
manage_read_window, |
| 693 |
initial_read_window, |
| 694 |
core) |
| 695 |
|
| 696 |
|
| 697 |
def create_handshake_request(*, host: str, path: str = '/') -> HttpRequest: |
| 698 |
"""Create an HTTP request with all the required fields for a WebSocket handshake. |
| 699 |
|
| 700 |
The method will be "GET", and the following headers are added:: |
| 701 |
|
| 702 |
Host: <host> |
| 703 |
Upgrade: websocket |
| 704 |
Connection: Upgrade |
| 705 |
Sec-WebSocket-Key: <base64-encoding of 16 random bytes> |
| 706 |
Sec-WebSocket-Version: 13 |
| 707 |
|
| 708 |
You may can add headers, or modify the path, before using this request. |
| 709 |
|
| 710 |
Args: |
| 711 |
host: Value for "Host" header |
| 712 |
path: Path (and query) string. Defaults to "/". |
| 713 |
""" |
| 714 |
http_request_binding, http_headers_binding = _awscrt.websocket_create_handshake_request(host, path) |
| 715 |
return HttpRequest._from_bindings(http_request_binding, http_headers_binding) |