client.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. from __future__ import annotations
  2. import asyncio
  3. import functools
  4. import logging
  5. import os
  6. import random
  7. import traceback
  8. import urllib.parse
  9. import warnings
  10. from collections.abc import AsyncIterator, Generator, Sequence
  11. from types import TracebackType
  12. from typing import Any, Callable, cast
  13. from ..datastructures import Headers, HeadersLike
  14. from ..exceptions import (
  15. InvalidHeader,
  16. InvalidHeaderValue,
  17. InvalidMessage,
  18. NegotiationError,
  19. SecurityError,
  20. )
  21. from ..extensions import ClientExtensionFactory, Extension
  22. from ..extensions.permessage_deflate import enable_client_permessage_deflate
  23. from ..headers import (
  24. build_authorization_basic,
  25. build_extension,
  26. build_host,
  27. build_subprotocol,
  28. parse_extension,
  29. parse_subprotocol,
  30. validate_subprotocols,
  31. )
  32. from ..http11 import USER_AGENT
  33. from ..typing import ExtensionHeader, LoggerLike, Origin, Subprotocol
  34. from ..uri import WebSocketURI, parse_uri
  35. from .exceptions import InvalidStatusCode, RedirectHandshake
  36. from .handshake import build_request, check_response
  37. from .http import read_response
  38. from .protocol import WebSocketCommonProtocol
  39. __all__ = ["connect", "unix_connect", "WebSocketClientProtocol"]
  40. class WebSocketClientProtocol(WebSocketCommonProtocol):
  41. """
  42. WebSocket client connection.
  43. :class:`WebSocketClientProtocol` provides :meth:`recv` and :meth:`send`
  44. coroutines for receiving and sending messages.
  45. It supports asynchronous iteration to receive messages::
  46. async for message in websocket:
  47. await process(message)
  48. The iterator exits normally when the connection is closed with close code
  49. 1000 (OK) or 1001 (going away) or without a close code. It raises
  50. a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection
  51. is closed with any other code.
  52. See :func:`connect` for the documentation of ``logger``, ``origin``,
  53. ``extensions``, ``subprotocols``, ``extra_headers``, and
  54. ``user_agent_header``.
  55. See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
  56. documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
  57. ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
  58. """
  59. is_client = True
  60. side = "client"
  61. def __init__(
  62. self,
  63. *,
  64. logger: LoggerLike | None = None,
  65. origin: Origin | None = None,
  66. extensions: Sequence[ClientExtensionFactory] | None = None,
  67. subprotocols: Sequence[Subprotocol] | None = None,
  68. extra_headers: HeadersLike | None = None,
  69. user_agent_header: str | None = USER_AGENT,
  70. **kwargs: Any,
  71. ) -> None:
  72. if logger is None:
  73. logger = logging.getLogger("websockets.client")
  74. super().__init__(logger=logger, **kwargs)
  75. self.origin = origin
  76. self.available_extensions = extensions
  77. self.available_subprotocols = subprotocols
  78. self.extra_headers = extra_headers
  79. self.user_agent_header = user_agent_header
  80. def write_http_request(self, path: str, headers: Headers) -> None:
  81. """
  82. Write request line and headers to the HTTP request.
  83. """
  84. self.path = path
  85. self.request_headers = headers
  86. if self.debug:
  87. self.logger.debug("> GET %s HTTP/1.1", path)
  88. for key, value in headers.raw_items():
  89. self.logger.debug("> %s: %s", key, value)
  90. # Since the path and headers only contain ASCII characters,
  91. # we can keep this simple.
  92. request = f"GET {path} HTTP/1.1\r\n"
  93. request += str(headers)
  94. self.transport.write(request.encode())
  95. async def read_http_response(self) -> tuple[int, Headers]:
  96. """
  97. Read status line and headers from the HTTP response.
  98. If the response contains a body, it may be read from ``self.reader``
  99. after this coroutine returns.
  100. Raises:
  101. InvalidMessage: If the HTTP message is malformed or isn't an
  102. HTTP/1.1 GET response.
  103. """
  104. try:
  105. status_code, reason, headers = await read_response(self.reader)
  106. except Exception as exc:
  107. raise InvalidMessage("did not receive a valid HTTP response") from exc
  108. if self.debug:
  109. self.logger.debug("< HTTP/1.1 %d %s", status_code, reason)
  110. for key, value in headers.raw_items():
  111. self.logger.debug("< %s: %s", key, value)
  112. self.response_headers = headers
  113. return status_code, self.response_headers
  114. @staticmethod
  115. def process_extensions(
  116. headers: Headers,
  117. available_extensions: Sequence[ClientExtensionFactory] | None,
  118. ) -> list[Extension]:
  119. """
  120. Handle the Sec-WebSocket-Extensions HTTP response header.
  121. Check that each extension is supported, as well as its parameters.
  122. Return the list of accepted extensions.
  123. Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the
  124. connection.
  125. :rfc:`6455` leaves the rules up to the specification of each
  126. :extension.
  127. To provide this level of flexibility, for each extension accepted by
  128. the server, we check for a match with each extension available in the
  129. client configuration. If no match is found, an exception is raised.
  130. If several variants of the same extension are accepted by the server,
  131. it may be configured several times, which won't make sense in general.
  132. Extensions must implement their own requirements. For this purpose,
  133. the list of previously accepted extensions is provided.
  134. Other requirements, for example related to mandatory extensions or the
  135. order of extensions, may be implemented by overriding this method.
  136. """
  137. accepted_extensions: list[Extension] = []
  138. header_values = headers.get_all("Sec-WebSocket-Extensions")
  139. if header_values:
  140. if available_extensions is None:
  141. raise NegotiationError("no extensions supported")
  142. parsed_header_values: list[ExtensionHeader] = sum(
  143. [parse_extension(header_value) for header_value in header_values], []
  144. )
  145. for name, response_params in parsed_header_values:
  146. for extension_factory in available_extensions:
  147. # Skip non-matching extensions based on their name.
  148. if extension_factory.name != name:
  149. continue
  150. # Skip non-matching extensions based on their params.
  151. try:
  152. extension = extension_factory.process_response_params(
  153. response_params, accepted_extensions
  154. )
  155. except NegotiationError:
  156. continue
  157. # Add matching extension to the final list.
  158. accepted_extensions.append(extension)
  159. # Break out of the loop once we have a match.
  160. break
  161. # If we didn't break from the loop, no extension in our list
  162. # matched what the server sent. Fail the connection.
  163. else:
  164. raise NegotiationError(
  165. f"Unsupported extension: "
  166. f"name = {name}, params = {response_params}"
  167. )
  168. return accepted_extensions
  169. @staticmethod
  170. def process_subprotocol(
  171. headers: Headers, available_subprotocols: Sequence[Subprotocol] | None
  172. ) -> Subprotocol | None:
  173. """
  174. Handle the Sec-WebSocket-Protocol HTTP response header.
  175. Check that it contains exactly one supported subprotocol.
  176. Return the selected subprotocol.
  177. """
  178. subprotocol: Subprotocol | None = None
  179. header_values = headers.get_all("Sec-WebSocket-Protocol")
  180. if header_values:
  181. if available_subprotocols is None:
  182. raise NegotiationError("no subprotocols supported")
  183. parsed_header_values: Sequence[Subprotocol] = sum(
  184. [parse_subprotocol(header_value) for header_value in header_values], []
  185. )
  186. if len(parsed_header_values) > 1:
  187. raise InvalidHeaderValue(
  188. "Sec-WebSocket-Protocol",
  189. f"multiple values: {', '.join(parsed_header_values)}",
  190. )
  191. subprotocol = parsed_header_values[0]
  192. if subprotocol not in available_subprotocols:
  193. raise NegotiationError(f"unsupported subprotocol: {subprotocol}")
  194. return subprotocol
  195. async def handshake(
  196. self,
  197. wsuri: WebSocketURI,
  198. origin: Origin | None = None,
  199. available_extensions: Sequence[ClientExtensionFactory] | None = None,
  200. available_subprotocols: Sequence[Subprotocol] | None = None,
  201. extra_headers: HeadersLike | None = None,
  202. ) -> None:
  203. """
  204. Perform the client side of the opening handshake.
  205. Args:
  206. wsuri: URI of the WebSocket server.
  207. origin: Value of the ``Origin`` header.
  208. extensions: List of supported extensions, in order in which they
  209. should be negotiated and run.
  210. subprotocols: List of supported subprotocols, in order of decreasing
  211. preference.
  212. extra_headers: Arbitrary HTTP headers to add to the handshake request.
  213. Raises:
  214. InvalidHandshake: If the handshake fails.
  215. """
  216. request_headers = Headers()
  217. request_headers["Host"] = build_host(wsuri.host, wsuri.port, wsuri.secure)
  218. if wsuri.user_info:
  219. request_headers["Authorization"] = build_authorization_basic(
  220. *wsuri.user_info
  221. )
  222. if origin is not None:
  223. request_headers["Origin"] = origin
  224. key = build_request(request_headers)
  225. if available_extensions is not None:
  226. extensions_header = build_extension(
  227. [
  228. (extension_factory.name, extension_factory.get_request_params())
  229. for extension_factory in available_extensions
  230. ]
  231. )
  232. request_headers["Sec-WebSocket-Extensions"] = extensions_header
  233. if available_subprotocols is not None:
  234. protocol_header = build_subprotocol(available_subprotocols)
  235. request_headers["Sec-WebSocket-Protocol"] = protocol_header
  236. if self.extra_headers is not None:
  237. request_headers.update(self.extra_headers)
  238. if self.user_agent_header:
  239. request_headers.setdefault("User-Agent", self.user_agent_header)
  240. self.write_http_request(wsuri.resource_name, request_headers)
  241. status_code, response_headers = await self.read_http_response()
  242. if status_code in (301, 302, 303, 307, 308):
  243. if "Location" not in response_headers:
  244. raise InvalidHeader("Location")
  245. raise RedirectHandshake(response_headers["Location"])
  246. elif status_code != 101:
  247. raise InvalidStatusCode(status_code, response_headers)
  248. check_response(response_headers, key)
  249. self.extensions = self.process_extensions(
  250. response_headers, available_extensions
  251. )
  252. self.subprotocol = self.process_subprotocol(
  253. response_headers, available_subprotocols
  254. )
  255. self.connection_open()
  256. class Connect:
  257. """
  258. Connect to the WebSocket server at ``uri``.
  259. Awaiting :func:`connect` yields a :class:`WebSocketClientProtocol` which
  260. can then be used to send and receive messages.
  261. :func:`connect` can be used as a asynchronous context manager::
  262. async with connect(...) as websocket:
  263. ...
  264. The connection is closed automatically when exiting the context.
  265. :func:`connect` can be used as an infinite asynchronous iterator to
  266. reconnect automatically on errors::
  267. async for websocket in connect(...):
  268. try:
  269. ...
  270. except websockets.exceptions.ConnectionClosed:
  271. continue
  272. The connection is closed automatically after each iteration of the loop.
  273. If an error occurs while establishing the connection, :func:`connect`
  274. retries with exponential backoff. The backoff delay starts at three
  275. seconds and increases up to one minute.
  276. If an error occurs in the body of the loop, you can handle the exception
  277. and :func:`connect` will reconnect with the next iteration; or you can
  278. let the exception bubble up and break out of the loop. This lets you
  279. decide which errors trigger a reconnection and which errors are fatal.
  280. Args:
  281. uri: URI of the WebSocket server.
  282. create_protocol: Factory for the :class:`asyncio.Protocol` managing
  283. the connection. It defaults to :class:`WebSocketClientProtocol`.
  284. Set it to a wrapper or a subclass to customize connection handling.
  285. logger: Logger for this client.
  286. It defaults to ``logging.getLogger("websockets.client")``.
  287. See the :doc:`logging guide <../../topics/logging>` for details.
  288. compression: The "permessage-deflate" extension is enabled by default.
  289. Set ``compression`` to :obj:`None` to disable it. See the
  290. :doc:`compression guide <../../topics/compression>` for details.
  291. origin: Value of the ``Origin`` header, for servers that require it.
  292. extensions: List of supported extensions, in order in which they
  293. should be negotiated and run.
  294. subprotocols: List of supported subprotocols, in order of decreasing
  295. preference.
  296. extra_headers: Arbitrary HTTP headers to add to the handshake request.
  297. user_agent_header: Value of the ``User-Agent`` request header.
  298. It defaults to ``"Python/x.y.z websockets/X.Y"``.
  299. Setting it to :obj:`None` removes the header.
  300. open_timeout: Timeout for opening the connection in seconds.
  301. :obj:`None` disables the timeout.
  302. See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
  303. documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
  304. ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
  305. Any other keyword arguments are passed the event loop's
  306. :meth:`~asyncio.loop.create_connection` method.
  307. For example:
  308. * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS
  309. settings. When connecting to a ``wss://`` URI, if ``ssl`` isn't
  310. provided, a TLS context is created
  311. with :func:`~ssl.create_default_context`.
  312. * You can set ``host`` and ``port`` to connect to a different host and
  313. port from those found in ``uri``. This only changes the destination of
  314. the TCP connection. The host name from ``uri`` is still used in the TLS
  315. handshake for secure connections and in the ``Host`` header.
  316. Raises:
  317. InvalidURI: If ``uri`` isn't a valid WebSocket URI.
  318. OSError: If the TCP connection fails.
  319. InvalidHandshake: If the opening handshake fails.
  320. ~asyncio.TimeoutError: If the opening handshake times out.
  321. """
  322. MAX_REDIRECTS_ALLOWED = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10"))
  323. def __init__(
  324. self,
  325. uri: str,
  326. *,
  327. create_protocol: Callable[..., WebSocketClientProtocol] | None = None,
  328. logger: LoggerLike | None = None,
  329. compression: str | None = "deflate",
  330. origin: Origin | None = None,
  331. extensions: Sequence[ClientExtensionFactory] | None = None,
  332. subprotocols: Sequence[Subprotocol] | None = None,
  333. extra_headers: HeadersLike | None = None,
  334. user_agent_header: str | None = USER_AGENT,
  335. open_timeout: float | None = 10,
  336. ping_interval: float | None = 20,
  337. ping_timeout: float | None = 20,
  338. close_timeout: float | None = None,
  339. max_size: int | None = 2**20,
  340. max_queue: int | None = 2**5,
  341. read_limit: int = 2**16,
  342. write_limit: int = 2**16,
  343. **kwargs: Any,
  344. ) -> None:
  345. # Backwards compatibility: close_timeout used to be called timeout.
  346. timeout: float | None = kwargs.pop("timeout", None)
  347. if timeout is None:
  348. timeout = 10
  349. else:
  350. warnings.warn("rename timeout to close_timeout", DeprecationWarning)
  351. # If both are specified, timeout is ignored.
  352. if close_timeout is None:
  353. close_timeout = timeout
  354. # Backwards compatibility: create_protocol used to be called klass.
  355. klass: type[WebSocketClientProtocol] | None = kwargs.pop("klass", None)
  356. if klass is None:
  357. klass = WebSocketClientProtocol
  358. else:
  359. warnings.warn("rename klass to create_protocol", DeprecationWarning)
  360. # If both are specified, klass is ignored.
  361. if create_protocol is None:
  362. create_protocol = klass
  363. # Backwards compatibility: recv() used to return None on closed connections
  364. legacy_recv: bool = kwargs.pop("legacy_recv", False)
  365. # Backwards compatibility: the loop parameter used to be supported.
  366. _loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None)
  367. if _loop is None:
  368. loop = asyncio.get_event_loop()
  369. else:
  370. loop = _loop
  371. warnings.warn("remove loop argument", DeprecationWarning)
  372. wsuri = parse_uri(uri)
  373. if wsuri.secure:
  374. kwargs.setdefault("ssl", True)
  375. elif kwargs.get("ssl") is not None:
  376. raise ValueError(
  377. "connect() received a ssl argument for a ws:// URI, "
  378. "use a wss:// URI to enable TLS"
  379. )
  380. if compression == "deflate":
  381. extensions = enable_client_permessage_deflate(extensions)
  382. elif compression is not None:
  383. raise ValueError(f"unsupported compression: {compression}")
  384. if subprotocols is not None:
  385. validate_subprotocols(subprotocols)
  386. # Help mypy and avoid this error: "type[WebSocketClientProtocol] |
  387. # Callable[..., WebSocketClientProtocol]" not callable [misc]
  388. create_protocol = cast(Callable[..., WebSocketClientProtocol], create_protocol)
  389. factory = functools.partial(
  390. create_protocol,
  391. logger=logger,
  392. origin=origin,
  393. extensions=extensions,
  394. subprotocols=subprotocols,
  395. extra_headers=extra_headers,
  396. user_agent_header=user_agent_header,
  397. ping_interval=ping_interval,
  398. ping_timeout=ping_timeout,
  399. close_timeout=close_timeout,
  400. max_size=max_size,
  401. max_queue=max_queue,
  402. read_limit=read_limit,
  403. write_limit=write_limit,
  404. host=wsuri.host,
  405. port=wsuri.port,
  406. secure=wsuri.secure,
  407. legacy_recv=legacy_recv,
  408. loop=_loop,
  409. )
  410. if kwargs.pop("unix", False):
  411. path: str | None = kwargs.pop("path", None)
  412. create_connection = functools.partial(
  413. loop.create_unix_connection, factory, path, **kwargs
  414. )
  415. else:
  416. host: str | None
  417. port: int | None
  418. if kwargs.get("sock") is None:
  419. host, port = wsuri.host, wsuri.port
  420. else:
  421. # If sock is given, host and port shouldn't be specified.
  422. host, port = None, None
  423. if kwargs.get("ssl"):
  424. kwargs.setdefault("server_hostname", wsuri.host)
  425. # If host and port are given, override values from the URI.
  426. host = kwargs.pop("host", host)
  427. port = kwargs.pop("port", port)
  428. create_connection = functools.partial(
  429. loop.create_connection, factory, host, port, **kwargs
  430. )
  431. self.open_timeout = open_timeout
  432. if logger is None:
  433. logger = logging.getLogger("websockets.client")
  434. self.logger = logger
  435. # This is a coroutine function.
  436. self._create_connection = create_connection
  437. self._uri = uri
  438. self._wsuri = wsuri
  439. def handle_redirect(self, uri: str) -> None:
  440. # Update the state of this instance to connect to a new URI.
  441. old_uri = self._uri
  442. old_wsuri = self._wsuri
  443. new_uri = urllib.parse.urljoin(old_uri, uri)
  444. new_wsuri = parse_uri(new_uri)
  445. # Forbid TLS downgrade.
  446. if old_wsuri.secure and not new_wsuri.secure:
  447. raise SecurityError("redirect from WSS to WS")
  448. same_origin = (
  449. old_wsuri.secure == new_wsuri.secure
  450. and old_wsuri.host == new_wsuri.host
  451. and old_wsuri.port == new_wsuri.port
  452. )
  453. # Rewrite secure, host, and port for cross-origin redirects.
  454. # This preserves connection overrides with the host and port
  455. # arguments if the redirect points to the same host and port.
  456. if not same_origin:
  457. factory = self._create_connection.args[0]
  458. # Support TLS upgrade.
  459. if not old_wsuri.secure and new_wsuri.secure:
  460. factory.keywords["secure"] = True
  461. self._create_connection.keywords.setdefault("ssl", True)
  462. # Strip credentials to avoid leaking them to a different origin.
  463. extra_headers = factory.keywords.get("extra_headers")
  464. if extra_headers is not None: # pragma: no cover
  465. factory.keywords["extra_headers"] = Headers(
  466. (
  467. (key, value)
  468. for key, value in Headers(extra_headers).raw_items()
  469. if key.lower()
  470. not in ["authorization", "cookie", "proxy-authorization"]
  471. )
  472. )
  473. # Replace secure, host, and port arguments of the protocol factory.
  474. factory = functools.partial(
  475. factory.func,
  476. *factory.args,
  477. **dict(factory.keywords, host=new_wsuri.host, port=new_wsuri.port),
  478. )
  479. # Replace secure, host, and port arguments of create_connection.
  480. self._create_connection = functools.partial(
  481. self._create_connection.func,
  482. *(factory, new_wsuri.host, new_wsuri.port),
  483. **self._create_connection.keywords,
  484. )
  485. # Set the new WebSocket URI. This suffices for same-origin redirects.
  486. self._uri = new_uri
  487. self._wsuri = new_wsuri
  488. # async for ... in connect(...):
  489. BACKOFF_INITIAL = float(os.environ.get("WEBSOCKETS_BACKOFF_INITIAL_DELAY", "5"))
  490. BACKOFF_MIN = float(os.environ.get("WEBSOCKETS_BACKOFF_MIN_DELAY", "3.1"))
  491. BACKOFF_MAX = float(os.environ.get("WEBSOCKETS_BACKOFF_MAX_DELAY", "90.0"))
  492. BACKOFF_FACTOR = float(os.environ.get("WEBSOCKETS_BACKOFF_FACTOR", "1.618"))
  493. async def __aiter__(self) -> AsyncIterator[WebSocketClientProtocol]:
  494. backoff_delay = self.BACKOFF_MIN / self.BACKOFF_FACTOR
  495. while True:
  496. try:
  497. async with self as protocol:
  498. yield protocol
  499. except Exception as exc:
  500. # Add a random initial delay between 0 and 5 seconds.
  501. # See 7.2.3. Recovering from Abnormal Closure in RFC 6455.
  502. if backoff_delay == self.BACKOFF_MIN:
  503. initial_delay = random.random() * self.BACKOFF_INITIAL
  504. self.logger.info(
  505. "connect failed; reconnecting in %.1f seconds: %s",
  506. initial_delay,
  507. traceback.format_exception_only(exc)[0].strip(),
  508. )
  509. await asyncio.sleep(initial_delay)
  510. else:
  511. self.logger.info(
  512. "connect failed again; retrying in %d seconds: %s",
  513. int(backoff_delay),
  514. traceback.format_exception_only(exc)[0].strip(),
  515. )
  516. await asyncio.sleep(int(backoff_delay))
  517. # Increase delay with truncated exponential backoff.
  518. backoff_delay = backoff_delay * self.BACKOFF_FACTOR
  519. backoff_delay = min(backoff_delay, self.BACKOFF_MAX)
  520. continue
  521. else:
  522. # Connection succeeded - reset backoff delay
  523. backoff_delay = self.BACKOFF_MIN
  524. # async with connect(...) as ...:
  525. async def __aenter__(self) -> WebSocketClientProtocol:
  526. return await self
  527. async def __aexit__(
  528. self,
  529. exc_type: type[BaseException] | None,
  530. exc_value: BaseException | None,
  531. traceback: TracebackType | None,
  532. ) -> None:
  533. await self.protocol.close()
  534. # ... = await connect(...)
  535. def __await__(self) -> Generator[Any, None, WebSocketClientProtocol]:
  536. # Create a suitable iterator by calling __await__ on a coroutine.
  537. return self.__await_impl__().__await__()
  538. async def __await_impl__(self) -> WebSocketClientProtocol:
  539. async with asyncio.timeout(self.open_timeout):
  540. for _redirects in range(self.MAX_REDIRECTS_ALLOWED):
  541. _transport, protocol = await self._create_connection()
  542. try:
  543. await protocol.handshake(
  544. self._wsuri,
  545. origin=protocol.origin,
  546. available_extensions=protocol.available_extensions,
  547. available_subprotocols=protocol.available_subprotocols,
  548. extra_headers=protocol.extra_headers,
  549. )
  550. except RedirectHandshake as exc:
  551. protocol.fail_connection()
  552. await protocol.wait_closed()
  553. self.handle_redirect(exc.uri)
  554. # Avoid leaking a connected socket when the handshake fails.
  555. except (Exception, asyncio.CancelledError):
  556. protocol.fail_connection()
  557. await protocol.wait_closed()
  558. raise
  559. else:
  560. self.protocol = protocol
  561. return protocol
  562. else:
  563. raise SecurityError("too many redirects")
  564. connect = Connect
  565. def unix_connect(
  566. path: str | None = None,
  567. uri: str = "ws://localhost/",
  568. **kwargs: Any,
  569. ) -> Connect:
  570. """
  571. Similar to :func:`connect`, but for connecting to a Unix socket.
  572. This function builds upon the event loop's
  573. :meth:`~asyncio.loop.create_unix_connection` method.
  574. It is only available on Unix.
  575. It's mainly useful for debugging servers listening on Unix sockets.
  576. Args:
  577. path: File system path to the Unix socket.
  578. uri: URI of the WebSocket server; the host is used in the TLS
  579. handshake for secure connections and in the ``Host`` header.
  580. """
  581. return connect(uri=uri, path=path, unix=True, **kwargs)