_base_call.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. # Copyright 2019 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 client-side Call objects.
  15. Call objects represents the RPC itself, and offer methods to access / modify
  16. its information. They also offer methods to manipulate the life-cycle of the
  17. RPC, e.g. cancellation.
  18. """
  19. from abc import ABCMeta
  20. from abc import abstractmethod
  21. from typing import Any, AsyncIterator, Generator, Generic, Optional, Union
  22. import grpc
  23. from ._metadata import Metadata
  24. from ._typing import DoneCallbackType
  25. from ._typing import EOFType
  26. from ._typing import RequestType
  27. from ._typing import ResponseType
  28. __all__ = "RpcContext", "Call", "UnaryUnaryCall", "UnaryStreamCall"
  29. class RpcContext(metaclass=ABCMeta):
  30. """Provides RPC-related information and action."""
  31. @abstractmethod
  32. def cancelled(self) -> bool:
  33. """Return True if the RPC is cancelled.
  34. The RPC is cancelled when the cancellation was requested with cancel().
  35. Returns:
  36. A bool indicates whether the RPC is cancelled or not.
  37. """
  38. @abstractmethod
  39. def done(self) -> bool:
  40. """Return True if the RPC is done.
  41. An RPC is done if the RPC is completed, cancelled or aborted.
  42. Returns:
  43. A bool indicates if the RPC is done.
  44. """
  45. @abstractmethod
  46. def time_remaining(self) -> Optional[float]:
  47. """Describes the length of allowed time remaining for the RPC.
  48. Returns:
  49. A nonnegative float indicating the length of allowed time in seconds
  50. remaining for the RPC to complete before it is considered to have
  51. timed out, or None if no deadline was specified for the RPC.
  52. """
  53. @abstractmethod
  54. def cancel(self) -> bool:
  55. """Cancels the RPC.
  56. Idempotent and has no effect if the RPC has already terminated.
  57. Returns:
  58. A bool indicates if the cancellation is performed or not.
  59. """
  60. @abstractmethod
  61. def add_done_callback(self, callback: DoneCallbackType) -> None:
  62. """Registers a callback to be called on RPC termination.
  63. Args:
  64. callback: A callable object will be called with the call object as
  65. its only argument.
  66. """
  67. class Call(RpcContext, metaclass=ABCMeta):
  68. """The abstract base class of an RPC on the client-side."""
  69. @abstractmethod
  70. async def initial_metadata(self) -> Metadata:
  71. """Accesses the initial metadata sent by the server.
  72. Returns:
  73. The initial :term:`metadata`.
  74. """
  75. @abstractmethod
  76. async def trailing_metadata(self) -> Metadata:
  77. """Accesses the trailing metadata sent by the server.
  78. Returns:
  79. The trailing :term:`metadata`.
  80. """
  81. @abstractmethod
  82. async def code(self) -> grpc.StatusCode:
  83. """Accesses the status code sent by the server.
  84. Returns:
  85. The StatusCode value for the RPC.
  86. """
  87. @abstractmethod
  88. async def details(self) -> str:
  89. """Accesses the details sent by the server.
  90. Returns:
  91. The details string of the RPC.
  92. """
  93. @abstractmethod
  94. async def wait_for_connection(self) -> None:
  95. """Waits until connected to peer and raises aio.AioRpcError if failed.
  96. This is an EXPERIMENTAL method.
  97. This method ensures the RPC has been successfully connected. Otherwise,
  98. an AioRpcError will be raised to explain the reason of the connection
  99. failure.
  100. This method is recommended for building retry mechanisms.
  101. """
  102. class UnaryUnaryCall(
  103. Generic[RequestType, ResponseType], Call, metaclass=ABCMeta
  104. ):
  105. """The abstract base class of a unary-unary RPC on the client-side."""
  106. @abstractmethod
  107. def __await__(self) -> Generator[Any, None, ResponseType]:
  108. """Await the response message to be ready.
  109. Returns:
  110. The response message of the RPC.
  111. """
  112. class UnaryStreamCall(
  113. Generic[RequestType, ResponseType], Call, metaclass=ABCMeta
  114. ):
  115. @abstractmethod
  116. def __aiter__(self) -> AsyncIterator[ResponseType]:
  117. """Returns the async iterator representation that yields messages.
  118. Under the hood, it is calling the "read" method.
  119. Returns:
  120. An async iterator object that yields messages.
  121. """
  122. @abstractmethod
  123. async def read(self) -> Union[EOFType, ResponseType]:
  124. """Reads one message from the stream.
  125. Read operations must be serialized when called from multiple
  126. coroutines.
  127. Note that the iterator and read/write APIs may not be mixed on
  128. a single RPC.
  129. Returns:
  130. A response message, or an `grpc.aio.EOF` to indicate the end of the
  131. stream.
  132. """
  133. class StreamUnaryCall(
  134. Generic[RequestType, ResponseType], Call, metaclass=ABCMeta
  135. ):
  136. @abstractmethod
  137. async def write(self, request: RequestType) -> None:
  138. """Writes one message to the stream.
  139. Note that the iterator and read/write APIs may not be mixed on
  140. a single RPC.
  141. Raises:
  142. An RpcError exception if the write failed.
  143. """
  144. @abstractmethod
  145. async def done_writing(self) -> None:
  146. """Notifies server that the client is done sending messages.
  147. After done_writing is called, any additional invocation to the write
  148. function will fail. This function is idempotent.
  149. """
  150. @abstractmethod
  151. def __await__(self) -> Generator[Any, None, ResponseType]:
  152. """Await the response message to be ready.
  153. Returns:
  154. The response message of the stream.
  155. """
  156. class StreamStreamCall(
  157. Generic[RequestType, ResponseType], Call, metaclass=ABCMeta
  158. ):
  159. @abstractmethod
  160. def __aiter__(self) -> AsyncIterator[ResponseType]:
  161. """Returns the async iterator representation that yields messages.
  162. Under the hood, it is calling the "read" method.
  163. Returns:
  164. An async iterator object that yields messages.
  165. """
  166. @abstractmethod
  167. async def read(self) -> Union[EOFType, ResponseType]:
  168. """Reads one message from the stream.
  169. Read operations must be serialized when called from multiple
  170. coroutines.
  171. Note that the iterator and read/write APIs may not be mixed on
  172. a single RPC.
  173. Returns:
  174. A response message, or an `grpc.aio.EOF` to indicate the end of the
  175. stream.
  176. """
  177. @abstractmethod
  178. async def write(self, request: RequestType) -> None:
  179. """Writes one message to the stream.
  180. Note that the iterator and read/write APIs may not be mixed on
  181. a single RPC.
  182. Raises:
  183. An RpcError exception if the write failed.
  184. """
  185. @abstractmethod
  186. async def done_writing(self) -> None:
  187. """Notifies server that the client is done sending messages.
  188. After done_writing is called, any additional invocation to the write
  189. function will fail. This function is idempotent.
  190. """