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
16import abc
17from typing import Generic, Iterable, Mapping, NoReturn, Optional, Sequence
18
19import grpc
20
21from ._metadata import Metadata # pylint: disable=unused-import
22from ._typing import DoneCallbackType
23from ._typing import MetadataType
24from ._typing import RequestType
25from ._typing import ResponseType
26
27
28class Server(abc.ABC):
29 """Serves RPCs."""
30
31 @abc.abstractmethod
32 def add_generic_rpc_handlers(
33 self, generic_rpc_handlers: Sequence[grpc.GenericRpcHandler]
34 ) -> None:
35 """Registers GenericRpcHandlers with this Server.
36
37 This method is only safe to call before the server is started.
38
39 Args:
40 generic_rpc_handlers: A sequence of GenericRpcHandlers that will be
41 used to service RPCs.
42 """
43
44 @abc.abstractmethod
45 def add_insecure_port(self, address: str) -> int:
46 """Opens an insecure port for accepting RPCs.
47
48 A port is a communication endpoint that used by networking protocols,
49 like TCP and UDP. To date, we only support TCP.
50
51 This method may only be called before starting the server.
52
53 Args:
54 address: The address for which to open a port. If the port is 0,
55 or not specified in the address, then the gRPC runtime will choose a port.
56
57 Returns:
58 An integer port on which the server will accept RPC requests.
59 """
60
61 @abc.abstractmethod
62 def add_secure_port(
63 self, address: str, server_credentials: grpc.ServerCredentials
64 ) -> int:
65 """Opens a secure port for accepting RPCs.
66
67 A port is a communication endpoint that used by networking protocols,
68 like TCP and UDP. To date, we only support TCP.
69
70 This method may only be called before starting the server.
71
72 Args:
73 address: The address for which to open a port.
74 if the port is 0, or not specified in the address, then the gRPC
75 runtime will choose a port.
76 server_credentials: A ServerCredentials object.
77
78 Returns:
79 An integer port on which the server will accept RPC requests.
80 """
81
82 @abc.abstractmethod
83 async def start(self) -> None:
84 """Starts this Server.
85
86 This method may only be called once. (i.e. it is not idempotent).
87 """
88
89 @abc.abstractmethod
90 async def stop(self, grace: Optional[float]) -> None:
91 """Stops this Server.
92
93 This method immediately stops the server from servicing new RPCs in
94 all cases.
95
96 If a grace period is specified, this method waits until all active
97 RPCs are finished or until the grace period is reached. RPCs that haven't
98 been terminated within the grace period are aborted.
99 If a grace period is not specified (by passing None for grace), all
100 existing RPCs are aborted immediately and this method blocks until
101 the last RPC handler terminates.
102
103 This method is idempotent and may be called at any time. Passing a
104 smaller grace value in a subsequent call will have the effect of
105 stopping the Server sooner (passing None will have the effect of
106 stopping the server immediately). Passing a larger grace value in a
107 subsequent call will not have the effect of stopping the server later
108 (i.e. the most restrictive grace value is used).
109
110 Args:
111 grace: A duration of time in seconds or None.
112 """
113
114 @abc.abstractmethod
115 async def wait_for_termination(
116 self, timeout: Optional[float] = None
117 ) -> bool:
118 """Continues current coroutine once the server stops.
119
120 This is an EXPERIMENTAL API.
121
122 The wait will not consume computational resources during blocking, and
123 it will block until one of the two following conditions are met:
124
125 1) The server is stopped or terminated;
126 2) A timeout occurs if timeout is not `None`.
127
128 The timeout argument works in the same way as `threading.Event.wait()`.
129 https://docs.python.org/3/library/threading.html#threading.Event.wait
130
131 Args:
132 timeout: A floating point number specifying a timeout for the
133 operation in seconds.
134
135 Returns:
136 A bool indicates if the operation times out.
137 """
138
139 def add_registered_method_handlers( # noqa: B027
140 self, service_name, method_handlers
141 ):
142 """Registers GenericRpcHandlers with this Server.
143
144 This method is only safe to call before the server is started.
145
146 Args:
147 service_name: The service name.
148 method_handlers: A dictionary that maps method names to corresponding
149 RpcMethodHandler.
150 """
151
152
153# pylint: disable=too-many-public-methods
154class ServicerContext(Generic[RequestType, ResponseType], abc.ABC):
155 """A context object passed to method implementations."""
156
157 @abc.abstractmethod
158 async def read(self) -> RequestType:
159 """Reads one message from the RPC.
160
161 Only one read operation is allowed simultaneously.
162
163 Returns:
164 A response message of the RPC.
165
166 Raises:
167 An RpcError exception if the read failed.
168 """
169
170 @abc.abstractmethod
171 async def write(self, message: ResponseType) -> None:
172 """Writes one message to the RPC.
173
174 Only one write operation is allowed simultaneously.
175
176 Raises:
177 An RpcError exception if the write failed.
178 """
179
180 @abc.abstractmethod
181 async def send_initial_metadata(
182 self, initial_metadata: MetadataType
183 ) -> None:
184 """Sends the initial metadata value to the client.
185
186 This method need not be called by implementations if they have no
187 metadata to add to what the gRPC runtime will transmit.
188
189 Args:
190 initial_metadata: The initial :term:`metadata`.
191 """
192
193 @abc.abstractmethod
194 async def abort(
195 self,
196 code: grpc.StatusCode,
197 details: str = "",
198 trailing_metadata: MetadataType = (),
199 ) -> NoReturn:
200 """Raises an exception to terminate the RPC with a non-OK status.
201
202 The code and details passed as arguments will supersede any existing
203 ones.
204
205 Args:
206 code: A StatusCode object to be sent to the client.
207 It must not be StatusCode.OK.
208 details: A UTF-8-encodable string to be sent to the client upon
209 termination of the RPC.
210 trailing_metadata: A sequence of tuple represents the trailing
211 :term:`metadata`.
212
213 Raises:
214 Exception: An exception is always raised to signal the abortion the
215 RPC to the gRPC runtime.
216 """
217 raise NotImplementedError()
218
219 @abc.abstractmethod
220 async def abort_with_status(self, status: grpc.Status) -> NoReturn:
221 """Raises an exception to terminate the RPC with a non-OK status.
222
223 The status passed as argument will supersede any existing status code,
224 status message and trailing metadata.
225
226 This is an EXPERIMENTAL API.
227
228 Args:
229 status: A grpc.Status object. The status code in it must not be
230 StatusCode.OK.
231
232 Raises:
233 Exception: An exception is always raised to signal the abortion of the
234 RPC to the gRPC runtime.
235 """
236 raise NotImplementedError()
237
238 @abc.abstractmethod
239 def set_trailing_metadata(self, trailing_metadata: MetadataType) -> None:
240 """Sends the trailing metadata for the RPC.
241
242 This method need not be called by implementations if they have no
243 metadata to add to what the gRPC runtime will transmit.
244
245 Args:
246 trailing_metadata: The trailing :term:`metadata`.
247 """
248
249 @abc.abstractmethod
250 def invocation_metadata(self) -> Optional[MetadataType]:
251 """Accesses the metadata sent by the client.
252
253 Returns:
254 The invocation :term:`metadata`.
255 """
256
257 @abc.abstractmethod
258 def set_code(self, code: grpc.StatusCode) -> None:
259 """Sets the value to be used as status code upon RPC completion.
260
261 This method need not be called by method implementations if they wish
262 the gRPC runtime to determine the status code of the RPC.
263
264 Args:
265 code: A StatusCode object to be sent to the client.
266 """
267
268 @abc.abstractmethod
269 def set_details(self, details: str) -> None:
270 """Sets the value to be used the as detail string upon RPC completion.
271
272 This method need not be called by method implementations if they have
273 no details to transmit.
274
275 Args:
276 details: A UTF-8-encodable string to be sent to the client upon
277 termination of the RPC.
278 """
279
280 @abc.abstractmethod
281 def set_compression(self, compression: grpc.Compression) -> None:
282 """Set the compression algorithm to be used for the entire call.
283
284 Args:
285 compression: An element of grpc.compression, e.g.
286 grpc.compression.Gzip.
287 """
288
289 @abc.abstractmethod
290 def disable_next_message_compression(self) -> None:
291 """Disables compression for the next response message.
292
293 This method will override any compression configuration set during
294 server creation or set on the call.
295 """
296
297 @abc.abstractmethod
298 def peer(self) -> str:
299 """Identifies the peer that invoked the RPC being serviced.
300
301 Returns:
302 A string identifying the peer that invoked the RPC being serviced.
303 The string format is determined by gRPC runtime.
304 """
305
306 @abc.abstractmethod
307 def peer_identities(self) -> Optional[Iterable[bytes]]:
308 """Gets one or more peer identity(s).
309
310 Equivalent to
311 servicer_context.auth_context().get(servicer_context.peer_identity_key())
312
313 Returns:
314 An iterable of the identities, or None if the call is not
315 authenticated. Each identity is returned as a raw bytes type.
316 """
317
318 @abc.abstractmethod
319 def peer_identity_key(self) -> Optional[str]:
320 """The auth property used to identify the peer.
321
322 For example, "x509_common_name" or "x509_subject_alternative_name" are
323 used to identify an SSL peer.
324
325 Returns:
326 The auth property (string) that indicates the
327 peer identity, or None if the call is not authenticated.
328 """
329
330 @abc.abstractmethod
331 def auth_context(self) -> Mapping[str, Iterable[bytes]]:
332 """Gets the auth context for the call.
333
334 Returns:
335 A map of strings to an iterable of bytes for each auth property.
336 """
337
338 def time_remaining(self) -> float:
339 """Describes the length of allowed time remaining for the RPC.
340
341 Returns:
342 A nonnegative float indicating the length of allowed time in seconds
343 remaining for the RPC to complete before it is considered to have
344 timed out, or None if no deadline was specified for the RPC.
345 """
346 raise NotImplementedError()
347
348 def trailing_metadata(self):
349 """Access value to be used as trailing metadata upon RPC completion.
350
351 This is an EXPERIMENTAL API.
352
353 Returns:
354 The trailing :term:`metadata` for the RPC.
355 """
356 raise NotImplementedError()
357
358 def code(self):
359 """Accesses the value to be used as status code upon RPC completion.
360
361 This is an EXPERIMENTAL API.
362
363 Returns:
364 The StatusCode value for the RPC.
365 """
366 raise NotImplementedError()
367
368 def details(self):
369 """Accesses the value to be used as detail string upon RPC completion.
370
371 This is an EXPERIMENTAL API.
372
373 Returns:
374 The details string of the RPC.
375 """
376 raise NotImplementedError()
377
378 def add_done_callback(self, callback: DoneCallbackType) -> None:
379 """Registers a callback to be called on RPC termination.
380
381 This is an EXPERIMENTAL API.
382
383 Args:
384 callback: A callable object will be called with the servicer context
385 object as its only argument.
386 """
387
388 def cancelled(self) -> bool:
389 """Return True if the RPC is cancelled.
390
391 The RPC is cancelled when the cancellation was requested with cancel().
392
393 This is an EXPERIMENTAL API.
394
395 Returns:
396 A bool indicates whether the RPC is cancelled or not.
397 """
398 raise NotImplementedError()
399
400 def done(self) -> bool:
401 """Return True if the RPC is done.
402
403 An RPC is done if the RPC is completed, cancelled or aborted.
404
405 This is an EXPERIMENTAL API.
406
407 Returns:
408 A bool indicates if the RPC is done.
409 """
410 raise NotImplementedError()