_base_channel.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. # Copyright 2020 The gRPC Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Abstract base classes for Channel objects and Multicallable objects."""
  15. import abc
  16. from typing import Generic, Optional
  17. import grpc
  18. from . import _base_call
  19. from ._typing import DeserializingFunction
  20. from ._typing import MetadataType
  21. from ._typing import RequestIterableType
  22. from ._typing import RequestType
  23. from ._typing import ResponseType
  24. from ._typing import SerializingFunction
  25. class UnaryUnaryMultiCallable(Generic[RequestType, ResponseType], abc.ABC):
  26. """Enables asynchronous invocation of a unary-call RPC."""
  27. @abc.abstractmethod
  28. def __call__(
  29. self,
  30. request: RequestType,
  31. *,
  32. timeout: Optional[float] = None,
  33. metadata: Optional[MetadataType] = None,
  34. credentials: Optional[grpc.CallCredentials] = None,
  35. wait_for_ready: Optional[bool] = None,
  36. compression: Optional[grpc.Compression] = None,
  37. ) -> _base_call.UnaryUnaryCall[RequestType, ResponseType]:
  38. """Asynchronously invokes the underlying RPC.
  39. Args:
  40. request: The request value for the RPC.
  41. timeout: An optional duration of time in seconds to allow
  42. for the RPC.
  43. metadata: Optional :term:`metadata` to be transmitted to the
  44. service-side of the RPC.
  45. credentials: An optional CallCredentials for the RPC. Only valid for
  46. secure Channel.
  47. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  48. compression: An element of grpc.compression, e.g.
  49. grpc.compression.Gzip.
  50. Returns:
  51. A UnaryUnaryCall object.
  52. Raises:
  53. RpcError: Indicates that the RPC terminated with non-OK status. The
  54. raised RpcError will also be a Call for the RPC affording the RPC's
  55. metadata, status code, and details.
  56. """
  57. class UnaryStreamMultiCallable(Generic[RequestType, ResponseType], abc.ABC):
  58. """Enables asynchronous invocation of a server-streaming RPC."""
  59. @abc.abstractmethod
  60. def __call__(
  61. self,
  62. request: RequestType,
  63. *,
  64. timeout: Optional[float] = None,
  65. metadata: Optional[MetadataType] = None,
  66. credentials: Optional[grpc.CallCredentials] = None,
  67. wait_for_ready: Optional[bool] = None,
  68. compression: Optional[grpc.Compression] = None,
  69. ) -> _base_call.UnaryStreamCall[RequestType, ResponseType]:
  70. """Asynchronously invokes the underlying RPC.
  71. Args:
  72. request: The request value for the RPC.
  73. timeout: An optional duration of time in seconds to allow
  74. for the RPC.
  75. metadata: Optional :term:`metadata` to be transmitted to the
  76. service-side of the RPC.
  77. credentials: An optional CallCredentials for the RPC. Only valid for
  78. secure Channel.
  79. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  80. compression: An element of grpc.compression, e.g.
  81. grpc.compression.Gzip.
  82. Returns:
  83. A UnaryStreamCall object.
  84. Raises:
  85. RpcError: Indicates that the RPC terminated with non-OK status. The
  86. raised RpcError will also be a Call for the RPC affording the RPC's
  87. metadata, status code, and details.
  88. """
  89. class StreamUnaryMultiCallable(abc.ABC):
  90. """Enables asynchronous invocation of a client-streaming RPC."""
  91. @abc.abstractmethod
  92. def __call__(
  93. self,
  94. request_iterator: Optional[RequestIterableType] = None,
  95. timeout: Optional[float] = None,
  96. metadata: Optional[MetadataType] = None,
  97. credentials: Optional[grpc.CallCredentials] = None,
  98. wait_for_ready: Optional[bool] = None,
  99. compression: Optional[grpc.Compression] = None,
  100. ) -> _base_call.StreamUnaryCall:
  101. """Asynchronously invokes the underlying RPC.
  102. Args:
  103. request_iterator: An optional async iterable or iterable of request
  104. messages for the RPC.
  105. timeout: An optional duration of time in seconds to allow
  106. for the RPC.
  107. metadata: Optional :term:`metadata` to be transmitted to the
  108. service-side of the RPC.
  109. credentials: An optional CallCredentials for the RPC. Only valid for
  110. secure Channel.
  111. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  112. compression: An element of grpc.compression, e.g.
  113. grpc.compression.Gzip.
  114. Returns:
  115. A StreamUnaryCall object.
  116. Raises:
  117. RpcError: Indicates that the RPC terminated with non-OK status. The
  118. raised RpcError will also be a Call for the RPC affording the RPC's
  119. metadata, status code, and details.
  120. """
  121. class StreamStreamMultiCallable(abc.ABC):
  122. """Enables asynchronous invocation of a bidirectional-streaming RPC."""
  123. @abc.abstractmethod
  124. def __call__(
  125. self,
  126. request_iterator: Optional[RequestIterableType] = None,
  127. timeout: Optional[float] = None,
  128. metadata: Optional[MetadataType] = None,
  129. credentials: Optional[grpc.CallCredentials] = None,
  130. wait_for_ready: Optional[bool] = None,
  131. compression: Optional[grpc.Compression] = None,
  132. ) -> _base_call.StreamStreamCall:
  133. """Asynchronously invokes the underlying RPC.
  134. Args:
  135. request_iterator: An optional async iterable or iterable of request
  136. messages for the RPC.
  137. timeout: An optional duration of time in seconds to allow
  138. for the RPC.
  139. metadata: Optional :term:`metadata` to be transmitted to the
  140. service-side of the RPC.
  141. credentials: An optional CallCredentials for the RPC. Only valid for
  142. secure Channel.
  143. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  144. compression: An element of grpc.compression, e.g.
  145. grpc.compression.Gzip.
  146. Returns:
  147. A StreamStreamCall object.
  148. Raises:
  149. RpcError: Indicates that the RPC terminated with non-OK status. The
  150. raised RpcError will also be a Call for the RPC affording the RPC's
  151. metadata, status code, and details.
  152. """
  153. class Channel(abc.ABC):
  154. """Enables asynchronous RPC invocation as a client.
  155. Channel objects implement the Asynchronous Context Manager (aka. async
  156. with) type, although they are not supported to be entered and exited
  157. multiple times.
  158. """
  159. @abc.abstractmethod
  160. async def __aenter__(self):
  161. """Starts an asynchronous context manager.
  162. Returns:
  163. Channel the channel that was instantiated.
  164. """
  165. @abc.abstractmethod
  166. async def __aexit__(self, exc_type, exc_val, exc_tb):
  167. """Finishes the asynchronous context manager by closing the channel.
  168. Still active RPCs will be cancelled.
  169. """
  170. @abc.abstractmethod
  171. async def close(self, grace: Optional[float] = None):
  172. """Closes this Channel and releases all resources held by it.
  173. This method immediately stops the channel from executing new RPCs in
  174. all cases.
  175. If a grace period is specified, this method waits until all active
  176. RPCs are finished or until the grace period is reached. RPCs that haven't
  177. been terminated within the grace period are aborted.
  178. If a grace period is not specified (by passing None for grace),
  179. all existing RPCs are cancelled immediately.
  180. This method is idempotent.
  181. """
  182. @abc.abstractmethod
  183. def get_state(
  184. self, try_to_connect: bool = False
  185. ) -> grpc.ChannelConnectivity:
  186. """Checks the connectivity state of a channel.
  187. This is an EXPERIMENTAL API.
  188. If the channel reaches a stable connectivity state, it is guaranteed
  189. that the return value of this function will eventually converge to that
  190. state.
  191. Args:
  192. try_to_connect: a bool indicate whether the Channel should try to
  193. connect to peer or not.
  194. Returns: A ChannelConnectivity object.
  195. """
  196. @abc.abstractmethod
  197. async def wait_for_state_change(
  198. self,
  199. last_observed_state: grpc.ChannelConnectivity,
  200. ) -> None:
  201. """Waits for a change in connectivity state.
  202. This is an EXPERIMENTAL API.
  203. The function blocks until there is a change in the channel connectivity
  204. state from the "last_observed_state". If the state is already
  205. different, this function will return immediately.
  206. There is an inherent race between the invocation of
  207. "Channel.wait_for_state_change" and "Channel.get_state". The state can
  208. change arbitrary many times during the race, so there is no way to
  209. observe every state transition.
  210. If there is a need to put a timeout for this function, please refer to
  211. "asyncio.wait_for".
  212. Args:
  213. last_observed_state: A grpc.ChannelConnectivity object representing
  214. the last known state.
  215. """
  216. @abc.abstractmethod
  217. async def channel_ready(self) -> None:
  218. """Creates a coroutine that blocks until the Channel is READY."""
  219. @abc.abstractmethod
  220. def unary_unary(
  221. self,
  222. method: str,
  223. request_serializer: Optional[SerializingFunction] = None,
  224. response_deserializer: Optional[DeserializingFunction] = None,
  225. _registered_method: Optional[bool] = False,
  226. ) -> UnaryUnaryMultiCallable:
  227. """Creates a UnaryUnaryMultiCallable for a unary-unary method.
  228. Args:
  229. method: The name of the RPC method.
  230. request_serializer: Optional :term:`serializer` for serializing the request
  231. message. Request goes unserialized in case None is passed.
  232. response_deserializer: Optional :term:`deserializer` for deserializing the
  233. response message. Response goes undeserialized in case None
  234. is passed.
  235. _registered_method: Implementation Private. Optional: A bool representing
  236. whether the method is registered.
  237. Returns:
  238. A UnaryUnaryMultiCallable value for the named unary-unary method.
  239. """
  240. @abc.abstractmethod
  241. def unary_stream(
  242. self,
  243. method: str,
  244. request_serializer: Optional[SerializingFunction] = None,
  245. response_deserializer: Optional[DeserializingFunction] = None,
  246. _registered_method: Optional[bool] = False,
  247. ) -> UnaryStreamMultiCallable:
  248. """Creates a UnaryStreamMultiCallable for a unary-stream method.
  249. Args:
  250. method: The name of the RPC method.
  251. request_serializer: Optional :term:`serializer` for serializing the request
  252. message. Request goes unserialized in case None is passed.
  253. response_deserializer: Optional :term:`deserializer` for deserializing the
  254. response message. Response goes undeserialized in case None
  255. is passed.
  256. _registered_method: Implementation Private. Optional: A bool representing
  257. whether the method is registered.
  258. Returns:
  259. A UnaryStreamMultiCallable value for the named unary-stream method.
  260. """
  261. @abc.abstractmethod
  262. def stream_unary(
  263. self,
  264. method: str,
  265. request_serializer: Optional[SerializingFunction] = None,
  266. response_deserializer: Optional[DeserializingFunction] = None,
  267. _registered_method: Optional[bool] = False,
  268. ) -> StreamUnaryMultiCallable:
  269. """Creates a StreamUnaryMultiCallable for a stream-unary method.
  270. Args:
  271. method: The name of the RPC method.
  272. request_serializer: Optional :term:`serializer` for serializing the request
  273. message. Request goes unserialized in case None is passed.
  274. response_deserializer: Optional :term:`deserializer` for deserializing the
  275. response message. Response goes undeserialized in case None
  276. is passed.
  277. _registered_method: Implementation Private. Optional: A bool representing
  278. whether the method is registered.
  279. Returns:
  280. A StreamUnaryMultiCallable value for the named stream-unary method.
  281. """
  282. @abc.abstractmethod
  283. def stream_stream(
  284. self,
  285. method: str,
  286. request_serializer: Optional[SerializingFunction] = None,
  287. response_deserializer: Optional[DeserializingFunction] = None,
  288. _registered_method: Optional[bool] = False,
  289. ) -> StreamStreamMultiCallable:
  290. """Creates a StreamStreamMultiCallable for a stream-stream method.
  291. Args:
  292. method: The name of the RPC method.
  293. request_serializer: Optional :term:`serializer` for serializing the request
  294. message. Request goes unserialized in case None is passed.
  295. response_deserializer: Optional :term:`deserializer` for deserializing the
  296. response message. Response goes undeserialized in case None
  297. is passed.
  298. _registered_method: Implementation Private. Optional: A bool representing
  299. whether the method is registered.
  300. Returns:
  301. A StreamStreamMultiCallable value for the named stream-stream method.
  302. """