1 # Copyright 2015-2016 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 """gRPC's Python API."""
23 from grpc._cython import cygrpc as _cygrpc
24 from grpc import _compression
26 logging.getLogger(__name__).addHandler(logging.NullHandler())
29 from grpc._grpcio_metadata import __version__
33 ############################## Future Interface ###############################
36 class FutureTimeoutError(Exception):
37 """Indicates that a method call on a Future timed out."""
40 class FutureCancelledError(Exception):
41 """Indicates that the computation underlying a Future was cancelled."""
44 class Future(six.with_metaclass(abc.ABCMeta)):
45 """A representation of a computation in another control flow.
47 Computations represented by a Future may be yet to be begun,
48 may be ongoing, or may have already completed.
53 """Attempts to cancel the computation.
55 This method does not block.
59 Returns True if the computation was canceled.
61 Returns False under all other circumstances, for example:
63 1. computation has begun and could not be canceled.
64 2. computation has finished
65 3. computation is scheduled for execution and it is impossible
66 to determine its state without blocking.
68 raise NotImplementedError()
72 """Describes whether the computation was cancelled.
74 This method does not block.
78 Returns True if the computation was cancelled before its result became
81 Returns False under all other circumstances, for example:
83 1. computation was not cancelled.
84 2. computation's result is available.
86 raise NotImplementedError()
90 """Describes whether the computation is taking place.
92 This method does not block.
95 Returns True if the computation is scheduled for execution or
98 Returns False if the computation already executed or was cancelled.
100 raise NotImplementedError()
104 """Describes whether the computation has taken place.
106 This method does not block.
110 Returns True if the computation already executed or was cancelled.
111 Returns False if the computation is scheduled for execution or
113 This is exactly opposite of the running() method's result.
115 raise NotImplementedError()
118 def result(self, timeout=None):
119 """Returns the result of the computation or raises its exception.
121 This method may return immediately or may block.
124 timeout: The length of time in seconds to wait for the computation to
125 finish or be cancelled. If None, the call will block until the
126 computations's termination.
129 The return value of the computation.
132 FutureTimeoutError: If a timeout value is passed and the computation
133 does not terminate within the allotted time.
134 FutureCancelledError: If the computation was cancelled.
135 Exception: If the computation raised an exception, this call will
136 raise the same exception.
138 raise NotImplementedError()
141 def exception(self, timeout=None):
142 """Return the exception raised by the computation.
144 This method may return immediately or may block.
147 timeout: The length of time in seconds to wait for the computation to
148 terminate or be cancelled. If None, the call will block until the
149 computations's termination.
152 The exception raised by the computation, or None if the computation
153 did not raise an exception.
156 FutureTimeoutError: If a timeout value is passed and the computation
157 does not terminate within the allotted time.
158 FutureCancelledError: If the computation was cancelled.
160 raise NotImplementedError()
163 def traceback(self, timeout=None):
164 """Access the traceback of the exception raised by the computation.
166 This method may return immediately or may block.
169 timeout: The length of time in seconds to wait for the computation
170 to terminate or be cancelled. If None, the call will block until
171 the computation's termination.
174 The traceback of the exception raised by the computation, or None
175 if the computation did not raise an exception.
178 FutureTimeoutError: If a timeout value is passed and the computation
179 does not terminate within the allotted time.
180 FutureCancelledError: If the computation was cancelled.
182 raise NotImplementedError()
185 def add_done_callback(self, fn):
186 """Adds a function to be called at completion of the computation.
188 The callback will be passed this Future object describing the outcome
189 of the computation. Callbacks will be invoked after the future is
190 terminated, whether successfully or not.
192 If the computation has already completed, the callback will be called
195 Exceptions raised in the callback will be logged at ERROR level, but
196 will not terminate any threads of execution.
199 fn: A callable taking this Future object as its single parameter.
201 raise NotImplementedError()
204 ################################ gRPC Enums ##################################
208 class ChannelConnectivity(enum.Enum):
209 """Mirrors grpc_connectivity_state in the gRPC Core.
212 IDLE: The channel is idle.
213 CONNECTING: The channel is connecting.
214 READY: The channel is ready to conduct RPCs.
215 TRANSIENT_FAILURE: The channel has seen a failure from which it expects
217 SHUTDOWN: The channel has seen a failure from which it cannot recover.
219 IDLE = (_cygrpc.ConnectivityState.idle, 'idle')
220 CONNECTING = (_cygrpc.ConnectivityState.connecting, 'connecting')
221 READY = (_cygrpc.ConnectivityState.ready, 'ready')
222 TRANSIENT_FAILURE = (_cygrpc.ConnectivityState.transient_failure,
224 SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, 'shutdown')
228 class StatusCode(enum.Enum):
229 """Mirrors grpc_status_code in the gRPC Core.
232 OK: Not an error; returned on success
233 CANCELLED: The operation was cancelled (typically by the caller).
234 UNKNOWN: Unknown error.
235 INVALID_ARGUMENT: Client specified an invalid argument.
236 DEADLINE_EXCEEDED: Deadline expired before operation could complete.
237 NOT_FOUND: Some requested entity (e.g., file or directory) was not found.
238 ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory)
240 PERMISSION_DENIED: The caller does not have permission to execute the specified
242 UNAUTHENTICATED: The request does not have valid authentication credentials for the
244 RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or
245 perhaps the entire file system is out of space.
246 FAILED_PRECONDITION: Operation was rejected because the system is not in a state
247 required for the operation's execution.
248 ABORTED: The operation was aborted, typically due to a concurrency issue
249 like sequencer check failures, transaction aborts, etc.
250 UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service.
251 INTERNAL: Internal errors. Means some invariants expected by underlying
252 system has been broken.
253 UNAVAILABLE: The service is currently unavailable.
254 DATA_LOSS: Unrecoverable data loss or corruption.
256 OK = (_cygrpc.StatusCode.ok, 'ok')
257 CANCELLED = (_cygrpc.StatusCode.cancelled, 'cancelled')
258 UNKNOWN = (_cygrpc.StatusCode.unknown, 'unknown')
259 INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, 'invalid argument')
260 DEADLINE_EXCEEDED = (_cygrpc.StatusCode.deadline_exceeded,
262 NOT_FOUND = (_cygrpc.StatusCode.not_found, 'not found')
263 ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, 'already exists')
264 PERMISSION_DENIED = (_cygrpc.StatusCode.permission_denied,
266 RESOURCE_EXHAUSTED = (_cygrpc.StatusCode.resource_exhausted,
267 'resource exhausted')
268 FAILED_PRECONDITION = (_cygrpc.StatusCode.failed_precondition,
269 'failed precondition')
270 ABORTED = (_cygrpc.StatusCode.aborted, 'aborted')
271 OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, 'out of range')
272 UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, 'unimplemented')
273 INTERNAL = (_cygrpc.StatusCode.internal, 'internal')
274 UNAVAILABLE = (_cygrpc.StatusCode.unavailable, 'unavailable')
275 DATA_LOSS = (_cygrpc.StatusCode.data_loss, 'data loss')
276 UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, 'unauthenticated')
279 ############################# gRPC Status ################################
282 class Status(six.with_metaclass(abc.ABCMeta)):
283 """Describes the status of an RPC.
285 This is an EXPERIMENTAL API.
288 code: A StatusCode object to be sent to the client.
289 details: A UTF-8-encodable string to be sent to the client upon
290 termination of the RPC.
291 trailing_metadata: The trailing :term:`metadata` in the RPC.
295 ############################# gRPC Exceptions ################################
298 class RpcError(Exception):
299 """Raised by the gRPC library to indicate non-OK-status RPC termination."""
302 ############################## Shared Context ################################
305 class RpcContext(six.with_metaclass(abc.ABCMeta)):
306 """Provides RPC-related information and action."""
310 """Describes whether the RPC is active or has terminated.
314 True if RPC is active, False otherwise.
316 raise NotImplementedError()
319 def time_remaining(self):
320 """Describes the length of allowed time remaining for the RPC.
323 A nonnegative float indicating the length of allowed time in seconds
324 remaining for the RPC to complete before it is considered to have
325 timed out, or None if no deadline was specified for the RPC.
327 raise NotImplementedError()
333 Idempotent and has no effect if the RPC has already terminated.
335 raise NotImplementedError()
338 def add_callback(self, callback):
339 """Registers a callback to be called on RPC termination.
342 callback: A no-parameter callable to be called on RPC termination.
345 True if the callback was added and will be called later; False if
346 the callback was not added and will not be called (because the RPC
347 already terminated or some other reason).
349 raise NotImplementedError()
352 ######################### Invocation-Side Context ############################
355 class Call(six.with_metaclass(abc.ABCMeta, RpcContext)):
356 """Invocation-side utility object for an RPC."""
359 def initial_metadata(self):
360 """Accesses the initial metadata sent by the server.
362 This method blocks until the value is available.
365 The initial :term:`metadata`.
367 raise NotImplementedError()
370 def trailing_metadata(self):
371 """Accesses the trailing metadata sent by the server.
373 This method blocks until the value is available.
376 The trailing :term:`metadata`.
378 raise NotImplementedError()
382 """Accesses the status code sent by the server.
384 This method blocks until the value is available.
387 The StatusCode value for the RPC.
389 raise NotImplementedError()
393 """Accesses the details sent by the server.
395 This method blocks until the value is available.
398 The details string of the RPC.
400 raise NotImplementedError()
403 ############## Invocation-Side Interceptor Interfaces & Classes ##############
406 class ClientCallDetails(six.with_metaclass(abc.ABCMeta)):
407 """Describes an RPC to be invoked.
410 method: The method name of the RPC.
411 timeout: An optional duration of time in seconds to allow for the RPC.
412 metadata: Optional :term:`metadata` to be transmitted to
413 the service-side of the RPC.
414 credentials: An optional CallCredentials for the RPC.
415 wait_for_ready: This is an EXPERIMENTAL argument. An optional
416 flag to enable :term:`wait_for_ready` mechanism.
417 compression: An element of grpc.compression, e.g.
418 grpc.compression.Gzip. This is an EXPERIMENTAL option.
422 class UnaryUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
423 """Affords intercepting unary-unary invocations."""
426 def intercept_unary_unary(self, continuation, client_call_details, request):
427 """Intercepts a unary-unary invocation asynchronously.
430 continuation: A function that proceeds with the invocation by
431 executing the next interceptor in chain or invoking the
432 actual RPC on the underlying Channel. It is the interceptor's
433 responsibility to call it if it decides to move the RPC forward.
434 The interceptor can use
435 `response_future = continuation(client_call_details, request)`
436 to continue with the RPC. `continuation` returns an object that is
437 both a Call for the RPC and a Future. In the event of RPC
438 completion, the return Call-Future's result value will be
439 the response message of the RPC. Should the event terminate
440 with non-OK status, the returned Call-Future's exception value
442 client_call_details: A ClientCallDetails object describing the
444 request: The request value for the RPC.
447 An object that is both a Call for the RPC and a Future.
448 In the event of RPC completion, the return Call-Future's
449 result value will be the response message of the RPC.
450 Should the event terminate with non-OK status, the returned
451 Call-Future's exception value will be an RpcError.
453 raise NotImplementedError()
456 class UnaryStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
457 """Affords intercepting unary-stream invocations."""
460 def intercept_unary_stream(self, continuation, client_call_details,
462 """Intercepts a unary-stream invocation.
465 continuation: A function that proceeds with the invocation by
466 executing the next interceptor in chain or invoking the
467 actual RPC on the underlying Channel. It is the interceptor's
468 responsibility to call it if it decides to move the RPC forward.
469 The interceptor can use
470 `response_iterator = continuation(client_call_details, request)`
471 to continue with the RPC. `continuation` returns an object that is
472 both a Call for the RPC and an iterator for response values.
473 Drawing response values from the returned Call-iterator may
474 raise RpcError indicating termination of the RPC with non-OK
476 client_call_details: A ClientCallDetails object describing the
478 request: The request value for the RPC.
481 An object that is both a Call for the RPC and an iterator of
482 response values. Drawing response values from the returned
483 Call-iterator may raise RpcError indicating termination of
484 the RPC with non-OK status. This object *should* also fulfill the
485 Future interface, though it may not.
487 raise NotImplementedError()
490 class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
491 """Affords intercepting stream-unary invocations."""
494 def intercept_stream_unary(self, continuation, client_call_details,
496 """Intercepts a stream-unary invocation asynchronously.
499 continuation: A function that proceeds with the invocation by
500 executing the next interceptor in chain or invoking the
501 actual RPC on the underlying Channel. It is the interceptor's
502 responsibility to call it if it decides to move the RPC forward.
503 The interceptor can use
504 `response_future = continuation(client_call_details, request_iterator)`
505 to continue with the RPC. `continuation` returns an object that is
506 both a Call for the RPC and a Future. In the event of RPC completion,
507 the return Call-Future's result value will be the response message
508 of the RPC. Should the event terminate with non-OK status, the
509 returned Call-Future's exception value will be an RpcError.
510 client_call_details: A ClientCallDetails object describing the
512 request_iterator: An iterator that yields request values for the RPC.
515 An object that is both a Call for the RPC and a Future.
516 In the event of RPC completion, the return Call-Future's
517 result value will be the response message of the RPC.
518 Should the event terminate with non-OK status, the returned
519 Call-Future's exception value will be an RpcError.
521 raise NotImplementedError()
524 class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
525 """Affords intercepting stream-stream invocations."""
528 def intercept_stream_stream(self, continuation, client_call_details,
530 """Intercepts a stream-stream invocation.
533 continuation: A function that proceeds with the invocation by
534 executing the next interceptor in chain or invoking the
535 actual RPC on the underlying Channel. It is the interceptor's
536 responsibility to call it if it decides to move the RPC forward.
537 The interceptor can use
538 `response_iterator = continuation(client_call_details, request_iterator)`
539 to continue with the RPC. `continuation` returns an object that is
540 both a Call for the RPC and an iterator for response values.
541 Drawing response values from the returned Call-iterator may
542 raise RpcError indicating termination of the RPC with non-OK
544 client_call_details: A ClientCallDetails object describing the
546 request_iterator: An iterator that yields request values for the RPC.
549 An object that is both a Call for the RPC and an iterator of
550 response values. Drawing response values from the returned
551 Call-iterator may raise RpcError indicating termination of
552 the RPC with non-OK status. This object *should* also fulfill the
553 Future interface, though it may not.
555 raise NotImplementedError()
558 ############ Authentication & Authorization Interfaces & Classes #############
561 class ChannelCredentials(object):
562 """An encapsulation of the data required to create a secure Channel.
564 This class has no supported interface - it exists to define the type of its
565 instances and its instances exist to be passed to other functions. For
566 example, ssl_channel_credentials returns an instance of this class and
567 secure_channel requires an instance of this class.
570 def __init__(self, credentials):
571 self._credentials = credentials
574 class CallCredentials(object):
575 """An encapsulation of the data required to assert an identity over a call.
577 A CallCredentials has to be used with secure Channel, otherwise the
578 metadata will not be transmitted to the server.
580 A CallCredentials may be composed with ChannelCredentials to always assert
581 identity for every call over that Channel.
583 This class has no supported interface - it exists to define the type of its
584 instances and its instances exist to be passed to other functions.
587 def __init__(self, credentials):
588 self._credentials = credentials
591 class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
592 """Provides information to call credentials metadata plugins.
595 service_url: A string URL of the service being called into.
596 method_name: A string of the fully qualified method name being called.
600 class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)):
601 """Callback object received by a metadata plugin."""
603 def __call__(self, metadata, error):
604 """Passes to the gRPC runtime authentication metadata for an RPC.
607 metadata: The :term:`metadata` used to construct the CallCredentials.
608 error: An Exception to indicate error or None to indicate success.
610 raise NotImplementedError()
613 class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
614 """A specification for custom authentication."""
616 def __call__(self, context, callback):
617 """Implements authentication by passing metadata to a callback.
619 This method will be invoked asynchronously in a separate thread.
622 context: An AuthMetadataContext providing information on the RPC that
623 the plugin is being called to authenticate.
624 callback: An AuthMetadataPluginCallback to be invoked either
625 synchronously or asynchronously.
627 raise NotImplementedError()
630 class ServerCredentials(object):
631 """An encapsulation of the data required to open a secure port on a Server.
633 This class has no supported interface - it exists to define the type of its
634 instances and its instances exist to be passed to other functions.
637 def __init__(self, credentials):
638 self._credentials = credentials
641 class ServerCertificateConfiguration(object):
642 """A certificate configuration for use with an SSL-enabled Server.
644 Instances of this class can be returned in the certificate configuration
647 This class has no supported interface -- it exists to define the
648 type of its instances and its instances exist to be passed to
652 def __init__(self, certificate_configuration):
653 self._certificate_configuration = certificate_configuration
656 ######################## Multi-Callable Interfaces ###########################
659 class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
660 """Affords invoking a unary-unary RPC from client-side."""
670 """Synchronously invokes the underlying RPC.
673 request: The request value for the RPC.
674 timeout: An optional duration of time in seconds to allow
676 metadata: Optional :term:`metadata` to be transmitted to the
677 service-side of the RPC.
678 credentials: An optional CallCredentials for the RPC. Only valid for
680 wait_for_ready: This is an EXPERIMENTAL argument. An optional
681 flag to enable :term:`wait_for_ready` mechanism.
682 compression: An element of grpc.compression, e.g.
683 grpc.compression.Gzip. This is an EXPERIMENTAL option.
686 The response value for the RPC.
689 RpcError: Indicating that the RPC terminated with non-OK status. The
690 raised RpcError will also be a Call for the RPC affording the RPC's
691 metadata, status code, and details.
693 raise NotImplementedError()
703 """Synchronously invokes the underlying RPC.
706 request: The request value for the RPC.
707 timeout: An optional durating of time in seconds to allow for
709 metadata: Optional :term:`metadata` to be transmitted to the
710 service-side of the RPC.
711 credentials: An optional CallCredentials for the RPC. Only valid for
713 wait_for_ready: This is an EXPERIMENTAL argument. An optional
714 flag to enable :term:`wait_for_ready` mechanism.
715 compression: An element of grpc.compression, e.g.
716 grpc.compression.Gzip. This is an EXPERIMENTAL option.
719 The response value for the RPC and a Call value for the RPC.
722 RpcError: Indicating that the RPC terminated with non-OK status. The
723 raised RpcError will also be a Call for the RPC affording the RPC's
724 metadata, status code, and details.
726 raise NotImplementedError()
736 """Asynchronously invokes the underlying RPC.
739 request: The request value for the RPC.
740 timeout: An optional duration of time in seconds to allow for
742 metadata: Optional :term:`metadata` to be transmitted to the
743 service-side of the RPC.
744 credentials: An optional CallCredentials for the RPC. Only valid for
746 wait_for_ready: This is an EXPERIMENTAL argument. An optional
747 flag to enable :term:`wait_for_ready` mechanism.
748 compression: An element of grpc.compression, e.g.
749 grpc.compression.Gzip. This is an EXPERIMENTAL option.
752 An object that is both a Call for the RPC and a Future.
753 In the event of RPC completion, the return Call-Future's result
754 value will be the response message of the RPC.
755 Should the event terminate with non-OK status,
756 the returned Call-Future's exception value will be an RpcError.
758 raise NotImplementedError()
761 class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
762 """Affords invoking a unary-stream RPC from client-side."""
772 """Invokes the underlying RPC.
775 request: The request value for the RPC.
776 timeout: An optional duration of time in seconds to allow for
777 the RPC. If None, the timeout is considered infinite.
778 metadata: An optional :term:`metadata` to be transmitted to the
779 service-side of the RPC.
780 credentials: An optional CallCredentials for the RPC. Only valid for
782 wait_for_ready: This is an EXPERIMENTAL argument. An optional
783 flag to enable :term:`wait_for_ready` mechanism.
784 compression: An element of grpc.compression, e.g.
785 grpc.compression.Gzip. This is an EXPERIMENTAL option.
788 An object that is a Call for the RPC, an iterator of response
789 values, and a Future for the RPC. Drawing response values from the
790 returned Call-iterator may raise RpcError indicating termination of
791 the RPC with non-OK status.
793 raise NotImplementedError()
796 class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
797 """Affords invoking a stream-unary RPC from client-side."""
807 """Synchronously invokes the underlying RPC.
810 request_iterator: An iterator that yields request values for
812 timeout: An optional duration of time in seconds to allow for
813 the RPC. If None, the timeout is considered infinite.
814 metadata: Optional :term:`metadata` to be transmitted to the
815 service-side of the RPC.
816 credentials: An optional CallCredentials for the RPC. Only valid for
818 wait_for_ready: This is an EXPERIMENTAL argument. An optional
819 flag to enable :term:`wait_for_ready` mechanism.
820 compression: An element of grpc.compression, e.g.
821 grpc.compression.Gzip. This is an EXPERIMENTAL option.
824 The response value for the RPC.
827 RpcError: Indicating that the RPC terminated with non-OK status. The
828 raised RpcError will also implement grpc.Call, affording methods
829 such as metadata, code, and details.
831 raise NotImplementedError()
841 """Synchronously invokes the underlying RPC on the client.
844 request_iterator: An iterator that yields request values for
846 timeout: An optional duration of time in seconds to allow for
847 the RPC. If None, the timeout is considered infinite.
848 metadata: Optional :term:`metadata` to be transmitted to the
849 service-side of the RPC.
850 credentials: An optional CallCredentials for the RPC. Only valid for
852 wait_for_ready: This is an EXPERIMENTAL argument. An optional
853 flag to enable :term:`wait_for_ready` mechanism.
854 compression: An element of grpc.compression, e.g.
855 grpc.compression.Gzip. This is an EXPERIMENTAL option.
858 The response value for the RPC and a Call object for the RPC.
861 RpcError: Indicating that the RPC terminated with non-OK status. The
862 raised RpcError will also be a Call for the RPC affording the RPC's
863 metadata, status code, and details.
865 raise NotImplementedError()
875 """Asynchronously invokes the underlying RPC on the client.
878 request_iterator: An iterator that yields request values for the RPC.
879 timeout: An optional duration of time in seconds to allow for
880 the RPC. If None, the timeout is considered infinite.
881 metadata: Optional :term:`metadata` to be transmitted to the
882 service-side of the RPC.
883 credentials: An optional CallCredentials for the RPC. Only valid for
885 wait_for_ready: This is an EXPERIMENTAL argument. An optional
886 flag to enable :term:`wait_for_ready` mechanism.
887 compression: An element of grpc.compression, e.g.
888 grpc.compression.Gzip. This is an EXPERIMENTAL option.
891 An object that is both a Call for the RPC and a Future.
892 In the event of RPC completion, the return Call-Future's result value
893 will be the response message of the RPC. Should the event terminate
894 with non-OK status, the returned Call-Future's exception value will
897 raise NotImplementedError()
900 class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
901 """Affords invoking a stream-stream RPC on client-side."""
911 """Invokes the underlying RPC on the client.
914 request_iterator: An iterator that yields request values for the RPC.
915 timeout: An optional duration of time in seconds to allow for
916 the RPC. If not specified, the timeout is considered infinite.
917 metadata: Optional :term:`metadata` to be transmitted to the
918 service-side of the RPC.
919 credentials: An optional CallCredentials for the RPC. Only valid for
921 wait_for_ready: This is an EXPERIMENTAL argument. An optional
922 flag to enable :term:`wait_for_ready` mechanism.
923 compression: An element of grpc.compression, e.g.
924 grpc.compression.Gzip. This is an EXPERIMENTAL option.
927 An object that is a Call for the RPC, an iterator of response
928 values, and a Future for the RPC. Drawing response values from the
929 returned Call-iterator may raise RpcError indicating termination of
930 the RPC with non-OK status.
932 raise NotImplementedError()
935 ############################# Channel Interface ##############################
938 class Channel(six.with_metaclass(abc.ABCMeta)):
939 """Affords RPC invocation via generic methods on client-side.
941 Channel objects implement the Context Manager type, although they need not
942 support being entered and exited multiple times.
946 def subscribe(self, callback, try_to_connect=False):
947 """Subscribe to this Channel's connectivity state machine.
949 A Channel may be in any of the states described by ChannelConnectivity.
950 This method allows application to monitor the state transitions.
951 The typical use case is to debug or gain better visibility into gRPC
955 callback: A callable to be invoked with ChannelConnectivity argument.
956 ChannelConnectivity describes current state of the channel.
957 The callable will be invoked immediately upon subscription
958 and again for every change to ChannelConnectivity until it
959 is unsubscribed or this Channel object goes out of scope.
960 try_to_connect: A boolean indicating whether or not this Channel
961 should attempt to connect immediately. If set to False, gRPC
962 runtime decides when to connect.
964 raise NotImplementedError()
967 def unsubscribe(self, callback):
968 """Unsubscribes a subscribed callback from this Channel's connectivity.
971 callback: A callable previously registered with this Channel from
972 having been passed to its "subscribe" method.
974 raise NotImplementedError()
977 def unary_unary(self,
979 request_serializer=None,
980 response_deserializer=None):
981 """Creates a UnaryUnaryMultiCallable for a unary-unary method.
984 method: The name of the RPC method.
985 request_serializer: Optional :term:`serializer` for serializing the request
986 message. Request goes unserialized in case None is passed.
987 response_deserializer: Optional :term:`deserializer` for deserializing the
988 response message. Response goes undeserialized in case None
992 A UnaryUnaryMultiCallable value for the named unary-unary method.
994 raise NotImplementedError()
997 def unary_stream(self,
999 request_serializer=None,
1000 response_deserializer=None):
1001 """Creates a UnaryStreamMultiCallable for a unary-stream method.
1004 method: The name of the RPC method.
1005 request_serializer: Optional :term:`serializer` for serializing the request
1006 message. Request goes unserialized in case None is passed.
1007 response_deserializer: Optional :term:`deserializer` for deserializing the
1008 response message. Response goes undeserialized in case None is
1012 A UnaryStreamMultiCallable value for the name unary-stream method.
1014 raise NotImplementedError()
1017 def stream_unary(self,
1019 request_serializer=None,
1020 response_deserializer=None):
1021 """Creates a StreamUnaryMultiCallable for a stream-unary method.
1024 method: The name of the RPC method.
1025 request_serializer: Optional :term:`serializer` for serializing the request
1026 message. Request goes unserialized in case None is passed.
1027 response_deserializer: Optional :term:`deserializer` for deserializing the
1028 response message. Response goes undeserialized in case None is
1032 A StreamUnaryMultiCallable value for the named stream-unary method.
1034 raise NotImplementedError()
1037 def stream_stream(self,
1039 request_serializer=None,
1040 response_deserializer=None):
1041 """Creates a StreamStreamMultiCallable for a stream-stream method.
1044 method: The name of the RPC method.
1045 request_serializer: Optional :term:`serializer` for serializing the request
1046 message. Request goes unserialized in case None is passed.
1047 response_deserializer: Optional :term:`deserializer` for deserializing the
1048 response message. Response goes undeserialized in case None
1052 A StreamStreamMultiCallable value for the named stream-stream method.
1054 raise NotImplementedError()
1058 """Closes this Channel and releases all resources held by it.
1060 Closing the Channel will immediately terminate all RPCs active with the
1061 Channel and it is not valid to invoke new RPCs with the Channel.
1063 This method is idempotent.
1065 raise NotImplementedError()
1067 def __enter__(self):
1068 """Enters the runtime context related to the channel object."""
1069 raise NotImplementedError()
1071 def __exit__(self, exc_type, exc_val, exc_tb):
1072 """Exits the runtime context related to the channel object."""
1073 raise NotImplementedError()
1076 ########################## Service-Side Context ##############################
1079 class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
1080 """A context object passed to method implementations."""
1083 def invocation_metadata(self):
1084 """Accesses the metadata from the sent by the client.
1087 The invocation :term:`metadata`.
1089 raise NotImplementedError()
1093 """Identifies the peer that invoked the RPC being serviced.
1096 A string identifying the peer that invoked the RPC being serviced.
1097 The string format is determined by gRPC runtime.
1099 raise NotImplementedError()
1102 def peer_identities(self):
1103 """Gets one or more peer identity(s).
1106 servicer_context.auth_context().get(servicer_context.peer_identity_key())
1109 An iterable of the identities, or None if the call is not
1110 authenticated. Each identity is returned as a raw bytes type.
1112 raise NotImplementedError()
1115 def peer_identity_key(self):
1116 """The auth property used to identify the peer.
1118 For example, "x509_common_name" or "x509_subject_alternative_name" are
1119 used to identify an SSL peer.
1122 The auth property (string) that indicates the
1123 peer identity, or None if the call is not authenticated.
1125 raise NotImplementedError()
1128 def auth_context(self):
1129 """Gets the auth context for the call.
1132 A map of strings to an iterable of bytes for each auth property.
1134 raise NotImplementedError()
1136 def set_compression(self, compression):
1137 """Set the compression algorithm to be used for the entire call.
1139 This is an EXPERIMENTAL method.
1142 compression: An element of grpc.compression, e.g.
1143 grpc.compression.Gzip.
1145 raise NotImplementedError()
1148 def send_initial_metadata(self, initial_metadata):
1149 """Sends the initial metadata value to the client.
1151 This method need not be called by implementations if they have no
1152 metadata to add to what the gRPC runtime will transmit.
1155 initial_metadata: The initial :term:`metadata`.
1157 raise NotImplementedError()
1160 def set_trailing_metadata(self, trailing_metadata):
1161 """Sets the trailing metadata for the RPC.
1163 Sets the trailing metadata to be sent upon completion of the RPC.
1165 If this method is invoked multiple times throughout the lifetime of an
1166 RPC, the value supplied in the final invocation will be the value sent
1169 This method need not be called by implementations if they have no
1170 metadata to add to what the gRPC runtime will transmit.
1173 trailing_metadata: The trailing :term:`metadata`.
1175 raise NotImplementedError()
1178 def abort(self, code, details):
1179 """Raises an exception to terminate the RPC with a non-OK status.
1181 The code and details passed as arguments will supercede any existing
1185 code: A StatusCode object to be sent to the client.
1186 It must not be StatusCode.OK.
1187 details: A UTF-8-encodable string to be sent to the client upon
1188 termination of the RPC.
1191 Exception: An exception is always raised to signal the abortion the
1192 RPC to the gRPC runtime.
1194 raise NotImplementedError()
1197 def abort_with_status(self, status):
1198 """Raises an exception to terminate the RPC with a non-OK status.
1200 The status passed as argument will supercede any existing status code,
1201 status message and trailing metadata.
1203 This is an EXPERIMENTAL API.
1206 status: A grpc.Status object. The status code in it must not be
1210 Exception: An exception is always raised to signal the abortion the
1211 RPC to the gRPC runtime.
1213 raise NotImplementedError()
1216 def set_code(self, code):
1217 """Sets the value to be used as status code upon RPC completion.
1219 This method need not be called by method implementations if they wish
1220 the gRPC runtime to determine the status code of the RPC.
1223 code: A StatusCode object to be sent to the client.
1225 raise NotImplementedError()
1228 def set_details(self, details):
1229 """Sets the value to be used as detail string upon RPC completion.
1231 This method need not be called by method implementations if they have
1232 no details to transmit.
1235 details: A UTF-8-encodable string to be sent to the client upon
1236 termination of the RPC.
1238 raise NotImplementedError()
1240 def disable_next_message_compression(self):
1241 """Disables compression for the next response message.
1243 This is an EXPERIMENTAL method.
1245 This method will override any compression configuration set during
1246 server creation or set on the call.
1248 raise NotImplementedError()
1251 ##################### Service-Side Handler Interfaces ########################
1254 class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
1255 """An implementation of a single RPC method.
1258 request_streaming: Whether the RPC supports exactly one request message
1259 or any arbitrary number of request messages.
1260 response_streaming: Whether the RPC supports exactly one response message
1261 or any arbitrary number of response messages.
1262 request_deserializer: A callable :term:`deserializer` that accepts a byte string and
1263 returns an object suitable to be passed to this object's business
1264 logic, or None to indicate that this object's business logic should be
1265 passed the raw request bytes.
1266 response_serializer: A callable :term:`serializer` that accepts an object produced
1267 by this object's business logic and returns a byte string, or None to
1268 indicate that the byte strings produced by this object's business logic
1269 should be transmitted on the wire as they are.
1270 unary_unary: This object's application-specific business logic as a
1271 callable value that takes a request value and a ServicerContext object
1272 and returns a response value. Only non-None if both request_streaming
1273 and response_streaming are False.
1274 unary_stream: This object's application-specific business logic as a
1275 callable value that takes a request value and a ServicerContext object
1276 and returns an iterator of response values. Only non-None if
1277 request_streaming is False and response_streaming is True.
1278 stream_unary: This object's application-specific business logic as a
1279 callable value that takes an iterator of request values and a
1280 ServicerContext object and returns a response value. Only non-None if
1281 request_streaming is True and response_streaming is False.
1282 stream_stream: This object's application-specific business logic as a
1283 callable value that takes an iterator of request values and a
1284 ServicerContext object and returns an iterator of response values.
1285 Only non-None if request_streaming and response_streaming are both
1290 class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
1291 """Describes an RPC that has just arrived for service.
1294 method: The method name of the RPC.
1295 invocation_metadata: The :term:`metadata` sent by the client.
1299 class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
1300 """An implementation of arbitrarily many RPC methods."""
1303 def service(self, handler_call_details):
1304 """Returns the handler for servicing the RPC.
1307 handler_call_details: A HandlerCallDetails describing the RPC.
1310 An RpcMethodHandler with which the RPC may be serviced if the
1311 implementation chooses to service this RPC, or None otherwise.
1313 raise NotImplementedError()
1316 class ServiceRpcHandler(six.with_metaclass(abc.ABCMeta, GenericRpcHandler)):
1317 """An implementation of RPC methods belonging to a service.
1319 A service handles RPC methods with structured names of the form
1320 '/Service.Name/Service.Method', where 'Service.Name' is the value
1321 returned by service_name(), and 'Service.Method' is the method
1322 name. A service can have multiple method names, but only a single
1327 def service_name(self):
1328 """Returns this service's name.
1333 raise NotImplementedError()
1336 #################### Service-Side Interceptor Interfaces #####################
1339 class ServerInterceptor(six.with_metaclass(abc.ABCMeta)):
1340 """Affords intercepting incoming RPCs on the service-side."""
1343 def intercept_service(self, continuation, handler_call_details):
1344 """Intercepts incoming RPCs before handing them over to a handler.
1347 continuation: A function that takes a HandlerCallDetails and
1348 proceeds to invoke the next interceptor in the chain, if any,
1349 or the RPC handler lookup logic, with the call details passed
1350 as an argument, and returns an RpcMethodHandler instance if
1351 the RPC is considered serviced, or None otherwise.
1352 handler_call_details: A HandlerCallDetails describing the RPC.
1355 An RpcMethodHandler with which the RPC may be serviced if the
1356 interceptor chooses to service this RPC, or None otherwise.
1358 raise NotImplementedError()
1361 ############################# Server Interface ###############################
1364 class Server(six.with_metaclass(abc.ABCMeta)):
1365 """Services RPCs."""
1368 def add_generic_rpc_handlers(self, generic_rpc_handlers):
1369 """Registers GenericRpcHandlers with this Server.
1371 This method is only safe to call before the server is started.
1374 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1375 used to service RPCs.
1377 raise NotImplementedError()
1380 def add_insecure_port(self, address):
1381 """Opens an insecure port for accepting RPCs.
1383 This method may only be called before starting the server.
1386 address: The address for which to open a port. If the port is 0,
1387 or not specified in the address, then gRPC runtime will choose a port.
1390 An integer port on which server will accept RPC requests.
1392 raise NotImplementedError()
1395 def add_secure_port(self, address, server_credentials):
1396 """Opens a secure port for accepting RPCs.
1398 This method may only be called before starting the server.
1401 address: The address for which to open a port.
1402 if the port is 0, or not specified in the address, then gRPC
1403 runtime will choose a port.
1404 server_credentials: A ServerCredentials object.
1407 An integer port on which server will accept RPC requests.
1409 raise NotImplementedError()
1413 """Starts this Server.
1415 This method may only be called once. (i.e. it is not idempotent).
1417 raise NotImplementedError()
1420 def stop(self, grace):
1421 """Stops this Server.
1423 This method immediately stop service of new RPCs in all cases.
1425 If a grace period is specified, this method returns immediately
1426 and all RPCs active at the end of the grace period are aborted.
1427 If a grace period is not specified (by passing None for `grace`),
1428 all existing RPCs are aborted immediately and this method
1429 blocks until the last RPC handler terminates.
1431 This method is idempotent and may be called at any time.
1432 Passing a smaller grace value in a subsequent call will have
1433 the effect of stopping the Server sooner (passing None will
1434 have the effect of stopping the server immediately). Passing
1435 a larger grace value in a subsequent call *will not* have the
1436 effect of stopping the server later (i.e. the most restrictive
1437 grace value is used).
1440 grace: A duration of time in seconds or None.
1443 A threading.Event that will be set when this Server has completely
1444 stopped, i.e. when running RPCs either complete or are aborted and
1445 all handlers have terminated.
1447 raise NotImplementedError()
1449 def wait_for_termination(self, timeout=None):
1450 """Block current thread until the server stops.
1452 This is an EXPERIMENTAL API.
1454 The wait will not consume computational resources during blocking, and
1455 it will block until one of the two following conditions are met:
1457 1) The server is stopped or terminated;
1458 2) A timeout occurs if timeout is not `None`.
1460 The timeout argument works in the same way as `threading.Event.wait()`.
1461 https://docs.python.org/3/library/threading.html#threading.Event.wait
1464 timeout: A floating point number specifying a timeout for the
1465 operation in seconds.
1468 A bool indicates if the operation times out.
1470 raise NotImplementedError()
1473 ################################# Functions ################################
1476 def unary_unary_rpc_method_handler(behavior,
1477 request_deserializer=None,
1478 response_serializer=None):
1479 """Creates an RpcMethodHandler for a unary-unary RPC method.
1482 behavior: The implementation of an RPC that accepts one request
1483 and returns one response.
1484 request_deserializer: An optional :term:`deserializer` for request deserialization.
1485 response_serializer: An optional :term:`serializer` for response serialization.
1488 An RpcMethodHandler object that is typically used by grpc.Server.
1490 from grpc import _utilities # pylint: disable=cyclic-import
1491 return _utilities.RpcMethodHandler(False, False, request_deserializer,
1492 response_serializer, behavior, None,
1496 def unary_stream_rpc_method_handler(behavior,
1497 request_deserializer=None,
1498 response_serializer=None):
1499 """Creates an RpcMethodHandler for a unary-stream RPC method.
1502 behavior: The implementation of an RPC that accepts one request
1503 and returns an iterator of response values.
1504 request_deserializer: An optional :term:`deserializer` for request deserialization.
1505 response_serializer: An optional :term:`serializer` for response serialization.
1508 An RpcMethodHandler object that is typically used by grpc.Server.
1510 from grpc import _utilities # pylint: disable=cyclic-import
1511 return _utilities.RpcMethodHandler(False, True, request_deserializer,
1512 response_serializer, None, behavior,
1516 def stream_unary_rpc_method_handler(behavior,
1517 request_deserializer=None,
1518 response_serializer=None):
1519 """Creates an RpcMethodHandler for a stream-unary RPC method.
1522 behavior: The implementation of an RPC that accepts an iterator of
1523 request values and returns a single response value.
1524 request_deserializer: An optional :term:`deserializer` for request deserialization.
1525 response_serializer: An optional :term:`serializer` for response serialization.
1528 An RpcMethodHandler object that is typically used by grpc.Server.
1530 from grpc import _utilities # pylint: disable=cyclic-import
1531 return _utilities.RpcMethodHandler(True, False, request_deserializer,
1532 response_serializer, None, None,
1536 def stream_stream_rpc_method_handler(behavior,
1537 request_deserializer=None,
1538 response_serializer=None):
1539 """Creates an RpcMethodHandler for a stream-stream RPC method.
1542 behavior: The implementation of an RPC that accepts an iterator of
1543 request values and returns an iterator of response values.
1544 request_deserializer: An optional :term:`deserializer` for request deserialization.
1545 response_serializer: An optional :term:`serializer` for response serialization.
1548 An RpcMethodHandler object that is typically used by grpc.Server.
1550 from grpc import _utilities # pylint: disable=cyclic-import
1551 return _utilities.RpcMethodHandler(True, True, request_deserializer,
1552 response_serializer, None, None, None,
1556 def method_handlers_generic_handler(service, method_handlers):
1557 """Creates a GenericRpcHandler from RpcMethodHandlers.
1560 service: The name of the service that is implemented by the
1562 method_handlers: A dictionary that maps method names to corresponding
1566 A GenericRpcHandler. This is typically added to the grpc.Server object
1567 with add_generic_rpc_handlers() before starting the server.
1569 from grpc import _utilities # pylint: disable=cyclic-import
1570 return _utilities.DictionaryGenericHandler(service, method_handlers)
1573 def ssl_channel_credentials(root_certificates=None,
1575 certificate_chain=None):
1576 """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1579 root_certificates: The PEM-encoded root certificates as a byte string,
1580 or None to retrieve them from a default location chosen by gRPC
1582 private_key: The PEM-encoded private key as a byte string, or None if no
1583 private key should be used.
1584 certificate_chain: The PEM-encoded certificate chain as a byte string
1585 to use or None if no certificate chain should be used.
1588 A ChannelCredentials for use with an SSL-enabled Channel.
1590 return ChannelCredentials(
1591 _cygrpc.SSLChannelCredentials(root_certificates, private_key,
1595 def xds_channel_credentials(fallback_credentials=None):
1596 """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL
1600 fallback_credentials: Credentials to use in case it is not possible to
1601 establish a secure connection via xDS. If no fallback_credentials
1602 argument is supplied, a default SSLChannelCredentials is used.
1604 fallback_credentials = ssl_channel_credentials(
1605 ) if fallback_credentials is None else fallback_credentials
1606 return ChannelCredentials(
1607 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials))
1610 def metadata_call_credentials(metadata_plugin, name=None):
1611 """Construct CallCredentials from an AuthMetadataPlugin.
1614 metadata_plugin: An AuthMetadataPlugin to use for authentication.
1615 name: An optional name for the plugin.
1620 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1621 return _plugin_wrapping.metadata_plugin_call_credentials(
1622 metadata_plugin, name)
1625 def access_token_call_credentials(access_token):
1626 """Construct CallCredentials from an access token.
1629 access_token: A string to place directly in the http request
1630 authorization header, for example
1631 "authorization: Bearer <access_token>".
1636 from grpc import _auth # pylint: disable=cyclic-import
1637 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1638 return _plugin_wrapping.metadata_plugin_call_credentials(
1639 _auth.AccessTokenAuthMetadataPlugin(access_token), None)
1642 def composite_call_credentials(*call_credentials):
1643 """Compose multiple CallCredentials to make a new CallCredentials.
1646 *call_credentials: At least two CallCredentials objects.
1649 A CallCredentials object composed of the given CallCredentials objects.
1651 return CallCredentials(
1652 _cygrpc.CompositeCallCredentials(
1653 tuple(single_call_credentials._credentials
1654 for single_call_credentials in call_credentials)))
1657 def composite_channel_credentials(channel_credentials, *call_credentials):
1658 """Compose a ChannelCredentials and one or more CallCredentials objects.
1661 channel_credentials: A ChannelCredentials object.
1662 *call_credentials: One or more CallCredentials objects.
1665 A ChannelCredentials composed of the given ChannelCredentials and
1666 CallCredentials objects.
1668 return ChannelCredentials(
1669 _cygrpc.CompositeChannelCredentials(
1670 tuple(single_call_credentials._credentials
1671 for single_call_credentials in call_credentials),
1672 channel_credentials._credentials))
1675 def ssl_server_credentials(private_key_certificate_chain_pairs,
1676 root_certificates=None,
1677 require_client_auth=False):
1678 """Creates a ServerCredentials for use with an SSL-enabled Server.
1681 private_key_certificate_chain_pairs: A list of pairs of the form
1682 [PEM-encoded private key, PEM-encoded certificate chain].
1683 root_certificates: An optional byte string of PEM-encoded client root
1684 certificates that the server will use to verify client authentication.
1685 If omitted, require_client_auth must also be False.
1686 require_client_auth: A boolean indicating whether or not to require
1687 clients to be authenticated. May only be True if root_certificates
1691 A ServerCredentials for use with an SSL-enabled Server. Typically, this
1692 object is an argument to add_secure_port() method during server setup.
1694 if not private_key_certificate_chain_pairs:
1696 'At least one private key-certificate chain pair is required!')
1697 elif require_client_auth and root_certificates is None:
1699 'Illegal to require client auth without providing root certificates!'
1702 return ServerCredentials(
1703 _cygrpc.server_credentials_ssl(root_certificates, [
1704 _cygrpc.SslPemKeyCertPair(key, pem)
1705 for key, pem in private_key_certificate_chain_pairs
1706 ], require_client_auth))
1709 def xds_server_credentials(fallback_credentials):
1710 """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL
1714 fallback_credentials: Credentials to use in case it is not possible to
1715 establish a secure connection via xDS. No default value is provided.
1717 return ServerCredentials(
1718 _cygrpc.xds_server_credentials(fallback_credentials._credentials))
1721 def insecure_server_credentials():
1722 """Creates a credentials object directing the server to use no credentials.
1723 This is an EXPERIMENTAL API.
1725 This object cannot be used directly in a call to `add_secure_port`.
1726 Instead, it should be used to construct other credentials objects, e.g.
1727 with xds_server_credentials.
1729 return ServerCredentials(_cygrpc.insecure_server_credentials())
1732 def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
1733 root_certificates=None):
1734 """Creates a ServerCertificateConfiguration for use with a Server.
1737 private_key_certificate_chain_pairs: A collection of pairs of
1738 the form [PEM-encoded private key, PEM-encoded certificate
1740 root_certificates: An optional byte string of PEM-encoded client root
1741 certificates that the server will use to verify client authentication.
1744 A ServerCertificateConfiguration that can be returned in the certificate
1745 configuration fetching callback.
1747 if private_key_certificate_chain_pairs:
1748 return ServerCertificateConfiguration(
1749 _cygrpc.server_certificate_config_ssl(root_certificates, [
1750 _cygrpc.SslPemKeyCertPair(key, pem)
1751 for key, pem in private_key_certificate_chain_pairs
1755 'At least one private key-certificate chain pair is required!')
1758 def dynamic_ssl_server_credentials(initial_certificate_configuration,
1759 certificate_configuration_fetcher,
1760 require_client_authentication=False):
1761 """Creates a ServerCredentials for use with an SSL-enabled Server.
1764 initial_certificate_configuration (ServerCertificateConfiguration): The
1765 certificate configuration with which the server will be initialized.
1766 certificate_configuration_fetcher (callable): A callable that takes no
1767 arguments and should return a ServerCertificateConfiguration to
1768 replace the server's current certificate, or None for no change
1769 (i.e., the server will continue its current certificate
1770 config). The library will call this callback on *every* new
1771 client connection before starting the TLS handshake with the
1772 client, thus allowing the user application to optionally
1773 return a new ServerCertificateConfiguration that the server will then
1774 use for the handshake.
1775 require_client_authentication: A boolean indicating whether or not to
1776 require clients to be authenticated.
1779 A ServerCredentials.
1781 return ServerCredentials(
1782 _cygrpc.server_credentials_ssl_dynamic_cert_config(
1783 initial_certificate_configuration,
1784 certificate_configuration_fetcher, require_client_authentication))
1788 class LocalConnectionType(enum.Enum):
1789 """Types of local connection for local credential creation.
1792 UDS: Unix domain socket connections
1793 LOCAL_TCP: Local TCP connections.
1795 UDS = _cygrpc.LocalConnectionType.uds
1796 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
1799 def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1800 """Creates a local ChannelCredentials used for local connections.
1802 This is an EXPERIMENTAL API.
1804 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1805 also UDS connections.
1807 The connections created by local channel credentials are not
1808 encrypted, but will be checked if they are local or not.
1809 The UDS connections are considered secure by providing peer authentication
1810 and data confidentiality while TCP connections are considered insecure.
1812 It is allowed to transmit call credentials over connections created by
1813 local channel credentials.
1815 Local channel credentials are useful for 1) eliminating insecure_channel usage;
1816 2) enable unit testing for call credentials without setting up secrets.
1819 local_connect_type: Local connection type (either
1820 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1823 A ChannelCredentials for use with a local Channel
1825 return ChannelCredentials(
1826 _cygrpc.channel_credentials_local(local_connect_type.value))
1829 def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1830 """Creates a local ServerCredentials used for local connections.
1832 This is an EXPERIMENTAL API.
1834 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1835 also UDS connections.
1837 The connections created by local server credentials are not
1838 encrypted, but will be checked if they are local or not.
1839 The UDS connections are considered secure by providing peer authentication
1840 and data confidentiality while TCP connections are considered insecure.
1842 It is allowed to transmit call credentials over connections created by local
1845 Local server credentials are useful for 1) eliminating insecure_channel usage;
1846 2) enable unit testing for call credentials without setting up secrets.
1849 local_connect_type: Local connection type (either
1850 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1853 A ServerCredentials for use with a local Server
1855 return ServerCredentials(
1856 _cygrpc.server_credentials_local(local_connect_type.value))
1859 def alts_channel_credentials(service_accounts=None):
1860 """Creates a ChannelCredentials for use with an ALTS-enabled Channel.
1862 This is an EXPERIMENTAL API.
1863 ALTS credentials API can only be used in GCP environment as it relies on
1864 handshaker service being available. For more info about ALTS see
1865 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1868 service_accounts: A list of server identities accepted by the client.
1869 If target service accounts are provided and none of them matches the
1870 peer identity of the server, handshake will fail. The arg can be empty
1871 if the client does not have any information about trusted server
1874 A ChannelCredentials for use with an ALTS-enabled Channel
1876 return ChannelCredentials(
1877 _cygrpc.channel_credentials_alts(service_accounts or []))
1880 def alts_server_credentials():
1881 """Creates a ServerCredentials for use with an ALTS-enabled connection.
1883 This is an EXPERIMENTAL API.
1884 ALTS credentials API can only be used in GCP environment as it relies on
1885 handshaker service being available. For more info about ALTS see
1886 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1889 A ServerCredentials for use with an ALTS-enabled Server
1891 return ServerCredentials(_cygrpc.server_credentials_alts())
1894 def compute_engine_channel_credentials(call_credentials):
1895 """Creates a compute engine channel credential.
1897 This credential can only be used in a GCP environment as it relies on
1898 a handshaker service. For more info about ALTS, see
1899 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1901 This channel credential is expected to be used as part of a composite
1902 credential in conjunction with a call credentials that authenticates the
1903 VM's default service account. If used with any other sort of call
1904 credential, the connection may suddenly and unexpectedly begin failing RPCs.
1906 return ChannelCredentials(
1907 _cygrpc.channel_credentials_compute_engine(
1908 call_credentials._credentials))
1911 def channel_ready_future(channel):
1912 """Creates a Future that tracks when a Channel is ready.
1914 Cancelling the Future does not affect the channel's state machine.
1915 It merely decouples the Future from channel state machine.
1918 channel: A Channel object.
1921 A Future object that matures when the channel connectivity is
1922 ChannelConnectivity.READY.
1924 from grpc import _utilities # pylint: disable=cyclic-import
1925 return _utilities.channel_ready_future(channel)
1928 def insecure_channel(target, options=None, compression=None):
1929 """Creates an insecure Channel to a server.
1931 The returned Channel is thread-safe.
1934 target: The server address
1935 options: An optional list of key-value pairs (:term:`channel_arguments`
1936 in gRPC Core runtime) to configure the channel.
1937 compression: An optional value indicating the compression method to be
1938 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1943 from grpc import _channel # pylint: disable=cyclic-import
1944 return _channel.Channel(target, () if options is None else options, None,
1948 def secure_channel(target, credentials, options=None, compression=None):
1949 """Creates a secure Channel to a server.
1951 The returned Channel is thread-safe.
1954 target: The server address.
1955 credentials: A ChannelCredentials instance.
1956 options: An optional list of key-value pairs (:term:`channel_arguments`
1957 in gRPC Core runtime) to configure the channel.
1958 compression: An optional value indicating the compression method to be
1959 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1964 from grpc import _channel # pylint: disable=cyclic-import
1965 from grpc.experimental import _insecure_channel_credentials
1966 if credentials._credentials is _insecure_channel_credentials:
1968 "secure_channel cannot be called with insecure credentials." +
1969 " Call insecure_channel instead.")
1970 return _channel.Channel(target, () if options is None else options,
1971 credentials._credentials, compression)
1974 def intercept_channel(channel, *interceptors):
1975 """Intercepts a channel through a set of interceptors.
1979 interceptors: Zero or more objects of type
1980 UnaryUnaryClientInterceptor,
1981 UnaryStreamClientInterceptor,
1982 StreamUnaryClientInterceptor, or
1983 StreamStreamClientInterceptor.
1984 Interceptors are given control in the order they are listed.
1987 A Channel that intercepts each invocation via the provided interceptors.
1990 TypeError: If interceptor does not derive from any of
1991 UnaryUnaryClientInterceptor,
1992 UnaryStreamClientInterceptor,
1993 StreamUnaryClientInterceptor, or
1994 StreamStreamClientInterceptor.
1996 from grpc import _interceptor # pylint: disable=cyclic-import
1997 return _interceptor.intercept_channel(channel, *interceptors)
2000 def server(thread_pool,
2004 maximum_concurrent_rpcs=None,
2007 """Creates a Server with which RPCs can be serviced.
2010 thread_pool: A futures.ThreadPoolExecutor to be used by the Server
2011 to execute RPC handlers.
2012 handlers: An optional list of GenericRpcHandlers used for executing RPCs.
2013 More handlers may be added by calling add_generic_rpc_handlers any time
2014 before the server is started.
2015 interceptors: An optional list of ServerInterceptor objects that observe
2016 and optionally manipulate the incoming RPCs before handing them over to
2017 handlers. The interceptors are given control in the order they are
2018 specified. This is an EXPERIMENTAL API.
2019 options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
2020 to configure the channel.
2021 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
2022 will service before returning RESOURCE_EXHAUSTED status, or None to
2024 compression: An element of grpc.compression, e.g.
2025 grpc.compression.Gzip. This compression algorithm will be used for the
2026 lifetime of the server unless overridden. This is an EXPERIMENTAL option.
2027 xds: If set to true, retrieves server configuration via xDS. This is an
2028 EXPERIMENTAL option.
2033 from grpc import _server # pylint: disable=cyclic-import
2034 return _server.create_server(thread_pool,
2035 () if handlers is None else handlers,
2036 () if interceptors is None else interceptors,
2037 () if options is None else options,
2038 maximum_concurrent_rpcs, compression, xds)
2041 @contextlib.contextmanager
2042 def _create_servicer_context(rpc_event, state, request_deserializer):
2043 from grpc import _server # pylint: disable=cyclic-import
2044 context = _server._Context(rpc_event, state, request_deserializer)
2046 context._finalize_state() # pylint: disable=protected-access
2050 class Compression(enum.IntEnum):
2051 """Indicates the compression method to be used for an RPC.
2053 This enumeration is part of an EXPERIMENTAL API.
2056 NoCompression: Do not use compression algorithm.
2057 Deflate: Use "Deflate" compression algorithm.
2058 Gzip: Use "Gzip" compression algorithm.
2060 NoCompression = _compression.NoCompression
2061 Deflate = _compression.Deflate
2062 Gzip = _compression.Gzip
2065 from grpc._runtime_protos import protos, services, protos_and_services # pylint: disable=wrong-import-position
2067 ################################### __all__ #################################
2070 'FutureTimeoutError',
2071 'FutureCancelledError',
2073 'ChannelConnectivity',
2079 'ChannelCredentials',
2081 'AuthMetadataContext',
2082 'AuthMetadataPluginCallback',
2083 'AuthMetadataPlugin',
2085 'ClientCallDetails',
2086 'ServerCertificateConfiguration',
2087 'ServerCredentials',
2088 'LocalConnectionType',
2089 'UnaryUnaryMultiCallable',
2090 'UnaryStreamMultiCallable',
2091 'StreamUnaryMultiCallable',
2092 'StreamStreamMultiCallable',
2093 'UnaryUnaryClientInterceptor',
2094 'UnaryStreamClientInterceptor',
2095 'StreamUnaryClientInterceptor',
2096 'StreamStreamClientInterceptor',
2100 'HandlerCallDetails',
2101 'GenericRpcHandler',
2102 'ServiceRpcHandler',
2104 'ServerInterceptor',
2105 'unary_unary_rpc_method_handler',
2106 'unary_stream_rpc_method_handler',
2107 'stream_unary_rpc_method_handler',
2108 'stream_stream_rpc_method_handler',
2109 'method_handlers_generic_handler',
2110 'ssl_channel_credentials',
2111 'metadata_call_credentials',
2112 'access_token_call_credentials',
2113 'composite_call_credentials',
2114 'composite_channel_credentials',
2115 'local_channel_credentials',
2116 'local_server_credentials',
2117 'alts_channel_credentials',
2118 'alts_server_credentials',
2119 'ssl_server_credentials',
2120 'ssl_server_certificate_configuration',
2121 'dynamic_ssl_server_credentials',
2122 'channel_ready_future',
2125 'intercept_channel',
2129 'protos_and_services',
2130 'xds_channel_credentials',
2131 'xds_server_credentials',
2132 'insecure_server_credentials',
2135 ############################### Extension Shims ################################
2137 # Here to maintain backwards compatibility; avoid using these in new code!
2140 sys.modules.update({'grpc.tools': grpc_tools})
2145 sys.modules.update({'grpc.health': grpc_health})
2149 import grpc_reflection
2150 sys.modules.update({'grpc.reflection': grpc_reflection})
2154 # Prevents import order issue in the case of renamed path.
2155 if sys.version_info >= (3, 6) and __name__ == "grpc":
2156 from grpc import aio # pylint: disable=ungrouped-imports
2157 sys.modules.update({'grpc.aio': aio})