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