_base_server.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 server-side classes."""
  15. import abc
  16. from typing import Generic, Iterable, Mapping, Optional, Sequence
  17. import grpc
  18. from ._metadata import Metadata
  19. from ._typing import DoneCallbackType
  20. from ._typing import MetadataType
  21. from ._typing import RequestType
  22. from ._typing import ResponseType
  23. class Server(abc.ABC):
  24. """Serves RPCs."""
  25. @abc.abstractmethod
  26. def add_generic_rpc_handlers(
  27. self,
  28. generic_rpc_handlers: Sequence[grpc.GenericRpcHandler]) -> None:
  29. """Registers GenericRpcHandlers with this Server.
  30. This method is only safe to call before the server is started.
  31. Args:
  32. generic_rpc_handlers: A sequence of GenericRpcHandlers that will be
  33. used to service RPCs.
  34. """
  35. @abc.abstractmethod
  36. def add_insecure_port(self, address: str) -> int:
  37. """Opens an insecure port for accepting RPCs.
  38. A port is a communication endpoint that used by networking protocols,
  39. like TCP and UDP. To date, we only support TCP.
  40. This method may only be called before starting the server.
  41. Args:
  42. address: The address for which to open a port. If the port is 0,
  43. or not specified in the address, then the gRPC runtime will choose a port.
  44. Returns:
  45. An integer port on which the server will accept RPC requests.
  46. """
  47. @abc.abstractmethod
  48. def add_secure_port(self, address: str,
  49. server_credentials: grpc.ServerCredentials) -> int:
  50. """Opens a secure port for accepting RPCs.
  51. A port is a communication endpoint that used by networking protocols,
  52. like TCP and UDP. To date, we only support TCP.
  53. This method may only be called before starting the server.
  54. Args:
  55. address: The address for which to open a port.
  56. if the port is 0, or not specified in the address, then the gRPC
  57. runtime will choose a port.
  58. server_credentials: A ServerCredentials object.
  59. Returns:
  60. An integer port on which the server will accept RPC requests.
  61. """
  62. @abc.abstractmethod
  63. async def start(self) -> None:
  64. """Starts this Server.
  65. This method may only be called once. (i.e. it is not idempotent).
  66. """
  67. @abc.abstractmethod
  68. async def stop(self, grace: Optional[float]) -> None:
  69. """Stops this Server.
  70. This method immediately stops the server from servicing new RPCs in
  71. all cases.
  72. If a grace period is specified, this method returns immediately and all
  73. RPCs active at the end of the grace period are aborted. If a grace
  74. period is not specified (by passing None for grace), all existing RPCs
  75. are aborted immediately and this method blocks until the last RPC
  76. handler terminates.
  77. This method is idempotent and may be called at any time. Passing a
  78. smaller grace value in a subsequent call will have the effect of
  79. stopping the Server sooner (passing None will have the effect of
  80. stopping the server immediately). Passing a larger grace value in a
  81. subsequent call will not have the effect of stopping the server later
  82. (i.e. the most restrictive grace value is used).
  83. Args:
  84. grace: A duration of time in seconds or None.
  85. """
  86. @abc.abstractmethod
  87. async def wait_for_termination(self,
  88. timeout: Optional[float] = None) -> bool:
  89. """Continues current coroutine once the server stops.
  90. This is an EXPERIMENTAL API.
  91. The wait will not consume computational resources during blocking, and
  92. it will block until one of the two following conditions are met:
  93. 1) The server is stopped or terminated;
  94. 2) A timeout occurs if timeout is not `None`.
  95. The timeout argument works in the same way as `threading.Event.wait()`.
  96. https://docs.python.org/3/library/threading.html#threading.Event.wait
  97. Args:
  98. timeout: A floating point number specifying a timeout for the
  99. operation in seconds.
  100. Returns:
  101. A bool indicates if the operation times out.
  102. """
  103. # pylint: disable=too-many-public-methods
  104. class ServicerContext(Generic[RequestType, ResponseType], abc.ABC):
  105. """A context object passed to method implementations."""
  106. @abc.abstractmethod
  107. async def read(self) -> RequestType:
  108. """Reads one message from the RPC.
  109. Only one read operation is allowed simultaneously.
  110. Returns:
  111. A response message of the RPC.
  112. Raises:
  113. An RpcError exception if the read failed.
  114. """
  115. @abc.abstractmethod
  116. async def write(self, message: ResponseType) -> None:
  117. """Writes one message to the RPC.
  118. Only one write operation is allowed simultaneously.
  119. Raises:
  120. An RpcError exception if the write failed.
  121. """
  122. @abc.abstractmethod
  123. async def send_initial_metadata(self,
  124. initial_metadata: MetadataType) -> None:
  125. """Sends the initial metadata value to the client.
  126. This method need not be called by implementations if they have no
  127. metadata to add to what the gRPC runtime will transmit.
  128. Args:
  129. initial_metadata: The initial :term:`metadata`.
  130. """
  131. @abc.abstractmethod
  132. async def abort(
  133. self,
  134. code: grpc.StatusCode,
  135. details: str = '',
  136. trailing_metadata: MetadataType = tuple()) -> None:
  137. """Raises an exception to terminate the RPC with a non-OK status.
  138. The code and details passed as arguments will supercede any existing
  139. ones.
  140. Args:
  141. code: A StatusCode object to be sent to the client.
  142. It must not be StatusCode.OK.
  143. details: A UTF-8-encodable string to be sent to the client upon
  144. termination of the RPC.
  145. trailing_metadata: A sequence of tuple represents the trailing
  146. :term:`metadata`.
  147. Raises:
  148. Exception: An exception is always raised to signal the abortion the
  149. RPC to the gRPC runtime.
  150. """
  151. @abc.abstractmethod
  152. def set_trailing_metadata(self, trailing_metadata: MetadataType) -> None:
  153. """Sends the trailing metadata for the RPC.
  154. This method need not be called by implementations if they have no
  155. metadata to add to what the gRPC runtime will transmit.
  156. Args:
  157. trailing_metadata: The trailing :term:`metadata`.
  158. """
  159. @abc.abstractmethod
  160. def invocation_metadata(self) -> Optional[Metadata]:
  161. """Accesses the metadata sent by the client.
  162. Returns:
  163. The invocation :term:`metadata`.
  164. """
  165. @abc.abstractmethod
  166. def set_code(self, code: grpc.StatusCode) -> None:
  167. """Sets the value to be used as status code upon RPC completion.
  168. This method need not be called by method implementations if they wish
  169. the gRPC runtime to determine the status code of the RPC.
  170. Args:
  171. code: A StatusCode object to be sent to the client.
  172. """
  173. @abc.abstractmethod
  174. def set_details(self, details: str) -> None:
  175. """Sets the value to be used the as detail string upon RPC completion.
  176. This method need not be called by method implementations if they have
  177. no details to transmit.
  178. Args:
  179. details: A UTF-8-encodable string to be sent to the client upon
  180. termination of the RPC.
  181. """
  182. @abc.abstractmethod
  183. def set_compression(self, compression: grpc.Compression) -> None:
  184. """Set the compression algorithm to be used for the entire call.
  185. This is an EXPERIMENTAL method.
  186. Args:
  187. compression: An element of grpc.compression, e.g.
  188. grpc.compression.Gzip.
  189. """
  190. @abc.abstractmethod
  191. def disable_next_message_compression(self) -> None:
  192. """Disables compression for the next response message.
  193. This is an EXPERIMENTAL method.
  194. This method will override any compression configuration set during
  195. server creation or set on the call.
  196. """
  197. @abc.abstractmethod
  198. def peer(self) -> str:
  199. """Identifies the peer that invoked the RPC being serviced.
  200. Returns:
  201. A string identifying the peer that invoked the RPC being serviced.
  202. The string format is determined by gRPC runtime.
  203. """
  204. @abc.abstractmethod
  205. def peer_identities(self) -> Optional[Iterable[bytes]]:
  206. """Gets one or more peer identity(s).
  207. Equivalent to
  208. servicer_context.auth_context().get(servicer_context.peer_identity_key())
  209. Returns:
  210. An iterable of the identities, or None if the call is not
  211. authenticated. Each identity is returned as a raw bytes type.
  212. """
  213. @abc.abstractmethod
  214. def peer_identity_key(self) -> Optional[str]:
  215. """The auth property used to identify the peer.
  216. For example, "x509_common_name" or "x509_subject_alternative_name" are
  217. used to identify an SSL peer.
  218. Returns:
  219. The auth property (string) that indicates the
  220. peer identity, or None if the call is not authenticated.
  221. """
  222. @abc.abstractmethod
  223. def auth_context(self) -> Mapping[str, Iterable[bytes]]:
  224. """Gets the auth context for the call.
  225. Returns:
  226. A map of strings to an iterable of bytes for each auth property.
  227. """
  228. def time_remaining(self) -> float:
  229. """Describes the length of allowed time remaining for the RPC.
  230. Returns:
  231. A nonnegative float indicating the length of allowed time in seconds
  232. remaining for the RPC to complete before it is considered to have
  233. timed out, or None if no deadline was specified for the RPC.
  234. """
  235. def trailing_metadata(self):
  236. """Access value to be used as trailing metadata upon RPC completion.
  237. This is an EXPERIMENTAL API.
  238. Returns:
  239. The trailing :term:`metadata` for the RPC.
  240. """
  241. raise NotImplementedError()
  242. def code(self):
  243. """Accesses the value to be used as status code upon RPC completion.
  244. This is an EXPERIMENTAL API.
  245. Returns:
  246. The StatusCode value for the RPC.
  247. """
  248. raise NotImplementedError()
  249. def details(self):
  250. """Accesses the value to be used as detail string upon RPC completion.
  251. This is an EXPERIMENTAL API.
  252. Returns:
  253. The details string of the RPC.
  254. """
  255. raise NotImplementedError()
  256. def add_done_callback(self, callback: DoneCallbackType) -> None:
  257. """Registers a callback to be called on RPC termination.
  258. This is an EXPERIMENTAL API.
  259. Args:
  260. callback: A callable object will be called with the servicer context
  261. object as its only argument.
  262. """
  263. def cancelled(self) -> bool:
  264. """Return True if the RPC is cancelled.
  265. The RPC is cancelled when the cancellation was requested with cancel().
  266. This is an EXPERIMENTAL API.
  267. Returns:
  268. A bool indicates whether the RPC is cancelled or not.
  269. """
  270. def done(self) -> bool:
  271. """Return True if the RPC is done.
  272. An RPC is done if the RPC is completed, cancelled or aborted.
  273. This is an EXPERIMENTAL API.
  274. Returns:
  275. A bool indicates if the RPC is done.
  276. """