_base_server.py 12 KB

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