1 # Copyright 2020 The gRPC Authors
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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."""
17 from typing import Generic, Mapping, Optional, Iterable, Sequence
21 from ._typing import RequestType, ResponseType
22 from ._metadata import Metadata
25 class Server(abc.ABC):
29 def add_generic_rpc_handlers(
31 generic_rpc_handlers: Sequence[grpc.GenericRpcHandler]) -> None:
32 """Registers GenericRpcHandlers with this Server.
34 This method is only safe to call before the server is started.
37 generic_rpc_handlers: A sequence of GenericRpcHandlers that will be
42 def add_insecure_port(self, address: str) -> int:
43 """Opens an insecure port for accepting RPCs.
45 A port is a communication endpoint that used by networking protocols,
46 like TCP and UDP. To date, we only support TCP.
48 This method may only be called before starting the server.
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.
55 An integer port on which the server will accept RPC requests.
59 def add_secure_port(self, address: str,
60 server_credentials: grpc.ServerCredentials) -> int:
61 """Opens a secure port for accepting RPCs.
63 A port is a communication endpoint that used by networking protocols,
64 like TCP and UDP. To date, we only support TCP.
66 This method may only be called before starting the server.
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.
75 An integer port on which the server will accept RPC requests.
79 async def start(self) -> None:
80 """Starts this Server.
82 This method may only be called once. (i.e. it is not idempotent).
86 async def stop(self, grace: Optional[float]) -> None:
89 This method immediately stops the server from servicing new RPCs in
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
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).
106 grace: A duration of time in seconds or None.
110 async def wait_for_termination(self,
111 timeout: Optional[float] = None) -> bool:
112 """Continues current coroutine once the server stops.
114 This is an EXPERIMENTAL API.
116 The wait will not consume computational resources during blocking, and
117 it will block until one of the two following conditions are met:
119 1) The server is stopped or terminated;
120 2) A timeout occurs if timeout is not `None`.
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
126 timeout: A floating point number specifying a timeout for the
127 operation in seconds.
130 A bool indicates if the operation times out.
134 class ServicerContext(Generic[RequestType, ResponseType], abc.ABC):
135 """A context object passed to method implementations."""
138 async def read(self) -> RequestType:
139 """Reads one message from the RPC.
141 Only one read operation is allowed simultaneously.
144 A response message of the RPC.
147 An RpcError exception if the read failed.
151 async def write(self, message: ResponseType) -> None:
152 """Writes one message to the RPC.
154 Only one write operation is allowed simultaneously.
157 An RpcError exception if the write failed.
161 async def send_initial_metadata(self, initial_metadata: Metadata) -> None:
162 """Sends the initial metadata value to the client.
164 This method need not be called by implementations if they have no
165 metadata to add to what the gRPC runtime will transmit.
168 initial_metadata: The initial :term:`metadata`.
174 code: grpc.StatusCode,
176 trailing_metadata: Metadata = tuple()) -> None:
177 """Raises an exception to terminate the RPC with a non-OK status.
179 The code and details passed as arguments will supercede any existing
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
191 Exception: An exception is always raised to signal the abortion the
192 RPC to the gRPC runtime.
196 async def set_trailing_metadata(self, trailing_metadata: Metadata) -> None:
197 """Sends the trailing metadata for the RPC.
199 This method need not be called by implementations if they have no
200 metadata to add to what the gRPC runtime will transmit.
203 trailing_metadata: The trailing :term:`metadata`.
207 def invocation_metadata(self) -> Optional[Metadata]:
208 """Accesses the metadata from the sent by the client.
211 The invocation :term:`metadata`.
215 def set_code(self, code: grpc.StatusCode) -> None:
216 """Sets the value to be used as status code upon RPC completion.
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.
222 code: A StatusCode object to be sent to the client.
226 def set_details(self, details: str) -> None:
227 """Sets the value to be used the as detail string upon RPC completion.
229 This method need not be called by method implementations if they have
230 no details to transmit.
233 details: A UTF-8-encodable string to be sent to the client upon
234 termination of the RPC.
238 def set_compression(self, compression: grpc.Compression) -> None:
239 """Set the compression algorithm to be used for the entire call.
241 This is an EXPERIMENTAL method.
244 compression: An element of grpc.compression, e.g.
245 grpc.compression.Gzip.
249 def disable_next_message_compression(self) -> None:
250 """Disables compression for the next response message.
252 This is an EXPERIMENTAL method.
254 This method will override any compression configuration set during
255 server creation or set on the call.
259 def peer(self) -> str:
260 """Identifies the peer that invoked the RPC being serviced.
263 A string identifying the peer that invoked the RPC being serviced.
264 The string format is determined by gRPC runtime.
268 def peer_identities(self) -> Optional[Iterable[bytes]]:
269 """Gets one or more peer identity(s).
272 servicer_context.auth_context().get(servicer_context.peer_identity_key())
275 An iterable of the identities, or None if the call is not
276 authenticated. Each identity is returned as a raw bytes type.
280 def peer_identity_key(self) -> Optional[str]:
281 """The auth property used to identify the peer.
283 For example, "x509_common_name" or "x509_subject_alternative_name" are
284 used to identify an SSL peer.
287 The auth property (string) that indicates the
288 peer identity, or None if the call is not authenticated.
292 def auth_context(self) -> Mapping[str, Iterable[bytes]]:
293 """Gets the auth context for the call.
296 A map of strings to an iterable of bytes for each auth property.