httpx2 2.6.0__tar.gz → 2.8.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. {httpx2-2.6.0 → httpx2-2.8.0}/PKG-INFO +3 -3
  2. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/websockets/__init__.py +9 -1
  3. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/websockets/_api.py +402 -134
  4. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/websockets/_transport.py +116 -50
  5. {httpx2-2.6.0 → httpx2-2.8.0}/pyproject.toml +1 -1
  6. {httpx2-2.6.0 → httpx2-2.8.0}/.gitignore +0 -0
  7. {httpx2-2.6.0 → httpx2-2.8.0}/CHANGELOG.md +0 -0
  8. {httpx2-2.6.0 → httpx2-2.8.0}/LICENSE.md +0 -0
  9. {httpx2-2.6.0 → httpx2-2.8.0}/README.md +0 -0
  10. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/__init__.py +0 -0
  11. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/__version__.py +0 -0
  12. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_api.py +0 -0
  13. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_auth.py +0 -0
  14. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_client.py +0 -0
  15. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_config.py +0 -0
  16. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_content.py +0 -0
  17. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_decoders.py +0 -0
  18. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_exceptions.py +0 -0
  19. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_main.py +0 -0
  20. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_models.py +0 -0
  21. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_multipart.py +0 -0
  22. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_sse.py +0 -0
  23. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_status_codes.py +0 -0
  24. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_transports/__init__.py +0 -0
  25. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_transports/asgi.py +0 -0
  26. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_transports/base.py +0 -0
  27. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_transports/default.py +0 -0
  28. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_transports/mock.py +0 -0
  29. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_transports/wsgi.py +0 -0
  30. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_types.py +0 -0
  31. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_urlparse.py +0 -0
  32. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_urls.py +0 -0
  33. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/_utils.py +0 -0
  34. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/py.typed +0 -0
  35. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/websockets/_exceptions.py +0 -0
  36. {httpx2-2.6.0 → httpx2-2.8.0}/httpx2/websockets/_ping.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: httpx2
3
- Version: 2.6.0
3
+ Version: 2.8.0
4
4
  Summary: The next generation HTTP client.
5
5
  Project-URL: Changelog, https://github.com/pydantic/httpx2/blob/main/src/httpx2/CHANGELOG.md
6
6
  Project-URL: Homepage, https://github.com/pydantic/httpx2
@@ -25,8 +25,8 @@ Classifier: Programming Language :: Python :: 3.13
25
25
  Classifier: Programming Language :: Python :: 3.14
26
26
  Classifier: Topic :: Internet :: WWW/HTTP
27
27
  Requires-Python: >=3.10
28
- Requires-Dist: anyio
29
- Requires-Dist: httpcore2==2.6.0
28
+ Requires-Dist: anyio>=4.10
29
+ Requires-Dist: httpcore2==2.8.0
30
30
  Requires-Dist: idna>=3.18
31
31
  Requires-Dist: truststore>=0.10
32
32
  Requires-Dist: typing-extensions>=4.5.0; python_version < '3.13'
@@ -4,7 +4,13 @@ WebSocket support, derived from httpx-ws (https://github.com/frankie567/httpx-ws
4
4
  Copyright (c) 2021 François Voron, MIT License (https://github.com/frankie567/httpx-ws/blob/main/LICENSE).
5
5
  """
6
6
 
7
- from ._api import AsyncWebSocketSession, JSONMode, WebSocketSession
7
+ from ._api import (
8
+ AsyncWebSocketClient,
9
+ AsyncWebSocketSession,
10
+ JSONMode,
11
+ WebSocketClient,
12
+ WebSocketSession,
13
+ )
8
14
  from ._exceptions import (
9
15
  HTTPXWSException,
10
16
  WebSocketDisconnect,
@@ -16,9 +22,11 @@ from ._transport import ASGIWebSocketTransport
16
22
 
17
23
  __all__ = [
18
24
  "ASGIWebSocketTransport",
25
+ "AsyncWebSocketClient",
19
26
  "AsyncWebSocketSession",
20
27
  "HTTPXWSException",
21
28
  "JSONMode",
29
+ "WebSocketClient",
22
30
  "WebSocketDisconnect",
23
31
  "WebSocketInvalidTypeReceived",
24
32
  "WebSocketNetworkError",
@@ -6,12 +6,19 @@ import contextlib
6
6
  import json
7
7
  import queue
8
8
  import secrets
9
+ import sys
9
10
  import threading
10
11
  import typing
11
12
  from types import TracebackType
12
13
 
14
+ if sys.version_info >= (3, 13):
15
+ from typing import TypeVar # pragma: no cover
16
+ else:
17
+ from typing_extensions import TypeVar # pragma: no cover
18
+
13
19
  import anyio
14
20
  import wsproto
21
+ import wsproto.utilities
15
22
  from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
16
23
  from wsproto.frame_protocol import CloseReason
17
24
 
@@ -50,12 +57,18 @@ if typing.TYPE_CHECKING:
50
57
  JSONMode = typing.Literal["text", "binary"]
51
58
  TaskFunction = typing.TypeVar("TaskFunction")
52
59
  TaskResult = typing.TypeVar("TaskResult")
60
+ SyncSession = TypeVar("SyncSession", bound="WebSocketSession", default="WebSocketSession")
61
+ AsyncSession = TypeVar("AsyncSession", bound="AsyncWebSocketSession", default="AsyncWebSocketSession")
53
62
 
54
63
 
55
64
  class ShouldClose(Exception):
56
65
  pass
57
66
 
58
67
 
68
+ class EndOfStream(Exception):
69
+ pass
70
+
71
+
59
72
  class WebSocketSession:
60
73
  """
61
74
  Sync context manager representing an opened WebSocket session.
@@ -92,6 +105,7 @@ class WebSocketSession:
92
105
 
93
106
  self._ping_manager = PingManager()
94
107
  self._should_close = threading.Event()
108
+ self._write_lock = threading.Lock()
95
109
  self._should_close_task: concurrent.futures.Future[bool] | None = None
96
110
  self._executor: concurrent.futures.ThreadPoolExecutor | None = None
97
111
 
@@ -190,7 +204,8 @@ class WebSocketSession:
190
204
 
191
205
  try:
192
206
  data = self.connection.send(event)
193
- self.stream.write(data)
207
+ with self._write_lock:
208
+ self.stream.write(data)
194
209
  except httpcore2.WriteError as e:
195
210
  self.close(CloseReason.INTERNAL_ERROR, "Stream write error")
196
211
  raise WebSocketNetworkError() from e
@@ -275,7 +290,7 @@ class WebSocketSession:
275
290
  A raw [wsproto.events.Event][wsproto.events.Event].
276
291
 
277
292
  Raises:
278
- queue.Empty: No event was received before the timeout delay.
293
+ TimeoutError: No event was received before the timeout delay.
279
294
  WebSocketDisconnect: The server closed the websocket.
280
295
  WebSocketNetworkError: A network error occured.
281
296
 
@@ -291,12 +306,15 @@ class WebSocketSession:
291
306
 
292
307
  try:
293
308
  event = ws.receive(timeout=2.)
294
- except queue.Empty:
309
+ except TimeoutError:
295
310
  print("No event received.")
296
311
  except WebSocketDisconnect:
297
312
  print("Connection closed")
298
313
  """
299
- event = self._events.get(block=True, timeout=timeout)
314
+ try:
315
+ event = self._events.get(block=True, timeout=timeout)
316
+ except queue.Empty as e:
317
+ raise TimeoutError from e
300
318
  if isinstance(event, HTTPXWSException):
301
319
  raise event
302
320
  if isinstance(event, wsproto.events.CloseConnection):
@@ -316,7 +334,7 @@ class WebSocketSession:
316
334
  Text data.
317
335
 
318
336
  Raises:
319
- queue.Empty: No event was received before the timeout delay.
337
+ TimeoutError: No event was received before the timeout delay.
320
338
  WebSocketDisconnect: The server closed the websocket.
321
339
  WebSocketNetworkError: A network error occured.
322
340
  WebSocketInvalidTypeReceived: The received event was not a text message.
@@ -333,7 +351,7 @@ class WebSocketSession:
333
351
 
334
352
  try:
335
353
  event = ws.receive_text(timeout=2.)
336
- except queue.Empty:
354
+ except TimeoutError:
337
355
  print("No text received.")
338
356
  except WebSocketDisconnect:
339
357
  print("Connection closed")
@@ -356,7 +374,7 @@ class WebSocketSession:
356
374
  Bytes data.
357
375
 
358
376
  Raises:
359
- queue.Empty: No event was received before the timeout delay.
377
+ TimeoutError: No event was received before the timeout delay.
360
378
  WebSocketDisconnect: The server closed the websocket.
361
379
  WebSocketNetworkError: A network error occured.
362
380
  WebSocketInvalidTypeReceived: The received event was not a bytes message.
@@ -373,7 +391,7 @@ class WebSocketSession:
373
391
 
374
392
  try:
375
393
  data = ws.receive_bytes(timeout=2.)
376
- except queue.Empty:
394
+ except TimeoutError:
377
395
  print("No data received.")
378
396
  except WebSocketDisconnect:
379
397
  print("Connection closed")
@@ -400,7 +418,7 @@ class WebSocketSession:
400
418
  Parsed JSON data.
401
419
 
402
420
  Raises:
403
- queue.Empty: No event was received before the timeout delay.
421
+ TimeoutError: No event was received before the timeout delay.
404
422
  WebSocketDisconnect: The server closed the websocket.
405
423
  WebSocketNetworkError: A network error occured.
406
424
  WebSocketInvalidTypeReceived: The received event
@@ -418,7 +436,7 @@ class WebSocketSession:
418
436
 
419
437
  try:
420
438
  data = ws.receive_json(timeout=2.)
421
- except queue.Empty:
439
+ except TimeoutError:
422
440
  print("No data received.")
423
441
  except WebSocketDisconnect:
424
442
  print("Connection closed")
@@ -463,7 +481,8 @@ class WebSocketSession:
463
481
  event = wsproto.events.CloseConnection(code, reason)
464
482
  data = self.connection.send(event)
465
483
  try:
466
- self.stream.write(data)
484
+ with self._write_lock:
485
+ self.stream.write(data)
467
486
  except httpcore2.WriteError:
468
487
  pass
469
488
  self.stream.close()
@@ -487,12 +506,13 @@ class WebSocketSession:
487
506
  partial_message_buffer: str | bytes | None = None
488
507
  try:
489
508
  while not self._should_close.is_set():
490
- data = self._wait_until_closed(self.stream.read, max_bytes)
509
+ data = self._wait_until_closed(self._read_stream, max_bytes)
491
510
  self.connection.receive_data(data)
492
511
  for event in self.connection.events():
493
512
  if isinstance(event, wsproto.events.Ping):
494
513
  data = self.connection.send(event.response())
495
- self.stream.write(data)
514
+ with self._write_lock:
515
+ self.stream.write(data)
496
516
  continue
497
517
  if isinstance(event, wsproto.events.Pong):
498
518
  self._ping_manager.ack(event.payload)
@@ -517,7 +537,7 @@ class WebSocketSession:
517
537
  self._events.put(full_message_event)
518
538
  continue
519
539
  self._events.put(event)
520
- except (httpcore2.ReadError, httpcore2.WriteError):
540
+ except (httpcore2.ReadError, httpcore2.WriteError, EndOfStream):
521
541
  self.close(CloseReason.INTERNAL_ERROR, "Stream error")
522
542
  self._events.put(WebSocketNetworkError())
523
543
  except ShouldClose:
@@ -557,11 +577,39 @@ class WebSocketSession:
557
577
  result = todo_task.result()
558
578
  return result
559
579
 
580
+ def _read_stream(self, max_bytes: int) -> bytes:
581
+ data = self.stream.read(max_bytes)
582
+ if data == b"":
583
+ raise EndOfStream()
584
+ return data
560
585
 
561
- class AsyncWebSocketSession:
586
+
587
+ class AsyncWebSocketSession(anyio.AsyncContextManagerMixin):
562
588
  """
563
589
  Async context manager representing an opened WebSocket session.
564
590
 
591
+ Internally, this session uses an anyio task group to manage background tasks.
592
+ As a result, exceptions that are not caught inside the context manager
593
+ and propagate out of the `async with` block will be wrapped
594
+ in an [ExceptionGroup][ExceptionGroup].
595
+
596
+ To handle them, use the `except*` syntax:
597
+
598
+ async with AsyncWebSocketSession(stream) as ws:
599
+ try:
600
+ data = await ws.receive_text()
601
+ except WebSocketDisconnect:
602
+ # Caught inside the context manager: plain exception.
603
+ print("Connection closed")
604
+
605
+ # If not caught inside:
606
+ try:
607
+ async with AsyncWebSocketSession(stream) as ws:
608
+ data = await ws.receive_text()
609
+ except* WebSocketDisconnect:
610
+ # Propagated out of the context manager: wrapped in ExceptionGroup.
611
+ print("Connection closed")
612
+
565
613
  Attributes:
566
614
  subprotocol (typing.Optional[str]):
567
615
  Optional protocol that has been accepted by the server.
@@ -594,6 +642,7 @@ class AsyncWebSocketSession:
594
642
 
595
643
  self._ping_manager = AsyncPingManager()
596
644
  self._should_close = anyio.Event()
645
+ self._write_lock = anyio.Lock()
597
646
 
598
647
  self._max_message_size_bytes = max_message_size_bytes
599
648
  self._queue_size = queue_size
@@ -606,17 +655,14 @@ class AsyncWebSocketSession:
606
655
  self._keepalive_ping_interval_seconds = keepalive_ping_interval_seconds
607
656
  self._keepalive_ping_timeout_seconds = keepalive_ping_timeout_seconds
608
657
 
609
- async def __aenter__(self) -> AsyncWebSocketSession:
610
- async with contextlib.AsyncExitStack() as exit_stack:
611
- self._send_event, self._receive_event = anyio.create_memory_object_stream[
612
- wsproto.events.Event | HTTPXWSException
613
- ]()
614
- exit_stack.enter_context(self._send_event)
615
- exit_stack.enter_context(self._receive_event)
616
-
617
- self._background_task_group = anyio.create_task_group()
618
- await exit_stack.enter_async_context(self._background_task_group)
658
+ @contextlib.asynccontextmanager
659
+ async def __asynccontextmanager__(self) -> typing.AsyncGenerator[AsyncWebSocketSession, None]:
660
+ self._send_event, self._receive_event = anyio.create_memory_object_stream[
661
+ wsproto.events.Event | HTTPXWSException
662
+ ]()
663
+ self._background_task_group = anyio.create_task_group()
619
664
 
665
+ async with self._send_event, self._receive_event, self._background_task_group:
620
666
  self._background_task_group.start_soon(self._background_receive, self._max_message_size_bytes)
621
667
  if self._keepalive_ping_interval_seconds is not None:
622
668
  self._background_task_group.start_soon(
@@ -625,19 +671,12 @@ class AsyncWebSocketSession:
625
671
  self._keepalive_ping_timeout_seconds,
626
672
  )
627
673
 
628
- exit_stack.callback(self._background_task_group.cancel_scope.cancel)
629
- exit_stack.push_async_callback(self.close)
630
- self._exit_stack = exit_stack.pop_all()
631
-
632
- return self
633
-
634
- async def __aexit__(
635
- self,
636
- exc_type: type[BaseException] | None,
637
- exc: BaseException | None,
638
- tb: TracebackType | None,
639
- ) -> None:
640
- await self._exit_stack.aclose()
674
+ try:
675
+ yield self
676
+ finally:
677
+ self._background_task_group.cancel_scope.cancel()
678
+ with anyio.CancelScope(shield=True):
679
+ await self.close()
641
680
 
642
681
  async def ping(self, payload: bytes = b"") -> anyio.Event:
643
682
  """
@@ -680,6 +719,11 @@ class AsyncWebSocketSession:
680
719
  Raises:
681
720
  WebSocketNetworkError: A network error occured.
682
721
 
722
+ Note:
723
+ Exceptions not caught inside the context manager will be
724
+ wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
725
+ outside the `async with` block.
726
+
683
727
  Examples:
684
728
  Send an event.
685
729
 
@@ -690,7 +734,8 @@ class AsyncWebSocketSession:
690
734
 
691
735
  try:
692
736
  data = self.connection.send(event)
693
- await self.stream.write(data)
737
+ async with self._write_lock:
738
+ await self.stream.write(data)
694
739
  except httpcore2.WriteError as e:
695
740
  await self.close(CloseReason.INTERNAL_ERROR, "Stream write error")
696
741
  raise WebSocketNetworkError() from e
@@ -705,6 +750,11 @@ class AsyncWebSocketSession:
705
750
  Raises:
706
751
  WebSocketNetworkError: A network error occured.
707
752
 
753
+ Note:
754
+ Exceptions not caught inside the context manager will be
755
+ wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
756
+ outside the `async with` block.
757
+
708
758
  Examples:
709
759
  Send a text message.
710
760
 
@@ -723,6 +773,11 @@ class AsyncWebSocketSession:
723
773
  Raises:
724
774
  WebSocketNetworkError: A network error occured.
725
775
 
776
+ Note:
777
+ Exceptions not caught inside the context manager will be
778
+ wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
779
+ outside the `async with` block.
780
+
726
781
  Examples:
727
782
  Send a bytes message.
728
783
 
@@ -744,6 +799,11 @@ class AsyncWebSocketSession:
744
799
  Raises:
745
800
  WebSocketNetworkError: A network error occured.
746
801
 
802
+ Note:
803
+ Exceptions not caught inside the context manager will be
804
+ wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
805
+ outside the `async with` block.
806
+
747
807
  Examples:
748
808
  Send JSON data.
749
809
 
@@ -779,6 +839,11 @@ class AsyncWebSocketSession:
779
839
  WebSocketDisconnect: The server closed the websocket.
780
840
  WebSocketNetworkError: A network error occured.
781
841
 
842
+ Note:
843
+ Exceptions not caught inside the context manager will be
844
+ wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
845
+ outside the `async with` block.
846
+
782
847
  Examples:
783
848
  Wait for an event until one is available.
784
849
 
@@ -822,6 +887,11 @@ class AsyncWebSocketSession:
822
887
  WebSocketNetworkError: A network error occured.
823
888
  WebSocketInvalidTypeReceived: The received event was not a text message.
824
889
 
890
+ Note:
891
+ Exceptions not caught inside the context manager will be
892
+ wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
893
+ outside the `async with` block.
894
+
825
895
  Examples:
826
896
  Wait for text until available.
827
897
 
@@ -862,6 +932,11 @@ class AsyncWebSocketSession:
862
932
  WebSocketNetworkError: A network error occured.
863
933
  WebSocketInvalidTypeReceived: The received event was not a bytes message.
864
934
 
935
+ Note:
936
+ Exceptions not caught inside the context manager will be
937
+ wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
938
+ outside the `async with` block.
939
+
865
940
  Examples:
866
941
  Wait for bytes until available.
867
942
 
@@ -907,6 +982,11 @@ class AsyncWebSocketSession:
907
982
  WebSocketInvalidTypeReceived: The received event
908
983
  didn't correspond to the specified mode.
909
984
 
985
+ Note:
986
+ Exceptions not caught inside the context manager will be
987
+ wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
988
+ outside the `async with` block.
989
+
910
990
  Examples:
911
991
  Wait for data until available.
912
992
 
@@ -962,7 +1042,8 @@ class AsyncWebSocketSession:
962
1042
  event = wsproto.events.CloseConnection(code, reason)
963
1043
  data = self.connection.send(event)
964
1044
  try:
965
- await self.stream.write(data)
1045
+ async with self._write_lock:
1046
+ await self.stream.write(data)
966
1047
  except httpcore2.WriteError:
967
1048
  pass
968
1049
  await self.stream.aclose()
@@ -986,12 +1067,13 @@ class AsyncWebSocketSession:
986
1067
  partial_message_buffer: str | bytes | None = None
987
1068
  try:
988
1069
  while not self._should_close.is_set():
989
- data = await self.stream.read(max_bytes=max_bytes)
1070
+ data = await self._read_stream(max_bytes)
990
1071
  self.connection.receive_data(data)
991
1072
  for event in self.connection.events():
992
1073
  if isinstance(event, wsproto.events.Ping):
993
1074
  data = self.connection.send(event.response())
994
- await self.stream.write(data)
1075
+ async with self._write_lock:
1076
+ await self.stream.write(data)
995
1077
  continue
996
1078
  if isinstance(event, wsproto.events.Pong):
997
1079
  self._ping_manager.ack(event.payload)
@@ -1016,16 +1098,20 @@ class AsyncWebSocketSession:
1016
1098
  await self._send_event.send(full_message_event)
1017
1099
  continue
1018
1100
  await self._send_event.send(event)
1019
- except (httpcore2.ReadError, httpcore2.WriteError):
1101
+ except (httpcore2.ReadError, httpcore2.WriteError, EndOfStream):
1020
1102
  await self.close(CloseReason.INTERNAL_ERROR, "Stream error")
1021
1103
  await self._send_event.send(WebSocketNetworkError())
1022
1104
 
1023
1105
  async def _background_keepalive_ping(self, interval_seconds: float, timeout_seconds: float | None = None) -> None:
1024
1106
  while not self._should_close.is_set():
1025
1107
  await anyio.sleep(interval_seconds)
1026
- if self._should_close.is_set():
1108
+
1109
+ try:
1110
+ pong_callback = await self.ping()
1111
+ # Connection is closing, exit the task
1112
+ except wsproto.utilities.LocalProtocolError:
1027
1113
  return
1028
- pong_callback = await self.ping()
1114
+
1029
1115
  if timeout_seconds is not None:
1030
1116
  try:
1031
1117
  with anyio.fail_after(timeout_seconds):
@@ -1034,6 +1120,12 @@ class AsyncWebSocketSession:
1034
1120
  await self.close(CloseReason.INTERNAL_ERROR, "Keepalive ping timeout")
1035
1121
  await self._send_event.send(WebSocketNetworkError())
1036
1122
 
1123
+ async def _read_stream(self, max_bytes: int) -> bytes:
1124
+ data = await self.stream.read(max_bytes)
1125
+ if data == b"":
1126
+ raise EndOfStream()
1127
+ return data
1128
+
1037
1129
 
1038
1130
  def _get_headers(
1039
1131
  subprotocols: list[str] | None,
@@ -1049,47 +1141,133 @@ def _get_headers(
1049
1141
  return headers
1050
1142
 
1051
1143
 
1052
- @contextlib.contextmanager
1053
- def _connect_ws(
1054
- url: str,
1055
- client: Client,
1056
- *,
1057
- max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
1058
- queue_size: int = DEFAULT_QUEUE_SIZE,
1059
- keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
1060
- keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
1061
- subprotocols: list[str] | None = None,
1062
- params: QueryParamTypes | None = None,
1063
- headers: HeaderTypes | None = None,
1064
- cookies: CookieTypes | None = None,
1065
- auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
1066
- follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1067
- timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1068
- extensions: RequestExtensions | None = None,
1069
- ) -> typing.Generator[WebSocketSession, None, None]:
1070
- with client.stream(
1071
- "GET",
1072
- url,
1073
- params=params,
1074
- headers=Headers(headers) | _get_headers(subprotocols),
1075
- cookies=cookies,
1076
- auth=auth,
1077
- follow_redirects=follow_redirects,
1078
- timeout=timeout,
1079
- extensions=extensions,
1080
- ) as response:
1081
- if response.status_code != 101:
1082
- raise WebSocketUpgradeError(response)
1083
-
1084
- with WebSocketSession(
1085
- response.extensions["network_stream"],
1086
- max_message_size_bytes=max_message_size_bytes,
1087
- queue_size=queue_size,
1088
- keepalive_ping_interval_seconds=keepalive_ping_interval_seconds,
1089
- keepalive_ping_timeout_seconds=keepalive_ping_timeout_seconds,
1090
- response=response,
1091
- ) as session:
1092
- yield session
1144
+ class WebSocketClient(typing.Generic[SyncSession]):
1145
+ """
1146
+ A sync WebSocket client.
1147
+
1148
+ This class provides an API for connecting to WebSocket.
1149
+
1150
+ Attributes:
1151
+ client:
1152
+ HTTPX client to use.
1153
+ max_message_size_bytes:
1154
+ Message size in bytes to receive from the server.
1155
+ Defaults to 65 KiB.
1156
+ queue_size:
1157
+ Size of the queue where the received messages will be held
1158
+ until they are consumed.
1159
+ If the queue is full, the client will stop receive messages
1160
+ from the server until the queue has room available.
1161
+ Defaults to 512.
1162
+ keepalive_ping_interval_seconds:
1163
+ Interval at which the client will automatically send a Ping event
1164
+ to keep the connection alive. Set it to `None` to disable this mechanism.
1165
+ Defaults to 20 seconds.
1166
+ keepalive_ping_timeout_seconds:
1167
+ Maximum delay the client will wait for an answer to its Ping event.
1168
+ If the delay is exceeded,
1169
+ [WebSocketNetworkError][httpx_ws.WebSocketNetworkError]
1170
+ will be raised and the connection closed.
1171
+ Defaults to 20 seconds.
1172
+ session_class:
1173
+ The session class to use.
1174
+ Defaults to [WebSocketSession][httpx_ws.WebSocketSession].
1175
+ """
1176
+
1177
+ def __init__(
1178
+ self,
1179
+ client: Client,
1180
+ *,
1181
+ max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
1182
+ queue_size: int = DEFAULT_QUEUE_SIZE,
1183
+ keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
1184
+ keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
1185
+ session_class: type[SyncSession] = WebSocketSession, # type: ignore[assignment]
1186
+ ) -> None:
1187
+ self.client = client
1188
+ self.max_message_size_bytes = max_message_size_bytes
1189
+ self.queue_size = queue_size
1190
+ self.keepalive_ping_interval_seconds = keepalive_ping_interval_seconds
1191
+ self.keepalive_ping_timeout_seconds = keepalive_ping_timeout_seconds
1192
+ self.session_class = session_class
1193
+
1194
+ @contextlib.contextmanager
1195
+ def connect(
1196
+ self,
1197
+ url: str,
1198
+ *,
1199
+ subprotocols: list[str] | None = None,
1200
+ params: QueryParamTypes | None = None,
1201
+ headers: HeaderTypes | None = None,
1202
+ cookies: CookieTypes | None = None,
1203
+ auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
1204
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1205
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1206
+ extensions: RequestExtensions | None = None,
1207
+ ) -> typing.Generator[SyncSession, None, None]:
1208
+ """
1209
+ Start a sync WebSocket session.
1210
+
1211
+ It returns a context manager that'll automatically
1212
+ call [close()][httpx_ws.WebSocketSession.close] when exiting.
1213
+
1214
+ Args:
1215
+ url: The WebSocket URL.
1216
+ subprotocols:
1217
+ Optional list of subprotocols to negotiate with the server.
1218
+ params:
1219
+ Query parameters to include in the handshake request.
1220
+ headers:
1221
+ Headers to include in the handshake request.
1222
+ cookies:
1223
+ Cookies to include in the handshake request.
1224
+ auth:
1225
+ Authentication to use for the handshake request.
1226
+ follow_redirects:
1227
+ Whether to follow redirects on the handshake request.
1228
+ timeout:
1229
+ Timeout configuration for the handshake request.
1230
+ extensions:
1231
+ Request extensions for the handshake request.
1232
+
1233
+ Returns:
1234
+ A [context manager][contextlib.AbstractContextManager]
1235
+ for [WebSocketSession][httpx_ws.WebSocketSession].
1236
+
1237
+ Examples:
1238
+ Initialize the client and connect to a WebSocket.
1239
+
1240
+ with httpx2.Client() as client:
1241
+ ws_client = WebSocketClient(client)
1242
+ with ws_client.connect("http://localhost:8000/ws") as ws:
1243
+ message = ws.receive_text()
1244
+ print(message)
1245
+ ws.send_text("Hello!")
1246
+ """
1247
+ with self.client.stream(
1248
+ "GET",
1249
+ url,
1250
+ params=params,
1251
+ headers=Headers(headers) | _get_headers(subprotocols),
1252
+ cookies=cookies,
1253
+ auth=auth,
1254
+ follow_redirects=follow_redirects,
1255
+ timeout=timeout,
1256
+ extensions=extensions,
1257
+ ) as response:
1258
+ if response.status_code != 101:
1259
+ raise WebSocketUpgradeError(response)
1260
+
1261
+ session = self.session_class(
1262
+ response.extensions["network_stream"],
1263
+ max_message_size_bytes=self.max_message_size_bytes,
1264
+ queue_size=self.queue_size,
1265
+ keepalive_ping_interval_seconds=self.keepalive_ping_interval_seconds,
1266
+ keepalive_ping_timeout_seconds=self.keepalive_ping_timeout_seconds,
1267
+ response=response,
1268
+ )
1269
+ with session:
1270
+ yield session
1093
1271
 
1094
1272
 
1095
1273
  @contextlib.contextmanager
@@ -1141,7 +1319,7 @@ def connect_ws(
1141
1319
  will be raised and the connection closed.
1142
1320
  Defaults to 20 seconds.
1143
1321
  subprotocols:
1144
- Optional list of suprotocols to negotiate with the server.
1322
+ Optional list of subprotocols to negotiate with the server.
1145
1323
  params:
1146
1324
  Query parameters to include in the handshake request.
1147
1325
  headers:
@@ -1185,13 +1363,15 @@ def connect_ws(
1185
1363
  owned_client = contextlib.nullcontext(client)
1186
1364
 
1187
1365
  with owned_client as client:
1188
- with _connect_ws(
1189
- url,
1366
+ ws_client = WebSocketClient(
1190
1367
  client=client,
1191
1368
  max_message_size_bytes=max_message_size_bytes,
1192
1369
  queue_size=queue_size,
1193
1370
  keepalive_ping_interval_seconds=keepalive_ping_interval_seconds,
1194
1371
  keepalive_ping_timeout_seconds=keepalive_ping_timeout_seconds,
1372
+ )
1373
+ with ws_client.connect(
1374
+ url,
1195
1375
  subprotocols=subprotocols,
1196
1376
  params=params,
1197
1377
  headers=headers,
@@ -1204,47 +1384,133 @@ def connect_ws(
1204
1384
  yield websocket
1205
1385
 
1206
1386
 
1207
- @contextlib.asynccontextmanager
1208
- async def _aconnect_ws(
1209
- url: str,
1210
- client: AsyncClient,
1211
- *,
1212
- max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
1213
- queue_size: int = DEFAULT_QUEUE_SIZE,
1214
- keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
1215
- keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
1216
- subprotocols: list[str] | None = None,
1217
- params: QueryParamTypes | None = None,
1218
- headers: HeaderTypes | None = None,
1219
- cookies: CookieTypes | None = None,
1220
- auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
1221
- follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1222
- timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1223
- extensions: RequestExtensions | None = None,
1224
- ) -> typing.AsyncGenerator[AsyncWebSocketSession, None]:
1225
- async with client.stream(
1226
- "GET",
1227
- url,
1228
- params=params,
1229
- headers=Headers(headers) | _get_headers(subprotocols),
1230
- cookies=cookies,
1231
- auth=auth,
1232
- follow_redirects=follow_redirects,
1233
- timeout=timeout,
1234
- extensions=extensions,
1235
- ) as response:
1236
- if response.status_code != 101:
1237
- raise WebSocketUpgradeError(response)
1238
-
1239
- async with AsyncWebSocketSession(
1240
- response.extensions["network_stream"],
1241
- max_message_size_bytes=max_message_size_bytes,
1242
- queue_size=queue_size,
1243
- keepalive_ping_interval_seconds=keepalive_ping_interval_seconds,
1244
- keepalive_ping_timeout_seconds=keepalive_ping_timeout_seconds,
1245
- response=response,
1246
- ) as session:
1247
- yield session
1387
+ class AsyncWebSocketClient(typing.Generic[AsyncSession]):
1388
+ """
1389
+ An async WebSocket client.
1390
+
1391
+ This class provides an API for connecting to WebSocket.
1392
+
1393
+ Attributes:
1394
+ client:
1395
+ HTTPX client to use.
1396
+ max_message_size_bytes:
1397
+ Message size in bytes to receive from the server.
1398
+ Defaults to 65 KiB.
1399
+ queue_size:
1400
+ Size of the queue where the received messages will be held
1401
+ until they are consumed.
1402
+ If the queue is full, the client will stop receive messages
1403
+ from the server until the queue has room available.
1404
+ Defaults to 512.
1405
+ keepalive_ping_interval_seconds:
1406
+ Interval at which the client will automatically send a Ping event
1407
+ to keep the connection alive. Set it to `None` to disable this mechanism.
1408
+ Defaults to 20 seconds.
1409
+ keepalive_ping_timeout_seconds:
1410
+ Maximum delay the client will wait for an answer to its Ping event.
1411
+ If the delay is exceeded,
1412
+ [WebSocketNetworkError][httpx_ws.WebSocketNetworkError]
1413
+ will be raised in an [ExceptionGroup][ExceptionGroup] and the connection closed.
1414
+ Defaults to 20 seconds.
1415
+ session_class:
1416
+ The session class to use.
1417
+ Defaults to [AsyncWebSocketSession][httpx_ws.AsyncWebSocketSession].
1418
+ """
1419
+
1420
+ def __init__(
1421
+ self,
1422
+ client: AsyncClient,
1423
+ *,
1424
+ max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
1425
+ queue_size: int = DEFAULT_QUEUE_SIZE,
1426
+ keepalive_ping_interval_seconds: float | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
1427
+ keepalive_ping_timeout_seconds: float | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
1428
+ session_class: type[AsyncSession] = AsyncWebSocketSession, # type: ignore[assignment]
1429
+ ) -> None:
1430
+ self.client = client
1431
+ self.max_message_size_bytes = max_message_size_bytes
1432
+ self.queue_size = queue_size
1433
+ self.keepalive_ping_interval_seconds = keepalive_ping_interval_seconds
1434
+ self.keepalive_ping_timeout_seconds = keepalive_ping_timeout_seconds
1435
+ self.session_class = session_class
1436
+
1437
+ @contextlib.asynccontextmanager
1438
+ async def connect(
1439
+ self,
1440
+ url: str,
1441
+ *,
1442
+ subprotocols: list[str] | None = None,
1443
+ params: QueryParamTypes | None = None,
1444
+ headers: HeaderTypes | None = None,
1445
+ cookies: CookieTypes | None = None,
1446
+ auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
1447
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1448
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1449
+ extensions: RequestExtensions | None = None,
1450
+ ) -> typing.AsyncGenerator[AsyncSession, None]:
1451
+ """
1452
+ Start an async WebSocket session.
1453
+
1454
+ It returns an async context manager that'll automatically
1455
+ call [close()][httpx_ws.AsyncWebSocketSession.close] when exiting.
1456
+
1457
+ Args:
1458
+ url: The WebSocket URL.
1459
+ subprotocols:
1460
+ Optional list of subprotocols to negotiate with the server.
1461
+ params:
1462
+ Query parameters to include in the handshake request.
1463
+ headers:
1464
+ Headers to include in the handshake request.
1465
+ cookies:
1466
+ Cookies to include in the handshake request.
1467
+ auth:
1468
+ Authentication to use for the handshake request.
1469
+ follow_redirects:
1470
+ Whether to follow redirects on the handshake request.
1471
+ timeout:
1472
+ Timeout configuration for the handshake request.
1473
+ extensions:
1474
+ Request extensions for the handshake request.
1475
+
1476
+ Returns:
1477
+ An [async context manager][contextlib.AbstractAsyncContextManager]
1478
+ for [AsyncWebSocketSession][httpx_ws.AsyncWebSocketSession].
1479
+
1480
+ Examples:
1481
+ Initialize the client and connect to a WebSocket.
1482
+
1483
+ async with httpx2.AsyncClient() as client:
1484
+ ws_client = AsyncWebSocketClient(client)
1485
+ async with ws_client.connect("http://localhost:8000/ws") as ws:
1486
+ message = await ws.receive_text()
1487
+ print(message)
1488
+ await ws.send_text("Hello!")
1489
+ """
1490
+ async with self.client.stream(
1491
+ "GET",
1492
+ url,
1493
+ params=params,
1494
+ headers=Headers(headers) | _get_headers(subprotocols),
1495
+ cookies=cookies,
1496
+ auth=auth,
1497
+ follow_redirects=follow_redirects,
1498
+ timeout=timeout,
1499
+ extensions=extensions,
1500
+ ) as response:
1501
+ if response.status_code != 101:
1502
+ raise WebSocketUpgradeError(response)
1503
+
1504
+ session = self.session_class(
1505
+ response.extensions["network_stream"],
1506
+ max_message_size_bytes=self.max_message_size_bytes,
1507
+ queue_size=self.queue_size,
1508
+ keepalive_ping_interval_seconds=self.keepalive_ping_interval_seconds,
1509
+ keepalive_ping_timeout_seconds=self.keepalive_ping_timeout_seconds,
1510
+ response=response,
1511
+ )
1512
+ async with session:
1513
+ yield session
1248
1514
 
1249
1515
 
1250
1516
  @contextlib.asynccontextmanager
@@ -1293,10 +1559,10 @@ async def aconnect_ws(
1293
1559
  Maximum delay the client will wait for an answer to its Ping event.
1294
1560
  If the delay is exceeded,
1295
1561
  [WebSocketNetworkError][httpx_ws.WebSocketNetworkError]
1296
- will be raised and the connection closed.
1562
+ will be raised in an [ExceptionGroup][ExceptionGroup] and the connection closed.
1297
1563
  Defaults to 20 seconds.
1298
1564
  subprotocols:
1299
- Optional list of suprotocols to negotiate with the server.
1565
+ Optional list of subprotocols to negotiate with the server.
1300
1566
  params:
1301
1567
  Query parameters to include in the handshake request.
1302
1568
  headers:
@@ -1340,13 +1606,15 @@ async def aconnect_ws(
1340
1606
  owned_client = contextlib.nullcontext(client)
1341
1607
 
1342
1608
  async with owned_client as client:
1343
- async with _aconnect_ws(
1344
- url,
1609
+ ws_client = AsyncWebSocketClient(
1345
1610
  client=client,
1346
1611
  max_message_size_bytes=max_message_size_bytes,
1347
1612
  queue_size=queue_size,
1348
1613
  keepalive_ping_interval_seconds=keepalive_ping_interval_seconds,
1349
1614
  keepalive_ping_timeout_seconds=keepalive_ping_timeout_seconds,
1615
+ )
1616
+ async with ws_client.connect(
1617
+ url,
1350
1618
  subprotocols=subprotocols,
1351
1619
  params=params,
1352
1620
  headers=headers,
@@ -1,9 +1,9 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import contextlib
4
- import queue
4
+ import math
5
5
  import typing
6
- from concurrent.futures import Future
6
+ from types import TracebackType
7
7
 
8
8
  import anyio
9
9
  import wsproto
@@ -12,7 +12,7 @@ from wsproto.frame_protocol import CloseReason
12
12
  from .._models import Request, Response
13
13
  from .._transports.asgi import ASGITransport, _ASGIApp
14
14
  from .._types import AsyncByteStream
15
- from ._exceptions import WebSocketDisconnect
15
+ from ._exceptions import WebSocketDisconnect, WebSocketUpgradeError
16
16
 
17
17
  Scope = dict[str, typing.Any]
18
18
  Message = dict[str, typing.Any]
@@ -36,33 +36,77 @@ class UnhandledWebSocketEvent(ASGIWebSocketTransportError):
36
36
 
37
37
 
38
38
  class ASGIWebSocketAsyncNetworkStream:
39
- def __init__(self, app: ASGIApp, scope: Scope) -> None:
39
+ def __init__(
40
+ self,
41
+ app: ASGIApp,
42
+ scope: Scope,
43
+ task_group: anyio.abc.TaskGroup,
44
+ initial_receive_timeout: float = 1.0,
45
+ ) -> None:
40
46
  self.app = app
41
47
  self.scope = scope
42
- self._receive_queue: queue.Queue[Message] = queue.Queue()
43
- self._send_queue: queue.Queue[Message] = queue.Queue()
48
+ self._receive_queue = anyio.streams.stapled.StapledObjectStream(
49
+ *anyio.create_memory_object_stream[Message](max_buffer_size=math.inf)
50
+ )
51
+ self._send_queue = anyio.streams.stapled.StapledObjectStream(
52
+ *anyio.create_memory_object_stream[Message](max_buffer_size=math.inf)
53
+ )
54
+ self._task_group = task_group
55
+ self._initial_receive_timeout = initial_receive_timeout
44
56
  self.connection = wsproto.WSConnection(wsproto.ConnectionType.SERVER)
45
57
  self.connection.initiate_upgrade_connection(scope["headers"], scope["path"])
58
+ self._aentered = False
46
59
 
47
60
  async def __aenter__(
48
61
  self,
49
62
  ) -> tuple[ASGIWebSocketAsyncNetworkStream, bytes]:
50
- self.exit_stack = contextlib.ExitStack()
51
- self.portal = self.exit_stack.enter_context(anyio.from_thread.start_blocking_portal("asyncio"))
52
- _: Future[None] = self.portal.start_task_soon(self._run)
53
-
54
- await self.send({"type": "websocket.connect"})
55
- message = await self.receive()
56
-
57
- if message["type"] == "websocket.close":
58
- await self.aclose()
59
- raise WebSocketDisconnect(message["code"], message.get("reason"))
60
-
61
- assert message["type"] == "websocket.accept"
62
- return self, self._build_accept_response(message)
63
-
64
- async def __aexit__(self, *args: typing.Any) -> None:
65
- await self.aclose()
63
+ if self._aentered:
64
+ raise RuntimeError("Cannot use ASGIWebSocketAsyncNetworkStream in a context manager twice")
65
+ self._aentered = True
66
+ self._task_group.start_soon(self._run)
67
+ async with contextlib.AsyncExitStack() as stack:
68
+ stack.push_async_callback(self.aclose)
69
+ await self.send({"type": "websocket.connect"})
70
+
71
+ try:
72
+ message = await self.receive(self._initial_receive_timeout)
73
+ except TimeoutError as e:
74
+ raise RuntimeError(
75
+ "WebSocket didn't accept the connection in time. Did you forget to call accept()?"
76
+ ) from e
77
+
78
+ if message["type"] == "websocket.close":
79
+ await stack.aclose()
80
+ raise WebSocketDisconnect(message["code"], message.get("reason"))
81
+
82
+ # Websocket Denial Response extension
83
+ # Ref: https://asgi.readthedocs.io/en/latest/extensions.html#websocket-denial-response
84
+ if message["type"] == "websocket.http.response.start":
85
+ status_code: int = message["status"]
86
+ headers: list[tuple[bytes, bytes]] = message["headers"]
87
+ body: list[bytes] = []
88
+ while True:
89
+ message = await self.receive()
90
+ assert message["type"] == "websocket.http.response.body"
91
+ body.append(message["body"])
92
+ if not message.get("more_body", False):
93
+ break
94
+
95
+ await stack.aclose()
96
+ raise WebSocketUpgradeError(Response(status_code, headers=headers, content=b"".join(body)))
97
+
98
+ assert message["type"] == "websocket.accept"
99
+ retval = self, self._build_accept_response(message)
100
+ self._exit_stack = stack.pop_all()
101
+ return retval
102
+
103
+ async def __aexit__(
104
+ self,
105
+ exc_type: type[BaseException] | None,
106
+ exc_val: BaseException | None,
107
+ exc_tb: TracebackType | None,
108
+ ) -> bool | None:
109
+ return await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
66
110
 
67
111
  async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
68
112
  message: Message = await self.receive(timeout=timeout)
@@ -92,7 +136,7 @@ class ASGIWebSocketAsyncNetworkStream:
92
136
  elif isinstance(event, wsproto.events.CloseConnection):
93
137
  await self.send(
94
138
  {
95
- "type": "websocket.close",
139
+ "type": "websocket.disconnect",
96
140
  "code": event.code,
97
141
  "reason": event.reason,
98
142
  }
@@ -105,24 +149,27 @@ class ASGIWebSocketAsyncNetworkStream:
105
149
  raise UnhandledWebSocketEvent(event)
106
150
 
107
151
  async def aclose(self) -> None:
108
- await self.send({"type": "websocket.close"})
109
- self.exit_stack.close()
152
+ with contextlib.suppress(anyio.ClosedResourceError):
153
+ await self.send({"type": "websocket.disconnect"})
154
+ await self._receive_queue.aclose()
155
+ await self._send_queue.aclose()
110
156
 
111
157
  async def send(self, message: Message) -> None:
112
- self._receive_queue.put(message)
158
+ await self._receive_queue.send(message)
113
159
 
114
160
  async def receive(self, timeout: float | None = None) -> Message:
115
- while self._send_queue.empty():
116
- await anyio.sleep(0)
117
- return self._send_queue.get(timeout=timeout)
161
+ if timeout is None:
162
+ timeout = math.inf
163
+ with anyio.fail_after(timeout):
164
+ return await self._send_queue.receive()
118
165
 
119
166
  async def _run(self) -> None:
120
167
  """
121
168
  The sub-thread in which the websocket session runs.
122
169
  """
123
170
  scope = self.scope
124
- receive = self._asgi_receive
125
- send = self._asgi_send
171
+ receive = self._receive_queue.receive
172
+ send = self._send_queue.send
126
173
  try:
127
174
  await self.app(scope, receive, send)
128
175
  except Exception as e:
@@ -131,15 +178,8 @@ class ASGIWebSocketAsyncNetworkStream:
131
178
  "code": CloseReason.INTERNAL_ERROR,
132
179
  "reason": str(e),
133
180
  }
134
- await self._asgi_send(message)
135
-
136
- async def _asgi_receive(self) -> Message:
137
- while self._receive_queue.empty():
138
- await anyio.sleep(0)
139
- return self._receive_queue.get()
140
-
141
- async def _asgi_send(self, message: Message) -> None:
142
- self._send_queue.put(message)
181
+ with contextlib.suppress(anyio.ClosedResourceError):
182
+ await send(message)
143
183
 
144
184
  def _build_accept_response(self, message: Message) -> bytes:
145
185
  subprotocol = message.get("subprotocol", None)
@@ -159,9 +199,28 @@ class ASGIWebSocketTransport(ASGITransport):
159
199
  raise_app_exceptions: bool = True,
160
200
  root_path: str = "",
161
201
  client: tuple[str, int] = ("127.0.0.1", 123),
202
+ initial_receive_timeout: float = 1.0,
162
203
  ) -> None:
163
204
  super().__init__(app, raise_app_exceptions, root_path, client)
164
- self.exit_stack: contextlib.AsyncExitStack | None = None
205
+ self._exit_stack: contextlib.AsyncExitStack | None = None
206
+ self._initial_receive_timeout = initial_receive_timeout
207
+
208
+ async def __aenter__(self) -> ASGIWebSocketTransport:
209
+ async with contextlib.AsyncExitStack() as stack:
210
+ self._task_group = await stack.enter_async_context(anyio.create_task_group())
211
+ self._exit_stack = stack.pop_all()
212
+
213
+ return self
214
+
215
+ async def __aexit__(
216
+ self,
217
+ exc_type: type[BaseException] | None = None,
218
+ exc_val: BaseException | None = None,
219
+ exc_tb: TracebackType | None = None,
220
+ ) -> None:
221
+ await super().__aexit__(exc_type, exc_val, exc_tb)
222
+ assert self._exit_stack is not None
223
+ await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
165
224
 
166
225
  async def handle_async_request(self, request: Request) -> Response:
167
226
  scheme = request.url.scheme
@@ -188,6 +247,21 @@ class ASGIWebSocketTransport(ASGITransport):
188
247
 
189
248
  return await super().handle_async_request(request)
190
249
 
250
+ async def _create_asgi_websocket_async_network_stream(
251
+ self,
252
+ *,
253
+ task_status: anyio.abc.TaskStatus[tuple[ASGIWebSocketAsyncNetworkStream, bytes]],
254
+ ) -> None:
255
+ stream = ASGIWebSocketAsyncNetworkStream(
256
+ self.app, # type: ignore[arg-type]
257
+ self.scope,
258
+ self._task_group,
259
+ self._initial_receive_timeout,
260
+ )
261
+ assert self._exit_stack is not None
262
+ result = await self._exit_stack.enter_async_context(stream)
263
+ task_status.started(result)
264
+
191
265
  async def _handle_ws_request(
192
266
  self,
193
267
  request: Request,
@@ -196,11 +270,7 @@ class ASGIWebSocketTransport(ASGITransport):
196
270
  assert isinstance(request.stream, AsyncByteStream)
197
271
 
198
272
  self.scope = scope
199
- self.exit_stack = contextlib.AsyncExitStack()
200
- stream, accept_response = await self.exit_stack.enter_async_context(
201
- ASGIWebSocketAsyncNetworkStream(self.app, self.scope) # type: ignore[arg-type]
202
- )
203
-
273
+ stream, accept_response = await self._task_group.start(self._create_asgi_websocket_async_network_stream)
204
274
  accept_response_lines = accept_response.decode("utf-8").splitlines()
205
275
  headers = [
206
276
  typing.cast(tuple[str, str], line.split(": ", 1))
@@ -213,7 +283,3 @@ class ASGIWebSocketTransport(ASGITransport):
213
283
  headers=headers,
214
284
  extensions={"network_stream": stream},
215
285
  )
216
-
217
- async def aclose(self) -> None:
218
- if self.exit_stack:
219
- await self.exit_stack.aclose()
@@ -46,7 +46,7 @@ dynamic = ["readme", "version", "dependencies"]
46
46
  dependencies = [
47
47
  "truststore>=0.10",
48
48
  "httpcore2=={{ version }}",
49
- "anyio",
49
+ "anyio>=4.10",
50
50
  "idna>=3.18",
51
51
  "typing_extensions>=4.5.0; python_version < '3.13'",
52
52
  ]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes