stapled.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. from __future__ import annotations
  2. from collections.abc import Callable, Mapping, Sequence
  3. from dataclasses import dataclass
  4. from typing import Any, Generic, TypeVar
  5. from ..abc import (
  6. ByteReceiveStream,
  7. ByteSendStream,
  8. ByteStream,
  9. Listener,
  10. ObjectReceiveStream,
  11. ObjectSendStream,
  12. ObjectStream,
  13. TaskGroup,
  14. )
  15. T_Item = TypeVar("T_Item")
  16. T_Stream = TypeVar("T_Stream")
  17. @dataclass(eq=False)
  18. class StapledByteStream(ByteStream):
  19. """
  20. Combines two byte streams into a single, bidirectional byte stream.
  21. Extra attributes will be provided from both streams, with the receive stream
  22. providing the values in case of a conflict.
  23. :param ByteSendStream send_stream: the sending byte stream
  24. :param ByteReceiveStream receive_stream: the receiving byte stream
  25. """
  26. send_stream: ByteSendStream
  27. receive_stream: ByteReceiveStream
  28. async def receive(self, max_bytes: int = 65536) -> bytes:
  29. return await self.receive_stream.receive(max_bytes)
  30. async def send(self, item: bytes) -> None:
  31. await self.send_stream.send(item)
  32. async def send_eof(self) -> None:
  33. await self.send_stream.aclose()
  34. async def aclose(self) -> None:
  35. await self.send_stream.aclose()
  36. await self.receive_stream.aclose()
  37. @property
  38. def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
  39. return {
  40. **self.send_stream.extra_attributes,
  41. **self.receive_stream.extra_attributes,
  42. }
  43. @dataclass(eq=False)
  44. class StapledObjectStream(Generic[T_Item], ObjectStream[T_Item]):
  45. """
  46. Combines two object streams into a single, bidirectional object stream.
  47. Extra attributes will be provided from both streams, with the receive stream
  48. providing the values in case of a conflict.
  49. :param ObjectSendStream send_stream: the sending object stream
  50. :param ObjectReceiveStream receive_stream: the receiving object stream
  51. """
  52. send_stream: ObjectSendStream[T_Item]
  53. receive_stream: ObjectReceiveStream[T_Item]
  54. async def receive(self) -> T_Item:
  55. return await self.receive_stream.receive()
  56. async def send(self, item: T_Item) -> None:
  57. await self.send_stream.send(item)
  58. async def send_eof(self) -> None:
  59. await self.send_stream.aclose()
  60. async def aclose(self) -> None:
  61. await self.send_stream.aclose()
  62. await self.receive_stream.aclose()
  63. @property
  64. def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
  65. return {
  66. **self.send_stream.extra_attributes,
  67. **self.receive_stream.extra_attributes,
  68. }
  69. @dataclass(eq=False)
  70. class MultiListener(Generic[T_Stream], Listener[T_Stream]):
  71. """
  72. Combines multiple listeners into one, serving connections from all of them at once.
  73. Any MultiListeners in the given collection of listeners will have their listeners
  74. moved into this one.
  75. Extra attributes are provided from each listener, with each successive listener
  76. overriding any conflicting attributes from the previous one.
  77. :param listeners: listeners to serve
  78. :type listeners: Sequence[Listener[T_Stream]]
  79. """
  80. listeners: Sequence[Listener[T_Stream]]
  81. def __post_init__(self) -> None:
  82. listeners: list[Listener[T_Stream]] = []
  83. for listener in self.listeners:
  84. if isinstance(listener, MultiListener):
  85. listeners.extend(listener.listeners)
  86. del listener.listeners[:] # type: ignore[attr-defined]
  87. else:
  88. listeners.append(listener)
  89. self.listeners = listeners
  90. async def serve(
  91. self, handler: Callable[[T_Stream], Any], task_group: TaskGroup | None = None
  92. ) -> None:
  93. from .. import create_task_group
  94. async with create_task_group() as tg:
  95. for listener in self.listeners:
  96. tg.start_soon(listener.serve, handler, task_group)
  97. async def aclose(self) -> None:
  98. for listener in self.listeners:
  99. await listener.aclose()
  100. @property
  101. def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
  102. attributes: dict = {}
  103. for listener in self.listeners:
  104. attributes.update(listener.extra_attributes)
  105. return attributes