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 terimated, 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.
409 This is an EXPERIMENTAL API.
412 method: The method name of the RPC.
413 timeout: An optional duration of time in seconds to allow for the RPC.
414 metadata: Optional :term:`metadata` to be transmitted to
415 the service-side of the RPC.
416 credentials: An optional CallCredentials for the RPC.
417 wait_for_ready: This is an EXPERIMENTAL argument. An optional flag t
418 enable wait for ready mechanism.
419 compression: An element of grpc.compression, e.g.
420 grpc.compression.Gzip. This is an EXPERIMENTAL option.
424 class UnaryUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
425 """Affords intercepting unary-unary invocations.
427 This is an EXPERIMENTAL API.
431 def intercept_unary_unary(self, continuation, client_call_details, request):
432 """Intercepts a unary-unary invocation asynchronously.
435 continuation: A function that proceeds with the invocation by
436 executing the next interceptor in chain or invoking the
437 actual RPC on the underlying Channel. It is the interceptor's
438 responsibility to call it if it decides to move the RPC forward.
439 The interceptor can use
440 `response_future = continuation(client_call_details, request)`
441 to continue with the RPC. `continuation` returns an object that is
442 both a Call for the RPC and a Future. In the event of RPC
443 completion, the return Call-Future's result value will be
444 the response message of the RPC. Should the event terminate
445 with non-OK status, the returned Call-Future's exception value
447 client_call_details: A ClientCallDetails object describing the
449 request: The request value for the RPC.
452 An object that is both a Call for the RPC and a Future.
453 In the event of RPC completion, the return Call-Future's
454 result value will be the response message of the RPC.
455 Should the event terminate with non-OK status, the returned
456 Call-Future's exception value will be an RpcError.
458 raise NotImplementedError()
461 class UnaryStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
462 """Affords intercepting unary-stream invocations.
464 This is an EXPERIMENTAL API.
468 def intercept_unary_stream(self, continuation, client_call_details,
470 """Intercepts a unary-stream invocation.
473 continuation: A function that proceeds with the invocation by
474 executing the next interceptor in chain or invoking the
475 actual RPC on the underlying Channel. It is the interceptor's
476 responsibility to call it if it decides to move the RPC forward.
477 The interceptor can use
478 `response_iterator = continuation(client_call_details, request)`
479 to continue with the RPC. `continuation` returns an object that is
480 both a Call for the RPC and an iterator for response values.
481 Drawing response values from the returned Call-iterator may
482 raise RpcError indicating termination of the RPC with non-OK
484 client_call_details: A ClientCallDetails object describing the
486 request: The request value for the RPC.
489 An object that is both a Call for the RPC and an iterator of
490 response values. Drawing response values from the returned
491 Call-iterator may raise RpcError indicating termination of
492 the RPC with non-OK status.
494 raise NotImplementedError()
497 class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
498 """Affords intercepting stream-unary invocations.
500 This is an EXPERIMENTAL API.
504 def intercept_stream_unary(self, continuation, client_call_details,
506 """Intercepts a stream-unary invocation asynchronously.
509 continuation: A function that proceeds with the invocation by
510 executing the next interceptor in chain or invoking the
511 actual RPC on the underlying Channel. It is the interceptor's
512 responsibility to call it if it decides to move the RPC forward.
513 The interceptor can use
514 `response_future = continuation(client_call_details, request_iterator)`
515 to continue with the RPC. `continuation` returns an object that is
516 both a Call for the RPC and a Future. In the event of RPC completion,
517 the return Call-Future's result value will be the response message
518 of the RPC. Should the event terminate with non-OK status, the
519 returned Call-Future's exception value will be an RpcError.
520 client_call_details: A ClientCallDetails object describing the
522 request_iterator: An iterator that yields request values for the RPC.
525 An object that is both a Call for the RPC and a Future.
526 In the event of RPC completion, the return Call-Future's
527 result value will be the response message of the RPC.
528 Should the event terminate with non-OK status, the returned
529 Call-Future's exception value will be an RpcError.
531 raise NotImplementedError()
534 class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
535 """Affords intercepting stream-stream invocations.
537 This is an EXPERIMENTAL API.
541 def intercept_stream_stream(self, continuation, client_call_details,
543 """Intercepts a stream-stream invocation.
546 continuation: A function that proceeds with the invocation by
547 executing the next interceptor in chain or invoking the
548 actual RPC on the underlying Channel. It is the interceptor's
549 responsibility to call it if it decides to move the RPC forward.
550 The interceptor can use
551 `response_iterator = continuation(client_call_details, request_iterator)`
552 to continue with the RPC. `continuation` returns an object that is
553 both a Call for the RPC and an iterator for response values.
554 Drawing response values from the returned Call-iterator may
555 raise RpcError indicating termination of the RPC with non-OK
557 client_call_details: A ClientCallDetails object describing the
559 request_iterator: An iterator that yields request values for the RPC.
562 An object that is both a Call for the RPC and an iterator of
563 response values. Drawing response values from the returned
564 Call-iterator may raise RpcError indicating termination of
565 the RPC with non-OK status.
567 raise NotImplementedError()
570 ############ Authentication & Authorization Interfaces & Classes #############
573 class ChannelCredentials(object):
574 """An encapsulation of the data required to create a secure Channel.
576 This class has no supported interface - it exists to define the type of its
577 instances and its instances exist to be passed to other functions. For
578 example, ssl_channel_credentials returns an instance of this class and
579 secure_channel requires an instance of this class.
582 def __init__(self, credentials):
583 self._credentials = credentials
586 class CallCredentials(object):
587 """An encapsulation of the data required to assert an identity over a call.
589 A CallCredentials has to be used with secure Channel, otherwise the
590 metadata will not be transmitted to the server.
592 A CallCredentials may be composed with ChannelCredentials to always assert
593 identity for every call over that Channel.
595 This class has no supported interface - it exists to define the type of its
596 instances and its instances exist to be passed to other functions.
599 def __init__(self, credentials):
600 self._credentials = credentials
603 class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
604 """Provides information to call credentials metadata plugins.
607 service_url: A string URL of the service being called into.
608 method_name: A string of the fully qualified method name being called.
612 class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)):
613 """Callback object received by a metadata plugin."""
615 def __call__(self, metadata, error):
616 """Passes to the gRPC runtime authentication metadata for an RPC.
619 metadata: The :term:`metadata` used to construct the CallCredentials.
620 error: An Exception to indicate error or None to indicate success.
622 raise NotImplementedError()
625 class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
626 """A specification for custom authentication."""
628 def __call__(self, context, callback):
629 """Implements authentication by passing metadata to a callback.
631 Implementations of this method must not block.
634 context: An AuthMetadataContext providing information on the RPC that
635 the plugin is being called to authenticate.
636 callback: An AuthMetadataPluginCallback to be invoked either
637 synchronously or asynchronously.
639 raise NotImplementedError()
642 class ServerCredentials(object):
643 """An encapsulation of the data required to open a secure port on a Server.
645 This class has no supported interface - it exists to define the type of its
646 instances and its instances exist to be passed to other functions.
649 def __init__(self, credentials):
650 self._credentials = credentials
653 class ServerCertificateConfiguration(object):
654 """A certificate configuration for use with an SSL-enabled Server.
656 Instances of this class can be returned in the certificate configuration
659 This class has no supported interface -- it exists to define the
660 type of its instances and its instances exist to be passed to
664 def __init__(self, certificate_configuration):
665 self._certificate_configuration = certificate_configuration
668 ######################## Multi-Callable Interfaces ###########################
671 class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
672 """Affords invoking a unary-unary RPC from client-side."""
682 """Synchronously invokes the underlying RPC.
685 request: The request value for the RPC.
686 timeout: An optional duration of time in seconds to allow
688 metadata: Optional :term:`metadata` to be transmitted to the
689 service-side of the RPC.
690 credentials: An optional CallCredentials for the RPC. Only valid for
692 wait_for_ready: This is an EXPERIMENTAL argument. An optional
693 flag to enable wait for ready mechanism
694 compression: An element of grpc.compression, e.g.
695 grpc.compression.Gzip. This is an EXPERIMENTAL option.
698 The response value for the RPC.
701 RpcError: Indicating that the RPC terminated with non-OK status. The
702 raised RpcError will also be a Call for the RPC affording the RPC's
703 metadata, status code, and details.
705 raise NotImplementedError()
715 """Synchronously invokes the underlying RPC.
718 request: The request value for the RPC.
719 timeout: An optional durating of time in seconds to allow for
721 metadata: Optional :term:`metadata` to be transmitted to the
722 service-side of the RPC.
723 credentials: An optional CallCredentials for the RPC. Only valid for
725 wait_for_ready: This is an EXPERIMENTAL argument. An optional
726 flag to enable wait for ready mechanism
727 compression: An element of grpc.compression, e.g.
728 grpc.compression.Gzip. This is an EXPERIMENTAL option.
731 The response value for the RPC and a Call value for the RPC.
734 RpcError: Indicating that the RPC terminated with non-OK status. The
735 raised RpcError will also be a Call for the RPC affording the RPC's
736 metadata, status code, and details.
738 raise NotImplementedError()
748 """Asynchronously invokes the underlying RPC.
751 request: The request value for the RPC.
752 timeout: An optional duration of time in seconds to allow for
754 metadata: Optional :term:`metadata` to be transmitted to the
755 service-side of the RPC.
756 credentials: An optional CallCredentials for the RPC. Only valid for
758 wait_for_ready: This is an EXPERIMENTAL argument. An optional
759 flag to enable wait for ready mechanism
760 compression: An element of grpc.compression, e.g.
761 grpc.compression.Gzip. This is an EXPERIMENTAL option.
764 An object that is both a Call for the RPC and a Future.
765 In the event of RPC completion, the return Call-Future's result
766 value will be the response message of the RPC.
767 Should the event terminate with non-OK status,
768 the returned Call-Future's exception value will be an RpcError.
770 raise NotImplementedError()
773 class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
774 """Affords invoking a unary-stream RPC from client-side."""
784 """Invokes the underlying RPC.
787 request: The request value for the RPC.
788 timeout: An optional duration of time in seconds to allow for
789 the RPC. If None, the timeout is considered infinite.
790 metadata: An optional :term:`metadata` to be transmitted to the
791 service-side of the RPC.
792 credentials: An optional CallCredentials for the RPC. Only valid for
794 wait_for_ready: This is an EXPERIMENTAL argument. An optional
795 flag to enable wait for ready mechanism
796 compression: An element of grpc.compression, e.g.
797 grpc.compression.Gzip. This is an EXPERIMENTAL option.
800 An object that is both a Call for the RPC and an iterator of
801 response values. Drawing response values from the returned
802 Call-iterator may raise RpcError indicating termination of the
803 RPC with non-OK status.
805 raise NotImplementedError()
808 class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
809 """Affords invoking a stream-unary RPC from client-side."""
819 """Synchronously invokes the underlying RPC.
822 request_iterator: An iterator that yields request values for
824 timeout: An optional duration of time in seconds to allow for
825 the RPC. If None, the timeout is considered infinite.
826 metadata: Optional :term:`metadata` to be transmitted to the
827 service-side of the RPC.
828 credentials: An optional CallCredentials for the RPC. Only valid for
830 wait_for_ready: This is an EXPERIMENTAL argument. An optional
831 flag to enable wait for ready mechanism
832 compression: An element of grpc.compression, e.g.
833 grpc.compression.Gzip. This is an EXPERIMENTAL option.
836 The response value for the RPC.
839 RpcError: Indicating that the RPC terminated with non-OK status. The
840 raised RpcError will also implement grpc.Call, affording methods
841 such as metadata, code, and details.
843 raise NotImplementedError()
853 """Synchronously invokes the underlying RPC on the client.
856 request_iterator: An iterator that yields request values for
858 timeout: An optional duration of time in seconds to allow for
859 the RPC. If None, the timeout is considered infinite.
860 metadata: Optional :term:`metadata` to be transmitted to the
861 service-side of the RPC.
862 credentials: An optional CallCredentials for the RPC. Only valid for
864 wait_for_ready: This is an EXPERIMENTAL argument. An optional
865 flag to enable wait for ready mechanism
866 compression: An element of grpc.compression, e.g.
867 grpc.compression.Gzip. This is an EXPERIMENTAL option.
870 The response value for the RPC and a Call object for the RPC.
873 RpcError: Indicating that the RPC terminated with non-OK status. The
874 raised RpcError will also be a Call for the RPC affording the RPC's
875 metadata, status code, and details.
877 raise NotImplementedError()
887 """Asynchronously invokes the underlying RPC on the client.
890 request_iterator: An iterator that yields request values for the RPC.
891 timeout: An optional duration of time in seconds to allow for
892 the RPC. If None, the timeout is considered infinite.
893 metadata: Optional :term:`metadata` to be transmitted to the
894 service-side of the RPC.
895 credentials: An optional CallCredentials for the RPC. Only valid for
897 wait_for_ready: This is an EXPERIMENTAL argument. An optional
898 flag to enable wait for ready mechanism
899 compression: An element of grpc.compression, e.g.
900 grpc.compression.Gzip. This is an EXPERIMENTAL option.
903 An object that is both a Call for the RPC and a Future.
904 In the event of RPC completion, the return Call-Future's result value
905 will be the response message of the RPC. Should the event terminate
906 with non-OK status, the returned Call-Future's exception value will
909 raise NotImplementedError()
912 class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
913 """Affords invoking a stream-stream RPC on client-side."""
923 """Invokes the underlying RPC on the client.
926 request_iterator: An iterator that yields request values for the RPC.
927 timeout: An optional duration of time in seconds to allow for
928 the RPC. If not specified, the timeout is considered infinite.
929 metadata: Optional :term:`metadata` to be transmitted to the
930 service-side of the RPC.
931 credentials: An optional CallCredentials for the RPC. Only valid for
933 wait_for_ready: This is an EXPERIMENTAL argument. An optional
934 flag to enable wait for ready mechanism
935 compression: An element of grpc.compression, e.g.
936 grpc.compression.Gzip. This is an EXPERIMENTAL option.
939 An object that is both a Call for the RPC and an iterator of
940 response values. Drawing response values from the returned
941 Call-iterator may raise RpcError indicating termination of the
942 RPC with non-OK status.
944 raise NotImplementedError()
947 ############################# Channel Interface ##############################
950 class Channel(six.with_metaclass(abc.ABCMeta)):
951 """Affords RPC invocation via generic methods on client-side.
953 Channel objects implement the Context Manager type, although they need not
954 support being entered and exited multiple times.
958 def subscribe(self, callback, try_to_connect=False):
959 """Subscribe to this Channel's connectivity state machine.
961 A Channel may be in any of the states described by ChannelConnectivity.
962 This method allows application to monitor the state transitions.
963 The typical use case is to debug or gain better visibility into gRPC
967 callback: A callable to be invoked with ChannelConnectivity argument.
968 ChannelConnectivity describes current state of the channel.
969 The callable will be invoked immediately upon subscription
970 and again for every change to ChannelConnectivity until it
971 is unsubscribed or this Channel object goes out of scope.
972 try_to_connect: A boolean indicating whether or not this Channel
973 should attempt to connect immediately. If set to False, gRPC
974 runtime decides when to connect.
976 raise NotImplementedError()
979 def unsubscribe(self, callback):
980 """Unsubscribes a subscribed callback from this Channel's connectivity.
983 callback: A callable previously registered with this Channel from
984 having been passed to its "subscribe" method.
986 raise NotImplementedError()
989 def unary_unary(self,
991 request_serializer=None,
992 response_deserializer=None):
993 """Creates a UnaryUnaryMultiCallable for a unary-unary method.
996 method: The name of the RPC method.
997 request_serializer: Optional behaviour for serializing the request
998 message. Request goes unserialized in case None is passed.
999 response_deserializer: Optional behaviour for deserializing the
1000 response message. Response goes undeserialized in case None
1004 A UnaryUnaryMultiCallable value for the named unary-unary method.
1006 raise NotImplementedError()
1009 def unary_stream(self,
1011 request_serializer=None,
1012 response_deserializer=None):
1013 """Creates a UnaryStreamMultiCallable for a unary-stream method.
1016 method: The name of the RPC method.
1017 request_serializer: Optional behaviour for serializing the request
1018 message. Request goes unserialized in case None is passed.
1019 response_deserializer: Optional behaviour for deserializing the
1020 response message. Response goes undeserialized in case None is
1024 A UnaryStreamMultiCallable value for the name unary-stream method.
1026 raise NotImplementedError()
1029 def stream_unary(self,
1031 request_serializer=None,
1032 response_deserializer=None):
1033 """Creates a StreamUnaryMultiCallable for a stream-unary method.
1036 method: The name of the RPC method.
1037 request_serializer: Optional behaviour for serializing the request
1038 message. Request goes unserialized in case None is passed.
1039 response_deserializer: Optional behaviour for deserializing the
1040 response message. Response goes undeserialized in case None is
1044 A StreamUnaryMultiCallable value for the named stream-unary method.
1046 raise NotImplementedError()
1049 def stream_stream(self,
1051 request_serializer=None,
1052 response_deserializer=None):
1053 """Creates a StreamStreamMultiCallable for a stream-stream method.
1056 method: The name of the RPC method.
1057 request_serializer: Optional behaviour for serializing the request
1058 message. Request goes unserialized in case None is passed.
1059 response_deserializer: Optional behaviour for deserializing the
1060 response message. Response goes undeserialized in case None
1064 A StreamStreamMultiCallable value for the named stream-stream method.
1066 raise NotImplementedError()
1070 """Closes this Channel and releases all resources held by it.
1072 Closing the Channel will immediately terminate all RPCs active with the
1073 Channel and it is not valid to invoke new RPCs with the Channel.
1075 This method is idempotent.
1077 raise NotImplementedError()
1080 ########################## Service-Side Context ##############################
1083 class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
1084 """A context object passed to method implementations."""
1087 def invocation_metadata(self):
1088 """Accesses the metadata from the sent by the client.
1091 The invocation :term:`metadata`.
1093 raise NotImplementedError()
1097 """Identifies the peer that invoked the RPC being serviced.
1100 A string identifying the peer that invoked the RPC being serviced.
1101 The string format is determined by gRPC runtime.
1103 raise NotImplementedError()
1106 def peer_identities(self):
1107 """Gets one or more peer identity(s).
1110 servicer_context.auth_context().get(servicer_context.peer_identity_key())
1113 An iterable of the identities, or None if the call is not
1114 authenticated. Each identity is returned as a raw bytes type.
1116 raise NotImplementedError()
1119 def peer_identity_key(self):
1120 """The auth property used to identify the peer.
1122 For example, "x509_common_name" or "x509_subject_alternative_name" are
1123 used to identify an SSL peer.
1126 The auth property (string) that indicates the
1127 peer identity, or None if the call is not authenticated.
1129 raise NotImplementedError()
1132 def auth_context(self):
1133 """Gets the auth context for the call.
1136 A map of strings to an iterable of bytes for each auth property.
1138 raise NotImplementedError()
1140 def set_compression(self, compression):
1141 """Set the compression algorithm to be used for the entire call.
1143 This is an EXPERIMENTAL method.
1146 compression: An element of grpc.compression, e.g.
1147 grpc.compression.Gzip.
1149 raise NotImplementedError()
1152 def send_initial_metadata(self, initial_metadata):
1153 """Sends the initial metadata value to the client.
1155 This method need not be called by implementations if they have no
1156 metadata to add to what the gRPC runtime will transmit.
1159 initial_metadata: The initial :term:`metadata`.
1161 raise NotImplementedError()
1164 def set_trailing_metadata(self, trailing_metadata):
1165 """Sets the trailing metadata for the RPC.
1167 Sets the trailing metadata to be sent upon completion of the RPC.
1169 If this method is invoked multiple times throughout the lifetime of an
1170 RPC, the value supplied in the final invocation will be the value sent
1173 This method need not be called by implementations if they have no
1174 metadata to add to what the gRPC runtime will transmit.
1177 trailing_metadata: The trailing :term:`metadata`.
1179 raise NotImplementedError()
1182 def abort(self, code, details):
1183 """Raises an exception to terminate the RPC with a non-OK status.
1185 The code and details passed as arguments will supercede any existing
1189 code: A StatusCode object to be sent to the client.
1190 It must not be StatusCode.OK.
1191 details: A UTF-8-encodable string to be sent to the client upon
1192 termination of the RPC.
1195 Exception: An exception is always raised to signal the abortion the
1196 RPC to the gRPC runtime.
1198 raise NotImplementedError()
1201 def abort_with_status(self, status):
1202 """Raises an exception to terminate the RPC with a non-OK status.
1204 The status passed as argument will supercede any existing status code,
1205 status message and trailing metadata.
1207 This is an EXPERIMENTAL API.
1210 status: A grpc.Status object. The status code in it must not be
1214 Exception: An exception is always raised to signal the abortion the
1215 RPC to the gRPC runtime.
1217 raise NotImplementedError()
1220 def set_code(self, code):
1221 """Sets the value to be used as status code upon RPC completion.
1223 This method need not be called by method implementations if they wish
1224 the gRPC runtime to determine the status code of the RPC.
1227 code: A StatusCode object to be sent to the client.
1229 raise NotImplementedError()
1232 def set_details(self, details):
1233 """Sets the value to be used as detail string upon RPC completion.
1235 This method need not be called by method implementations if they have
1236 no details to transmit.
1239 details: A UTF-8-encodable string to be sent to the client upon
1240 termination of the RPC.
1242 raise NotImplementedError()
1244 def disable_next_message_compression(self):
1245 """Disables compression for the next response message.
1247 This is an EXPERIMENTAL method.
1249 This method will override any compression configuration set during
1250 server creation or set on the call.
1252 raise NotImplementedError()
1255 ##################### Service-Side Handler Interfaces ########################
1258 class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
1259 """An implementation of a single RPC method.
1262 request_streaming: Whether the RPC supports exactly one request message
1263 or any arbitrary number of request messages.
1264 response_streaming: Whether the RPC supports exactly one response message
1265 or any arbitrary number of response messages.
1266 request_deserializer: A callable behavior that accepts a byte string and
1267 returns an object suitable to be passed to this object's business
1268 logic, or None to indicate that this object's business logic should be
1269 passed the raw request bytes.
1270 response_serializer: A callable behavior that accepts an object produced
1271 by this object's business logic and returns a byte string, or None to
1272 indicate that the byte strings produced by this object's business logic
1273 should be transmitted on the wire as they are.
1274 unary_unary: This object's application-specific business logic as a
1275 callable value that takes a request value and a ServicerContext object
1276 and returns a response value. Only non-None if both request_streaming
1277 and response_streaming are False.
1278 unary_stream: This object's application-specific business logic as a
1279 callable value that takes a request value and a ServicerContext object
1280 and returns an iterator of response values. Only non-None if
1281 request_streaming is False and response_streaming is True.
1282 stream_unary: 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 a response value. Only non-None if
1285 request_streaming is True and response_streaming is False.
1286 stream_stream: This object's application-specific business logic as a
1287 callable value that takes an iterator of request values and a
1288 ServicerContext object and returns an iterator of response values.
1289 Only non-None if request_streaming and response_streaming are both
1294 class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
1295 """Describes an RPC that has just arrived for service.
1298 method: The method name of the RPC.
1299 invocation_metadata: The :term:`metadata` sent by the client.
1303 class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
1304 """An implementation of arbitrarily many RPC methods."""
1307 def service(self, handler_call_details):
1308 """Returns the handler for servicing the RPC.
1311 handler_call_details: A HandlerCallDetails describing the RPC.
1314 An RpcMethodHandler with which the RPC may be serviced if the
1315 implementation chooses to service this RPC, or None otherwise.
1317 raise NotImplementedError()
1320 class ServiceRpcHandler(six.with_metaclass(abc.ABCMeta, GenericRpcHandler)):
1321 """An implementation of RPC methods belonging to a service.
1323 A service handles RPC methods with structured names of the form
1324 '/Service.Name/Service.Method', where 'Service.Name' is the value
1325 returned by service_name(), and 'Service.Method' is the method
1326 name. A service can have multiple method names, but only a single
1331 def service_name(self):
1332 """Returns this service's name.
1337 raise NotImplementedError()
1340 #################### Service-Side Interceptor Interfaces #####################
1343 class ServerInterceptor(six.with_metaclass(abc.ABCMeta)):
1344 """Affords intercepting incoming RPCs on the service-side.
1346 This is an EXPERIMENTAL API.
1350 def intercept_service(self, continuation, handler_call_details):
1351 """Intercepts incoming RPCs before handing them over to a handler.
1354 continuation: A function that takes a HandlerCallDetails and
1355 proceeds to invoke the next interceptor in the chain, if any,
1356 or the RPC handler lookup logic, with the call details passed
1357 as an argument, and returns an RpcMethodHandler instance if
1358 the RPC is considered serviced, or None otherwise.
1359 handler_call_details: A HandlerCallDetails describing the RPC.
1362 An RpcMethodHandler with which the RPC may be serviced if the
1363 interceptor chooses to service this RPC, or None otherwise.
1365 raise NotImplementedError()
1368 ############################# Server Interface ###############################
1371 class Server(six.with_metaclass(abc.ABCMeta)):
1372 """Services RPCs."""
1375 def add_generic_rpc_handlers(self, generic_rpc_handlers):
1376 """Registers GenericRpcHandlers with this Server.
1378 This method is only safe to call before the server is started.
1381 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1382 used to service RPCs.
1384 raise NotImplementedError()
1387 def add_insecure_port(self, address):
1388 """Opens an insecure port for accepting RPCs.
1390 This method may only be called before starting the server.
1393 address: The address for which to open a port. If the port is 0,
1394 or not specified in the address, then gRPC runtime will choose a port.
1397 An integer port on which server will accept RPC requests.
1399 raise NotImplementedError()
1402 def add_secure_port(self, address, server_credentials):
1403 """Opens a secure port for accepting RPCs.
1405 This method may only be called before starting the server.
1408 address: The address for which to open a port.
1409 if the port is 0, or not specified in the address, then gRPC
1410 runtime will choose a port.
1411 server_credentials: A ServerCredentials object.
1414 An integer port on which server will accept RPC requests.
1416 raise NotImplementedError()
1420 """Starts this Server.
1422 This method may only be called once. (i.e. it is not idempotent).
1424 raise NotImplementedError()
1427 def stop(self, grace):
1428 """Stops this Server.
1430 This method immediately stop service of new RPCs in all cases.
1432 If a grace period is specified, this method returns immediately
1433 and all RPCs active at the end of the grace period are aborted.
1434 If a grace period is not specified (by passing None for `grace`),
1435 all existing RPCs are aborted immediately and this method
1436 blocks until the last RPC handler terminates.
1438 This method is idempotent and may be called at any time.
1439 Passing a smaller grace value in a subsequent call will have
1440 the effect of stopping the Server sooner (passing None will
1441 have the effect of stopping the server immediately). Passing
1442 a larger grace value in a subsequent call *will not* have the
1443 effect of stopping the server later (i.e. the most restrictive
1444 grace value is used).
1447 grace: A duration of time in seconds or None.
1450 A threading.Event that will be set when this Server has completely
1451 stopped, i.e. when running RPCs either complete or are aborted and
1452 all handlers have terminated.
1454 raise NotImplementedError()
1456 def wait_for_termination(self, timeout=None):
1457 """Block current thread until the server stops.
1459 This is an EXPERIMENTAL API.
1461 The wait will not consume computational resources during blocking, and
1462 it will block until one of the two following conditions are met:
1464 1) The server is stopped or terminated;
1465 2) A timeout occurs if timeout is not `None`.
1467 The timeout argument works in the same way as `threading.Event.wait()`.
1468 https://docs.python.org/3/library/threading.html#threading.Event.wait
1471 timeout: A floating point number specifying a timeout for the
1472 operation in seconds.
1475 A bool indicates if the operation times out.
1477 raise NotImplementedError()
1480 ################################# Functions ################################
1483 def unary_unary_rpc_method_handler(behavior,
1484 request_deserializer=None,
1485 response_serializer=None):
1486 """Creates an RpcMethodHandler for a unary-unary RPC method.
1489 behavior: The implementation of an RPC that accepts one request
1490 and returns one response.
1491 request_deserializer: An optional behavior for request deserialization.
1492 response_serializer: An optional behavior for response serialization.
1495 An RpcMethodHandler object that is typically used by grpc.Server.
1497 from grpc import _utilities # pylint: disable=cyclic-import
1498 return _utilities.RpcMethodHandler(False, False, request_deserializer,
1499 response_serializer, behavior, None,
1503 def unary_stream_rpc_method_handler(behavior,
1504 request_deserializer=None,
1505 response_serializer=None):
1506 """Creates an RpcMethodHandler for a unary-stream RPC method.
1509 behavior: The implementation of an RPC that accepts one request
1510 and returns an iterator of response values.
1511 request_deserializer: An optional behavior for request deserialization.
1512 response_serializer: An optional behavior for response serialization.
1515 An RpcMethodHandler object that is typically used by grpc.Server.
1517 from grpc import _utilities # pylint: disable=cyclic-import
1518 return _utilities.RpcMethodHandler(False, True, request_deserializer,
1519 response_serializer, None, behavior,
1523 def stream_unary_rpc_method_handler(behavior,
1524 request_deserializer=None,
1525 response_serializer=None):
1526 """Creates an RpcMethodHandler for a stream-unary RPC method.
1529 behavior: The implementation of an RPC that accepts an iterator of
1530 request values and returns a single response value.
1531 request_deserializer: An optional behavior for request deserialization.
1532 response_serializer: An optional behavior for response serialization.
1535 An RpcMethodHandler object that is typically used by grpc.Server.
1537 from grpc import _utilities # pylint: disable=cyclic-import
1538 return _utilities.RpcMethodHandler(True, False, request_deserializer,
1539 response_serializer, None, None,
1543 def stream_stream_rpc_method_handler(behavior,
1544 request_deserializer=None,
1545 response_serializer=None):
1546 """Creates an RpcMethodHandler for a stream-stream RPC method.
1549 behavior: The implementation of an RPC that accepts an iterator of
1550 request values and returns an iterator of response values.
1551 request_deserializer: An optional behavior for request deserialization.
1552 response_serializer: An optional behavior for response serialization.
1555 An RpcMethodHandler object that is typically used by grpc.Server.
1557 from grpc import _utilities # pylint: disable=cyclic-import
1558 return _utilities.RpcMethodHandler(True, True, request_deserializer,
1559 response_serializer, None, None, None,
1563 def method_handlers_generic_handler(service, method_handlers):
1564 """Creates a GenericRpcHandler from RpcMethodHandlers.
1567 service: The name of the service that is implemented by the
1569 method_handlers: A dictionary that maps method names to corresponding
1573 A GenericRpcHandler. This is typically added to the grpc.Server object
1574 with add_generic_rpc_handlers() before starting the server.
1576 from grpc import _utilities # pylint: disable=cyclic-import
1577 return _utilities.DictionaryGenericHandler(service, method_handlers)
1580 def ssl_channel_credentials(root_certificates=None,
1582 certificate_chain=None):
1583 """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1586 root_certificates: The PEM-encoded root certificates as a byte string,
1587 or None to retrieve them from a default location chosen by gRPC
1589 private_key: The PEM-encoded private key as a byte string, or None if no
1590 private key should be used.
1591 certificate_chain: The PEM-encoded certificate chain as a byte string
1592 to use or None if no certificate chain should be used.
1595 A ChannelCredentials for use with an SSL-enabled Channel.
1597 return ChannelCredentials(
1598 _cygrpc.SSLChannelCredentials(root_certificates, private_key,
1602 def metadata_call_credentials(metadata_plugin, name=None):
1603 """Construct CallCredentials from an AuthMetadataPlugin.
1606 metadata_plugin: An AuthMetadataPlugin to use for authentication.
1607 name: An optional name for the plugin.
1612 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1613 return _plugin_wrapping.metadata_plugin_call_credentials(
1614 metadata_plugin, name)
1617 def access_token_call_credentials(access_token):
1618 """Construct CallCredentials from an access token.
1621 access_token: A string to place directly in the http request
1622 authorization header, for example
1623 "authorization: Bearer <access_token>".
1628 from grpc import _auth # pylint: disable=cyclic-import
1629 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1630 return _plugin_wrapping.metadata_plugin_call_credentials(
1631 _auth.AccessTokenAuthMetadataPlugin(access_token), None)
1634 def composite_call_credentials(*call_credentials):
1635 """Compose multiple CallCredentials to make a new CallCredentials.
1638 *call_credentials: At least two CallCredentials objects.
1641 A CallCredentials object composed of the given CallCredentials objects.
1643 return CallCredentials(
1644 _cygrpc.CompositeCallCredentials(
1645 tuple(single_call_credentials._credentials
1646 for single_call_credentials in call_credentials)))
1649 def composite_channel_credentials(channel_credentials, *call_credentials):
1650 """Compose a ChannelCredentials and one or more CallCredentials objects.
1653 channel_credentials: A ChannelCredentials object.
1654 *call_credentials: One or more CallCredentials objects.
1657 A ChannelCredentials composed of the given ChannelCredentials and
1658 CallCredentials objects.
1660 return ChannelCredentials(
1661 _cygrpc.CompositeChannelCredentials(
1662 tuple(single_call_credentials._credentials
1663 for single_call_credentials in call_credentials),
1664 channel_credentials._credentials))
1667 def ssl_server_credentials(private_key_certificate_chain_pairs,
1668 root_certificates=None,
1669 require_client_auth=False):
1670 """Creates a ServerCredentials for use with an SSL-enabled Server.
1673 private_key_certificate_chain_pairs: A list of pairs of the form
1674 [PEM-encoded private key, PEM-encoded certificate chain].
1675 root_certificates: An optional byte string of PEM-encoded client root
1676 certificates that the server will use to verify client authentication.
1677 If omitted, require_client_auth must also be False.
1678 require_client_auth: A boolean indicating whether or not to require
1679 clients to be authenticated. May only be True if root_certificates
1683 A ServerCredentials for use with an SSL-enabled Server. Typically, this
1684 object is an argument to add_secure_port() method during server setup.
1686 if not private_key_certificate_chain_pairs:
1688 'At least one private key-certificate chain pair is required!')
1689 elif require_client_auth and root_certificates is None:
1691 'Illegal to require client auth without providing root certificates!'
1694 return ServerCredentials(
1695 _cygrpc.server_credentials_ssl(root_certificates, [
1696 _cygrpc.SslPemKeyCertPair(key, pem)
1697 for key, pem in private_key_certificate_chain_pairs
1698 ], require_client_auth))
1701 def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
1702 root_certificates=None):
1703 """Creates a ServerCertificateConfiguration for use with a Server.
1706 private_key_certificate_chain_pairs: A collection of pairs of
1707 the form [PEM-encoded private key, PEM-encoded certificate
1709 root_certificates: An optional byte string of PEM-encoded client root
1710 certificates that the server will use to verify client authentication.
1713 A ServerCertificateConfiguration that can be returned in the certificate
1714 configuration fetching callback.
1716 if private_key_certificate_chain_pairs:
1717 return ServerCertificateConfiguration(
1718 _cygrpc.server_certificate_config_ssl(root_certificates, [
1719 _cygrpc.SslPemKeyCertPair(key, pem)
1720 for key, pem in private_key_certificate_chain_pairs
1724 'At least one private key-certificate chain pair is required!')
1727 def dynamic_ssl_server_credentials(initial_certificate_configuration,
1728 certificate_configuration_fetcher,
1729 require_client_authentication=False):
1730 """Creates a ServerCredentials for use with an SSL-enabled Server.
1733 initial_certificate_configuration (ServerCertificateConfiguration): The
1734 certificate configuration with which the server will be initialized.
1735 certificate_configuration_fetcher (callable): A callable that takes no
1736 arguments and should return a ServerCertificateConfiguration to
1737 replace the server's current certificate, or None for no change
1738 (i.e., the server will continue its current certificate
1739 config). The library will call this callback on *every* new
1740 client connection before starting the TLS handshake with the
1741 client, thus allowing the user application to optionally
1742 return a new ServerCertificateConfiguration that the server will then
1743 use for the handshake.
1744 require_client_authentication: A boolean indicating whether or not to
1745 require clients to be authenticated.
1748 A ServerCredentials.
1750 return ServerCredentials(
1751 _cygrpc.server_credentials_ssl_dynamic_cert_config(
1752 initial_certificate_configuration,
1753 certificate_configuration_fetcher, require_client_authentication))
1757 class LocalConnectionType(enum.Enum):
1758 """Types of local connection for local credential creation.
1761 UDS: Unix domain socket connections
1762 LOCAL_TCP: Local TCP connections.
1764 UDS = _cygrpc.LocalConnectionType.uds
1765 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
1768 def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1769 """Creates a local ChannelCredentials used for local connections.
1771 This is an EXPERIMENTAL API.
1773 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1774 also UDS connections.
1776 The connections created by local channel credentials are not
1777 encrypted, but will be checked if they are local or not.
1778 The UDS connections are considered secure by providing peer authentication
1779 and data confidentiality while TCP connections are considered insecure.
1781 It is allowed to transmit call credentials over connections created by
1782 local channel credentials.
1784 Local channel credentials are useful for 1) eliminating insecure_channel usage;
1785 2) enable unit testing for call credentials without setting up secrets.
1788 local_connect_type: Local connection type (either
1789 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1792 A ChannelCredentials for use with a local Channel
1794 return ChannelCredentials(
1795 _cygrpc.channel_credentials_local(local_connect_type.value))
1798 def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1799 """Creates a local ServerCredentials used for local connections.
1801 This is an EXPERIMENTAL API.
1803 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1804 also UDS connections.
1806 The connections created by local server credentials are not
1807 encrypted, but will be checked if they are local or not.
1808 The UDS connections are considered secure by providing peer authentication
1809 and data confidentiality while TCP connections are considered insecure.
1811 It is allowed to transmit call credentials over connections created by local
1814 Local server credentials are useful for 1) eliminating insecure_channel usage;
1815 2) enable unit testing for call credentials without setting up secrets.
1818 local_connect_type: Local connection type (either
1819 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1822 A ServerCredentials for use with a local Server
1824 return ServerCredentials(
1825 _cygrpc.server_credentials_local(local_connect_type.value))
1828 def channel_ready_future(channel):
1829 """Creates a Future that tracks when a Channel is ready.
1831 Cancelling the Future does not affect the channel's state machine.
1832 It merely decouples the Future from channel state machine.
1835 channel: A Channel object.
1838 A Future object that matures when the channel connectivity is
1839 ChannelConnectivity.READY.
1841 from grpc import _utilities # pylint: disable=cyclic-import
1842 return _utilities.channel_ready_future(channel)
1845 def insecure_channel(target, options=None, compression=None):
1846 """Creates an insecure Channel to a server.
1848 The returned Channel is thread-safe.
1851 target: The server address
1852 options: An optional list of key-value pairs (channel args
1853 in gRPC Core runtime) to configure the channel.
1854 compression: An optional value indicating the compression method to be
1855 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1860 from grpc import _channel # pylint: disable=cyclic-import
1861 return _channel.Channel(target, () if options is None else options, None,
1865 def secure_channel(target, credentials, options=None, compression=None):
1866 """Creates a secure Channel to a server.
1868 The returned Channel is thread-safe.
1871 target: The server address.
1872 credentials: A ChannelCredentials instance.
1873 options: An optional list of key-value pairs (channel args
1874 in gRPC Core runtime) to configure the channel.
1875 compression: An optional value indicating the compression method to be
1876 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1881 from grpc import _channel # pylint: disable=cyclic-import
1882 from grpc.experimental import _insecure_channel_credentials
1883 if credentials._credentials is _insecure_channel_credentials:
1885 "secure_channel cannot be called with insecure credentials." +
1886 " Call insecure_channel instead.")
1887 return _channel.Channel(target, () if options is None else options,
1888 credentials._credentials, compression)
1891 def intercept_channel(channel, *interceptors):
1892 """Intercepts a channel through a set of interceptors.
1894 This is an EXPERIMENTAL API.
1898 interceptors: Zero or more objects of type
1899 UnaryUnaryClientInterceptor,
1900 UnaryStreamClientInterceptor,
1901 StreamUnaryClientInterceptor, or
1902 StreamStreamClientInterceptor.
1903 Interceptors are given control in the order they are listed.
1906 A Channel that intercepts each invocation via the provided interceptors.
1909 TypeError: If interceptor does not derive from any of
1910 UnaryUnaryClientInterceptor,
1911 UnaryStreamClientInterceptor,
1912 StreamUnaryClientInterceptor, or
1913 StreamStreamClientInterceptor.
1915 from grpc import _interceptor # pylint: disable=cyclic-import
1916 return _interceptor.intercept_channel(channel, *interceptors)
1919 def server(thread_pool,
1923 maximum_concurrent_rpcs=None,
1925 """Creates a Server with which RPCs can be serviced.
1928 thread_pool: A futures.ThreadPoolExecutor to be used by the Server
1929 to execute RPC handlers.
1930 handlers: An optional list of GenericRpcHandlers used for executing RPCs.
1931 More handlers may be added by calling add_generic_rpc_handlers any time
1932 before the server is started.
1933 interceptors: An optional list of ServerInterceptor objects that observe
1934 and optionally manipulate the incoming RPCs before handing them over to
1935 handlers. The interceptors are given control in the order they are
1936 specified. This is an EXPERIMENTAL API.
1937 options: An optional list of key-value pairs (channel args in gRPC runtime)
1938 to configure the channel.
1939 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
1940 will service before returning RESOURCE_EXHAUSTED status, or None to
1942 compression: An element of grpc.compression, e.g.
1943 grpc.compression.Gzip. This compression algorithm will be used for the
1944 lifetime of the server unless overridden. This is an EXPERIMENTAL option.
1949 from grpc import _server # pylint: disable=cyclic-import
1950 return _server.create_server(thread_pool,
1951 () if handlers is None else handlers,
1952 () if interceptors is None else interceptors,
1953 () if options is None else options,
1954 maximum_concurrent_rpcs, compression)
1957 @contextlib.contextmanager
1958 def _create_servicer_context(rpc_event, state, request_deserializer):
1959 from grpc import _server # pylint: disable=cyclic-import
1960 context = _server._Context(rpc_event, state, request_deserializer)
1962 context._finalize_state() # pylint: disable=protected-access
1966 class Compression(enum.IntEnum):
1967 """Indicates the compression method to be used for an RPC.
1969 This enumeration is part of an EXPERIMENTAL API.
1972 NoCompression: Do not use compression algorithm.
1973 Deflate: Use "Deflate" compression algorithm.
1974 Gzip: Use "Gzip" compression algorithm.
1976 NoCompression = _compression.NoCompression
1977 Deflate = _compression.Deflate
1978 Gzip = _compression.Gzip
1981 ################################### __all__ #################################
1984 'FutureTimeoutError',
1985 'FutureCancelledError',
1987 'ChannelConnectivity',
1993 'ChannelCredentials',
1995 'AuthMetadataContext',
1996 'AuthMetadataPluginCallback',
1997 'AuthMetadataPlugin',
1999 'ClientCallDetails',
2000 'ServerCertificateConfiguration',
2001 'ServerCredentials',
2002 'LocalConnectionType',
2003 'UnaryUnaryMultiCallable',
2004 'UnaryStreamMultiCallable',
2005 'StreamUnaryMultiCallable',
2006 'StreamStreamMultiCallable',
2007 'UnaryUnaryClientInterceptor',
2008 'UnaryStreamClientInterceptor',
2009 'StreamUnaryClientInterceptor',
2010 'StreamStreamClientInterceptor',
2014 'HandlerCallDetails',
2015 'GenericRpcHandler',
2016 'ServiceRpcHandler',
2018 'ServerInterceptor',
2019 'unary_unary_rpc_method_handler',
2020 'unary_stream_rpc_method_handler',
2021 'stream_unary_rpc_method_handler',
2022 'stream_stream_rpc_method_handler',
2023 'method_handlers_generic_handler',
2024 'ssl_channel_credentials',
2025 'metadata_call_credentials',
2026 'access_token_call_credentials',
2027 'composite_call_credentials',
2028 'composite_channel_credentials',
2029 'local_channel_credentials',
2030 'local_server_credentials',
2031 'ssl_server_credentials',
2032 'ssl_server_certificate_configuration',
2033 'dynamic_ssl_server_credentials',
2034 'channel_ready_future',
2037 'intercept_channel',
2041 ############################### Extension Shims ################################
2043 # Here to maintain backwards compatibility; avoid using these in new code!
2046 sys.modules.update({'grpc.tools': grpc_tools})
2051 sys.modules.update({'grpc.health': grpc_health})
2055 import grpc_reflection
2056 sys.modules.update({'grpc.reflection': grpc_reflection})