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."""
22 from grpc import _compression
23 from grpc._cython import cygrpc as _cygrpc
24 from grpc._runtime_protos import protos
25 from grpc._runtime_protos import protos_and_services
26 from grpc._runtime_protos import services
29 logging.getLogger(__name__).addHandler(logging.NullHandler())
32 # pylint: disable=ungrouped-imports
33 from grpc._grpcio_metadata import __version__
37 ############################## Future Interface ###############################
40 class FutureTimeoutError(Exception):
41 """Indicates that a method call on a Future timed out."""
44 class FutureCancelledError(Exception):
45 """Indicates that the computation underlying a Future was cancelled."""
48 class Future(six.with_metaclass(abc.ABCMeta)):
49 """A representation of a computation in another control flow.
51 Computations represented by a Future may be yet to be begun,
52 may be ongoing, or may have already completed.
57 """Attempts to cancel the computation.
59 This method does not block.
63 Returns True if the computation was canceled.
65 Returns False under all other circumstances, for example:
67 1. computation has begun and could not be canceled.
68 2. computation has finished
69 3. computation is scheduled for execution and it is impossible
70 to determine its state without blocking.
72 raise NotImplementedError()
76 """Describes whether the computation was cancelled.
78 This method does not block.
82 Returns True if the computation was cancelled before its result became
85 Returns False under all other circumstances, for example:
87 1. computation was not cancelled.
88 2. computation's result is available.
90 raise NotImplementedError()
94 """Describes whether the computation is taking place.
96 This method does not block.
99 Returns True if the computation is scheduled for execution or
102 Returns False if the computation already executed or was cancelled.
104 raise NotImplementedError()
108 """Describes whether the computation has taken place.
110 This method does not block.
114 Returns True if the computation already executed or was cancelled.
115 Returns False if the computation is scheduled for execution or
117 This is exactly opposite of the running() method's result.
119 raise NotImplementedError()
122 def result(self, timeout=None):
123 """Returns the result of the computation or raises its exception.
125 This method may return immediately or may block.
128 timeout: The length of time in seconds to wait for the computation to
129 finish or be cancelled. If None, the call will block until the
130 computations's termination.
133 The return value of the computation.
136 FutureTimeoutError: If a timeout value is passed and the computation
137 does not terminate within the allotted time.
138 FutureCancelledError: If the computation was cancelled.
139 Exception: If the computation raised an exception, this call will
140 raise the same exception.
142 raise NotImplementedError()
145 def exception(self, timeout=None):
146 """Return the exception raised by the computation.
148 This method may return immediately or may block.
151 timeout: The length of time in seconds to wait for the computation to
152 terminate or be cancelled. If None, the call will block until the
153 computations's termination.
156 The exception raised by the computation, or None if the computation
157 did not raise an exception.
160 FutureTimeoutError: If a timeout value is passed and the computation
161 does not terminate within the allotted time.
162 FutureCancelledError: If the computation was cancelled.
164 raise NotImplementedError()
167 def traceback(self, timeout=None):
168 """Access the traceback of the exception raised by the computation.
170 This method may return immediately or may block.
173 timeout: The length of time in seconds to wait for the computation
174 to terminate or be cancelled. If None, the call will block until
175 the computation's termination.
178 The traceback of the exception raised by the computation, or None
179 if the computation did not raise an exception.
182 FutureTimeoutError: If a timeout value is passed and the computation
183 does not terminate within the allotted time.
184 FutureCancelledError: If the computation was cancelled.
186 raise NotImplementedError()
189 def add_done_callback(self, fn):
190 """Adds a function to be called at completion of the computation.
192 The callback will be passed this Future object describing the outcome
193 of the computation. Callbacks will be invoked after the future is
194 terminated, whether successfully or not.
196 If the computation has already completed, the callback will be called
199 Exceptions raised in the callback will be logged at ERROR level, but
200 will not terminate any threads of execution.
203 fn: A callable taking this Future object as its single parameter.
205 raise NotImplementedError()
208 ################################ gRPC Enums ##################################
212 class ChannelConnectivity(enum.Enum):
213 """Mirrors grpc_connectivity_state in the gRPC Core.
216 IDLE: The channel is idle.
217 CONNECTING: The channel is connecting.
218 READY: The channel is ready to conduct RPCs.
219 TRANSIENT_FAILURE: The channel has seen a failure from which it expects
221 SHUTDOWN: The channel has seen a failure from which it cannot recover.
223 IDLE = (_cygrpc.ConnectivityState.idle, 'idle')
224 CONNECTING = (_cygrpc.ConnectivityState.connecting, 'connecting')
225 READY = (_cygrpc.ConnectivityState.ready, 'ready')
226 TRANSIENT_FAILURE = (_cygrpc.ConnectivityState.transient_failure,
228 SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, 'shutdown')
232 class StatusCode(enum.Enum):
233 """Mirrors grpc_status_code in the gRPC Core.
236 OK: Not an error; returned on success
237 CANCELLED: The operation was cancelled (typically by the caller).
238 UNKNOWN: Unknown error.
239 INVALID_ARGUMENT: Client specified an invalid argument.
240 DEADLINE_EXCEEDED: Deadline expired before operation could complete.
241 NOT_FOUND: Some requested entity (e.g., file or directory) was not found.
242 ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory)
244 PERMISSION_DENIED: The caller does not have permission to execute the specified
246 UNAUTHENTICATED: The request does not have valid authentication credentials for the
248 RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or
249 perhaps the entire file system is out of space.
250 FAILED_PRECONDITION: Operation was rejected because the system is not in a state
251 required for the operation's execution.
252 ABORTED: The operation was aborted, typically due to a concurrency issue
253 like sequencer check failures, transaction aborts, etc.
254 UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service.
255 INTERNAL: Internal errors. Means some invariants expected by underlying
256 system has been broken.
257 UNAVAILABLE: The service is currently unavailable.
258 DATA_LOSS: Unrecoverable data loss or corruption.
260 OK = (_cygrpc.StatusCode.ok, 'ok')
261 CANCELLED = (_cygrpc.StatusCode.cancelled, 'cancelled')
262 UNKNOWN = (_cygrpc.StatusCode.unknown, 'unknown')
263 INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, 'invalid argument')
264 DEADLINE_EXCEEDED = (_cygrpc.StatusCode.deadline_exceeded,
266 NOT_FOUND = (_cygrpc.StatusCode.not_found, 'not found')
267 ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, 'already exists')
268 PERMISSION_DENIED = (_cygrpc.StatusCode.permission_denied,
270 RESOURCE_EXHAUSTED = (_cygrpc.StatusCode.resource_exhausted,
271 'resource exhausted')
272 FAILED_PRECONDITION = (_cygrpc.StatusCode.failed_precondition,
273 'failed precondition')
274 ABORTED = (_cygrpc.StatusCode.aborted, 'aborted')
275 OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, 'out of range')
276 UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, 'unimplemented')
277 INTERNAL = (_cygrpc.StatusCode.internal, 'internal')
278 UNAVAILABLE = (_cygrpc.StatusCode.unavailable, 'unavailable')
279 DATA_LOSS = (_cygrpc.StatusCode.data_loss, 'data loss')
280 UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, 'unauthenticated')
283 ############################# gRPC Status ################################
286 class Status(six.with_metaclass(abc.ABCMeta)):
287 """Describes the status of an RPC.
289 This is an EXPERIMENTAL API.
292 code: A StatusCode object to be sent to the client.
293 details: A UTF-8-encodable string to be sent to the client upon
294 termination of the RPC.
295 trailing_metadata: The trailing :term:`metadata` in the RPC.
299 ############################# gRPC Exceptions ################################
302 class RpcError(Exception):
303 """Raised by the gRPC library to indicate non-OK-status RPC termination."""
306 ############################## Shared Context ################################
309 class RpcContext(six.with_metaclass(abc.ABCMeta)):
310 """Provides RPC-related information and action."""
314 """Describes whether the RPC is active or has terminated.
318 True if RPC is active, False otherwise.
320 raise NotImplementedError()
323 def time_remaining(self):
324 """Describes the length of allowed time remaining for the RPC.
327 A nonnegative float indicating the length of allowed time in seconds
328 remaining for the RPC to complete before it is considered to have
329 timed out, or None if no deadline was specified for the RPC.
331 raise NotImplementedError()
337 Idempotent and has no effect if the RPC has already terminated.
339 raise NotImplementedError()
342 def add_callback(self, callback):
343 """Registers a callback to be called on RPC termination.
346 callback: A no-parameter callable to be called on RPC termination.
349 True if the callback was added and will be called later; False if
350 the callback was not added and will not be called (because the RPC
351 already terminated or some other reason).
353 raise NotImplementedError()
356 ######################### Invocation-Side Context ############################
359 class Call(six.with_metaclass(abc.ABCMeta, RpcContext)):
360 """Invocation-side utility object for an RPC."""
363 def initial_metadata(self):
364 """Accesses the initial metadata sent by the server.
366 This method blocks until the value is available.
369 The initial :term:`metadata`.
371 raise NotImplementedError()
374 def trailing_metadata(self):
375 """Accesses the trailing metadata sent by the server.
377 This method blocks until the value is available.
380 The trailing :term:`metadata`.
382 raise NotImplementedError()
386 """Accesses the status code sent by the server.
388 This method blocks until the value is available.
391 The StatusCode value for the RPC.
393 raise NotImplementedError()
397 """Accesses the details sent by the server.
399 This method blocks until the value is available.
402 The details string of the RPC.
404 raise NotImplementedError()
407 ############## Invocation-Side Interceptor Interfaces & Classes ##############
410 class ClientCallDetails(six.with_metaclass(abc.ABCMeta)):
411 """Describes an RPC to be invoked.
414 method: The method name of the RPC.
415 timeout: An optional duration of time in seconds to allow for the RPC.
416 metadata: Optional :term:`metadata` to be transmitted to
417 the service-side of the RPC.
418 credentials: An optional CallCredentials for the RPC.
419 wait_for_ready: This is an EXPERIMENTAL argument. An optional
420 flag to enable :term:`wait_for_ready` mechanism.
421 compression: An element of grpc.compression, e.g.
422 grpc.compression.Gzip. This is an EXPERIMENTAL option.
426 class UnaryUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
427 """Affords intercepting unary-unary invocations."""
430 def intercept_unary_unary(self, continuation, client_call_details, request):
431 """Intercepts a unary-unary invocation asynchronously.
434 continuation: A function that proceeds with the invocation by
435 executing the next interceptor in chain or invoking the
436 actual RPC on the underlying Channel. It is the interceptor's
437 responsibility to call it if it decides to move the RPC forward.
438 The interceptor can use
439 `response_future = continuation(client_call_details, request)`
440 to continue with the RPC. `continuation` returns an object that is
441 both a Call for the RPC and a Future. In the event of RPC
442 completion, the return Call-Future's result value will be
443 the response message of the RPC. Should the event terminate
444 with non-OK status, the returned Call-Future's exception value
446 client_call_details: A ClientCallDetails object describing the
448 request: The request value for the RPC.
451 An object that is both a Call for the RPC and a Future.
452 In the event of RPC completion, the return Call-Future's
453 result value will be the response message of the RPC.
454 Should the event terminate with non-OK status, the returned
455 Call-Future's exception value will be an RpcError.
457 raise NotImplementedError()
460 class UnaryStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
461 """Affords intercepting unary-stream invocations."""
464 def intercept_unary_stream(self, continuation, client_call_details,
466 """Intercepts a unary-stream invocation.
469 continuation: A function that proceeds with the invocation by
470 executing the next interceptor in chain or invoking the
471 actual RPC on the underlying Channel. It is the interceptor's
472 responsibility to call it if it decides to move the RPC forward.
473 The interceptor can use
474 `response_iterator = continuation(client_call_details, request)`
475 to continue with the RPC. `continuation` returns an object that is
476 both a Call for the RPC and an iterator for response values.
477 Drawing response values from the returned Call-iterator may
478 raise RpcError indicating termination of the RPC with non-OK
480 client_call_details: A ClientCallDetails object describing the
482 request: The request value for the RPC.
485 An object that is both a Call for the RPC and an iterator of
486 response values. Drawing response values from the returned
487 Call-iterator may raise RpcError indicating termination of
488 the RPC with non-OK status. This object *should* also fulfill the
489 Future interface, though it may not.
491 raise NotImplementedError()
494 class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
495 """Affords intercepting stream-unary invocations."""
498 def intercept_stream_unary(self, continuation, client_call_details,
500 """Intercepts a stream-unary invocation asynchronously.
503 continuation: A function that proceeds with the invocation by
504 executing the next interceptor in chain or invoking the
505 actual RPC on the underlying Channel. It is the interceptor's
506 responsibility to call it if it decides to move the RPC forward.
507 The interceptor can use
508 `response_future = continuation(client_call_details, request_iterator)`
509 to continue with the RPC. `continuation` returns an object that is
510 both a Call for the RPC and a Future. In the event of RPC completion,
511 the return Call-Future's result value will be the response message
512 of the RPC. Should the event terminate with non-OK status, the
513 returned Call-Future's exception value will be an RpcError.
514 client_call_details: A ClientCallDetails object describing the
516 request_iterator: An iterator that yields request values for the RPC.
519 An object that is both a Call for the RPC and a Future.
520 In the event of RPC completion, the return Call-Future's
521 result value will be the response message of the RPC.
522 Should the event terminate with non-OK status, the returned
523 Call-Future's exception value will be an RpcError.
525 raise NotImplementedError()
528 class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
529 """Affords intercepting stream-stream invocations."""
532 def intercept_stream_stream(self, continuation, client_call_details,
534 """Intercepts a stream-stream invocation.
537 continuation: A function that proceeds with the invocation by
538 executing the next interceptor in chain or invoking the
539 actual RPC on the underlying Channel. It is the interceptor's
540 responsibility to call it if it decides to move the RPC forward.
541 The interceptor can use
542 `response_iterator = continuation(client_call_details, request_iterator)`
543 to continue with the RPC. `continuation` returns an object that is
544 both a Call for the RPC and an iterator for response values.
545 Drawing response values from the returned Call-iterator may
546 raise RpcError indicating termination of the RPC with non-OK
548 client_call_details: A ClientCallDetails object describing the
550 request_iterator: An iterator that yields request values for the RPC.
553 An object that is both a Call for the RPC and an iterator of
554 response values. Drawing response values from the returned
555 Call-iterator may raise RpcError indicating termination of
556 the RPC with non-OK status. This object *should* also fulfill the
557 Future interface, though it may not.
559 raise NotImplementedError()
562 ############ Authentication & Authorization Interfaces & Classes #############
565 class ChannelCredentials(object):
566 """An encapsulation of the data required to create a secure Channel.
568 This class has no supported interface - it exists to define the type of its
569 instances and its instances exist to be passed to other functions. For
570 example, ssl_channel_credentials returns an instance of this class and
571 secure_channel requires an instance of this class.
574 def __init__(self, credentials):
575 self._credentials = credentials
578 class CallCredentials(object):
579 """An encapsulation of the data required to assert an identity over a call.
581 A CallCredentials has to be used with secure Channel, otherwise the
582 metadata will not be transmitted to the server.
584 A CallCredentials may be composed with ChannelCredentials to always assert
585 identity for every call over that Channel.
587 This class has no supported interface - it exists to define the type of its
588 instances and its instances exist to be passed to other functions.
591 def __init__(self, credentials):
592 self._credentials = credentials
595 class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
596 """Provides information to call credentials metadata plugins.
599 service_url: A string URL of the service being called into.
600 method_name: A string of the fully qualified method name being called.
604 class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)):
605 """Callback object received by a metadata plugin."""
607 def __call__(self, metadata, error):
608 """Passes to the gRPC runtime authentication metadata for an RPC.
611 metadata: The :term:`metadata` used to construct the CallCredentials.
612 error: An Exception to indicate error or None to indicate success.
614 raise NotImplementedError()
617 class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
618 """A specification for custom authentication."""
620 def __call__(self, context, callback):
621 """Implements authentication by passing metadata to a callback.
623 This method will be invoked asynchronously in a separate thread.
626 context: An AuthMetadataContext providing information on the RPC that
627 the plugin is being called to authenticate.
628 callback: An AuthMetadataPluginCallback to be invoked either
629 synchronously or asynchronously.
631 raise NotImplementedError()
634 class ServerCredentials(object):
635 """An encapsulation of the data required to open a secure port on a Server.
637 This class has no supported interface - it exists to define the type of its
638 instances and its instances exist to be passed to other functions.
641 def __init__(self, credentials):
642 self._credentials = credentials
645 class ServerCertificateConfiguration(object):
646 """A certificate configuration for use with an SSL-enabled Server.
648 Instances of this class can be returned in the certificate configuration
651 This class has no supported interface -- it exists to define the
652 type of its instances and its instances exist to be passed to
656 def __init__(self, certificate_configuration):
657 self._certificate_configuration = certificate_configuration
660 ######################## Multi-Callable Interfaces ###########################
663 class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
664 """Affords invoking a unary-unary RPC from client-side."""
674 """Synchronously invokes the underlying RPC.
677 request: The request value for the RPC.
678 timeout: An optional duration of time in seconds to allow
680 metadata: Optional :term:`metadata` to be transmitted to the
681 service-side of the RPC.
682 credentials: An optional CallCredentials for the RPC. Only valid for
684 wait_for_ready: This is an EXPERIMENTAL argument. An optional
685 flag to enable :term:`wait_for_ready` mechanism.
686 compression: An element of grpc.compression, e.g.
687 grpc.compression.Gzip. This is an EXPERIMENTAL option.
690 The response value for the RPC.
693 RpcError: Indicating that the RPC terminated with non-OK status. The
694 raised RpcError will also be a Call for the RPC affording the RPC's
695 metadata, status code, and details.
697 raise NotImplementedError()
707 """Synchronously invokes the underlying RPC.
710 request: The request value for the RPC.
711 timeout: An optional durating of time in seconds to allow for
713 metadata: Optional :term:`metadata` to be transmitted to the
714 service-side of the RPC.
715 credentials: An optional CallCredentials for the RPC. Only valid for
717 wait_for_ready: This is an EXPERIMENTAL argument. An optional
718 flag to enable :term:`wait_for_ready` mechanism.
719 compression: An element of grpc.compression, e.g.
720 grpc.compression.Gzip. This is an EXPERIMENTAL option.
723 The response value for the RPC and a Call value for the RPC.
726 RpcError: Indicating that the RPC terminated with non-OK status. The
727 raised RpcError will also be a Call for the RPC affording the RPC's
728 metadata, status code, and details.
730 raise NotImplementedError()
740 """Asynchronously invokes the underlying RPC.
743 request: The request value for the RPC.
744 timeout: An optional duration of time in seconds to allow for
746 metadata: Optional :term:`metadata` to be transmitted to the
747 service-side of the RPC.
748 credentials: An optional CallCredentials for the RPC. Only valid for
750 wait_for_ready: This is an EXPERIMENTAL argument. An optional
751 flag to enable :term:`wait_for_ready` mechanism.
752 compression: An element of grpc.compression, e.g.
753 grpc.compression.Gzip. This is an EXPERIMENTAL option.
756 An object that is both a Call for the RPC and a Future.
757 In the event of RPC completion, the return Call-Future's result
758 value will be the response message of the RPC.
759 Should the event terminate with non-OK status,
760 the returned Call-Future's exception value will be an RpcError.
762 raise NotImplementedError()
765 class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
766 """Affords invoking a unary-stream RPC from client-side."""
776 """Invokes the underlying RPC.
779 request: The request value for the RPC.
780 timeout: An optional duration of time in seconds to allow for
781 the RPC. If None, the timeout is considered infinite.
782 metadata: An optional :term:`metadata` to be transmitted to the
783 service-side of the RPC.
784 credentials: An optional CallCredentials for the RPC. Only valid for
786 wait_for_ready: This is an EXPERIMENTAL argument. An optional
787 flag to enable :term:`wait_for_ready` mechanism.
788 compression: An element of grpc.compression, e.g.
789 grpc.compression.Gzip. This is an EXPERIMENTAL option.
792 An object that is a Call for the RPC, an iterator of response
793 values, and a Future for the RPC. Drawing response values from the
794 returned Call-iterator may raise RpcError indicating termination of
795 the RPC with non-OK status.
797 raise NotImplementedError()
800 class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
801 """Affords invoking a stream-unary RPC from client-side."""
811 """Synchronously invokes the underlying RPC.
814 request_iterator: An iterator that yields request values for
816 timeout: An optional duration of time in seconds to allow for
817 the RPC. If None, the timeout is considered infinite.
818 metadata: Optional :term:`metadata` to be transmitted to the
819 service-side of the RPC.
820 credentials: An optional CallCredentials for the RPC. Only valid for
822 wait_for_ready: This is an EXPERIMENTAL argument. An optional
823 flag to enable :term:`wait_for_ready` mechanism.
824 compression: An element of grpc.compression, e.g.
825 grpc.compression.Gzip. This is an EXPERIMENTAL option.
828 The response value for the RPC.
831 RpcError: Indicating that the RPC terminated with non-OK status. The
832 raised RpcError will also implement grpc.Call, affording methods
833 such as metadata, code, and details.
835 raise NotImplementedError()
845 """Synchronously invokes the underlying RPC on the client.
848 request_iterator: An iterator that yields request values for
850 timeout: An optional duration of time in seconds to allow for
851 the RPC. If None, the timeout is considered infinite.
852 metadata: Optional :term:`metadata` to be transmitted to the
853 service-side of the RPC.
854 credentials: An optional CallCredentials for the RPC. Only valid for
856 wait_for_ready: This is an EXPERIMENTAL argument. An optional
857 flag to enable :term:`wait_for_ready` mechanism.
858 compression: An element of grpc.compression, e.g.
859 grpc.compression.Gzip. This is an EXPERIMENTAL option.
862 The response value for the RPC and a Call object for the RPC.
865 RpcError: Indicating that the RPC terminated with non-OK status. The
866 raised RpcError will also be a Call for the RPC affording the RPC's
867 metadata, status code, and details.
869 raise NotImplementedError()
879 """Asynchronously invokes the underlying RPC on the client.
882 request_iterator: An iterator that yields request values for the RPC.
883 timeout: An optional duration of time in seconds to allow for
884 the RPC. If None, the timeout is considered infinite.
885 metadata: Optional :term:`metadata` to be transmitted to the
886 service-side of the RPC.
887 credentials: An optional CallCredentials for the RPC. Only valid for
889 wait_for_ready: This is an EXPERIMENTAL argument. An optional
890 flag to enable :term:`wait_for_ready` mechanism.
891 compression: An element of grpc.compression, e.g.
892 grpc.compression.Gzip. This is an EXPERIMENTAL option.
895 An object that is both a Call for the RPC and a Future.
896 In the event of RPC completion, the return Call-Future's result value
897 will be the response message of the RPC. Should the event terminate
898 with non-OK status, the returned Call-Future's exception value will
901 raise NotImplementedError()
904 class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
905 """Affords invoking a stream-stream RPC on client-side."""
915 """Invokes the underlying RPC on the client.
918 request_iterator: An iterator that yields request values for the RPC.
919 timeout: An optional duration of time in seconds to allow for
920 the RPC. If not specified, the timeout is considered infinite.
921 metadata: Optional :term:`metadata` to be transmitted to the
922 service-side of the RPC.
923 credentials: An optional CallCredentials for the RPC. Only valid for
925 wait_for_ready: This is an EXPERIMENTAL argument. An optional
926 flag to enable :term:`wait_for_ready` mechanism.
927 compression: An element of grpc.compression, e.g.
928 grpc.compression.Gzip. This is an EXPERIMENTAL option.
931 An object that is a Call for the RPC, an iterator of response
932 values, and a Future for the RPC. Drawing response values from the
933 returned Call-iterator may raise RpcError indicating termination of
934 the RPC with non-OK status.
936 raise NotImplementedError()
939 ############################# Channel Interface ##############################
942 class Channel(six.with_metaclass(abc.ABCMeta)):
943 """Affords RPC invocation via generic methods on client-side.
945 Channel objects implement the Context Manager type, although they need not
946 support being entered and exited multiple times.
950 def subscribe(self, callback, try_to_connect=False):
951 """Subscribe to this Channel's connectivity state machine.
953 A Channel may be in any of the states described by ChannelConnectivity.
954 This method allows application to monitor the state transitions.
955 The typical use case is to debug or gain better visibility into gRPC
959 callback: A callable to be invoked with ChannelConnectivity argument.
960 ChannelConnectivity describes current state of the channel.
961 The callable will be invoked immediately upon subscription
962 and again for every change to ChannelConnectivity until it
963 is unsubscribed or this Channel object goes out of scope.
964 try_to_connect: A boolean indicating whether or not this Channel
965 should attempt to connect immediately. If set to False, gRPC
966 runtime decides when to connect.
968 raise NotImplementedError()
971 def unsubscribe(self, callback):
972 """Unsubscribes a subscribed callback from this Channel's connectivity.
975 callback: A callable previously registered with this Channel from
976 having been passed to its "subscribe" method.
978 raise NotImplementedError()
981 def unary_unary(self,
983 request_serializer=None,
984 response_deserializer=None):
985 """Creates a UnaryUnaryMultiCallable for a unary-unary method.
988 method: The name of the RPC method.
989 request_serializer: Optional :term:`serializer` for serializing the request
990 message. Request goes unserialized in case None is passed.
991 response_deserializer: Optional :term:`deserializer` for deserializing the
992 response message. Response goes undeserialized in case None
996 A UnaryUnaryMultiCallable value for the named unary-unary method.
998 raise NotImplementedError()
1001 def unary_stream(self,
1003 request_serializer=None,
1004 response_deserializer=None):
1005 """Creates a UnaryStreamMultiCallable for a unary-stream method.
1008 method: The name of the RPC method.
1009 request_serializer: Optional :term:`serializer` for serializing the request
1010 message. Request goes unserialized in case None is passed.
1011 response_deserializer: Optional :term:`deserializer` for deserializing the
1012 response message. Response goes undeserialized in case None is
1016 A UnaryStreamMultiCallable value for the name unary-stream method.
1018 raise NotImplementedError()
1021 def stream_unary(self,
1023 request_serializer=None,
1024 response_deserializer=None):
1025 """Creates a StreamUnaryMultiCallable for a stream-unary method.
1028 method: The name of the RPC method.
1029 request_serializer: Optional :term:`serializer` for serializing the request
1030 message. Request goes unserialized in case None is passed.
1031 response_deserializer: Optional :term:`deserializer` for deserializing the
1032 response message. Response goes undeserialized in case None is
1036 A StreamUnaryMultiCallable value for the named stream-unary method.
1038 raise NotImplementedError()
1041 def stream_stream(self,
1043 request_serializer=None,
1044 response_deserializer=None):
1045 """Creates a StreamStreamMultiCallable for a stream-stream method.
1048 method: The name of the RPC method.
1049 request_serializer: Optional :term:`serializer` for serializing the request
1050 message. Request goes unserialized in case None is passed.
1051 response_deserializer: Optional :term:`deserializer` for deserializing the
1052 response message. Response goes undeserialized in case None
1056 A StreamStreamMultiCallable value for the named stream-stream method.
1058 raise NotImplementedError()
1062 """Closes this Channel and releases all resources held by it.
1064 Closing the Channel will immediately terminate all RPCs active with the
1065 Channel and it is not valid to invoke new RPCs with the Channel.
1067 This method is idempotent.
1069 raise NotImplementedError()
1071 def __enter__(self):
1072 """Enters the runtime context related to the channel object."""
1073 raise NotImplementedError()
1075 def __exit__(self, exc_type, exc_val, exc_tb):
1076 """Exits the runtime context related to the channel object."""
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()
1181 def trailing_metadata(self):
1182 """Access value to be used as trailing metadata upon RPC completion.
1184 This is an EXPERIMENTAL API.
1187 The trailing :term:`metadata` for the RPC.
1189 raise NotImplementedError()
1192 def abort(self, code, details):
1193 """Raises an exception to terminate the RPC with a non-OK status.
1195 The code and details passed as arguments will supercede any existing
1199 code: A StatusCode object to be sent to the client.
1200 It must not be StatusCode.OK.
1201 details: A UTF-8-encodable string to be sent to the client upon
1202 termination of the RPC.
1205 Exception: An exception is always raised to signal the abortion the
1206 RPC to the gRPC runtime.
1208 raise NotImplementedError()
1211 def abort_with_status(self, status):
1212 """Raises an exception to terminate the RPC with a non-OK status.
1214 The status passed as argument will supercede any existing status code,
1215 status message and trailing metadata.
1217 This is an EXPERIMENTAL API.
1220 status: A grpc.Status object. The status code in it must not be
1224 Exception: An exception is always raised to signal the abortion the
1225 RPC to the gRPC runtime.
1227 raise NotImplementedError()
1230 def set_code(self, code):
1231 """Sets the value to be used as status code upon RPC completion.
1233 This method need not be called by method implementations if they wish
1234 the gRPC runtime to determine the status code of the RPC.
1237 code: A StatusCode object to be sent to the client.
1239 raise NotImplementedError()
1242 def set_details(self, details):
1243 """Sets the value to be used as detail string upon RPC completion.
1245 This method need not be called by method implementations if they have
1246 no details to transmit.
1249 details: A UTF-8-encodable string to be sent to the client upon
1250 termination of the RPC.
1252 raise NotImplementedError()
1255 """Accesses the value to be used as status code upon RPC completion.
1257 This is an EXPERIMENTAL API.
1260 The StatusCode value for the RPC.
1262 raise NotImplementedError()
1265 """Accesses the value to be used as detail string upon RPC completion.
1267 This is an EXPERIMENTAL API.
1270 The details string of the RPC.
1272 raise NotImplementedError()
1274 def disable_next_message_compression(self):
1275 """Disables compression for the next response message.
1277 This is an EXPERIMENTAL method.
1279 This method will override any compression configuration set during
1280 server creation or set on the call.
1282 raise NotImplementedError()
1285 ##################### Service-Side Handler Interfaces ########################
1288 class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
1289 """An implementation of a single RPC method.
1292 request_streaming: Whether the RPC supports exactly one request message
1293 or any arbitrary number of request messages.
1294 response_streaming: Whether the RPC supports exactly one response message
1295 or any arbitrary number of response messages.
1296 request_deserializer: A callable :term:`deserializer` that accepts a byte string and
1297 returns an object suitable to be passed to this object's business
1298 logic, or None to indicate that this object's business logic should be
1299 passed the raw request bytes.
1300 response_serializer: A callable :term:`serializer` that accepts an object produced
1301 by this object's business logic and returns a byte string, or None to
1302 indicate that the byte strings produced by this object's business logic
1303 should be transmitted on the wire as they are.
1304 unary_unary: This object's application-specific business logic as a
1305 callable value that takes a request value and a ServicerContext object
1306 and returns a response value. Only non-None if both request_streaming
1307 and response_streaming are False.
1308 unary_stream: This object's application-specific business logic as a
1309 callable value that takes a request value and a ServicerContext object
1310 and returns an iterator of response values. Only non-None if
1311 request_streaming is False and response_streaming is True.
1312 stream_unary: This object's application-specific business logic as a
1313 callable value that takes an iterator of request values and a
1314 ServicerContext object and returns a response value. Only non-None if
1315 request_streaming is True and response_streaming is False.
1316 stream_stream: This object's application-specific business logic as a
1317 callable value that takes an iterator of request values and a
1318 ServicerContext object and returns an iterator of response values.
1319 Only non-None if request_streaming and response_streaming are both
1324 class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
1325 """Describes an RPC that has just arrived for service.
1328 method: The method name of the RPC.
1329 invocation_metadata: The :term:`metadata` sent by the client.
1333 class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
1334 """An implementation of arbitrarily many RPC methods."""
1337 def service(self, handler_call_details):
1338 """Returns the handler for servicing the RPC.
1341 handler_call_details: A HandlerCallDetails describing the RPC.
1344 An RpcMethodHandler with which the RPC may be serviced if the
1345 implementation chooses to service this RPC, or None otherwise.
1347 raise NotImplementedError()
1350 class ServiceRpcHandler(six.with_metaclass(abc.ABCMeta, GenericRpcHandler)):
1351 """An implementation of RPC methods belonging to a service.
1353 A service handles RPC methods with structured names of the form
1354 '/Service.Name/Service.Method', where 'Service.Name' is the value
1355 returned by service_name(), and 'Service.Method' is the method
1356 name. A service can have multiple method names, but only a single
1361 def service_name(self):
1362 """Returns this service's name.
1367 raise NotImplementedError()
1370 #################### Service-Side Interceptor Interfaces #####################
1373 class ServerInterceptor(six.with_metaclass(abc.ABCMeta)):
1374 """Affords intercepting incoming RPCs on the service-side."""
1377 def intercept_service(self, continuation, handler_call_details):
1378 """Intercepts incoming RPCs before handing them over to a handler.
1381 continuation: A function that takes a HandlerCallDetails and
1382 proceeds to invoke the next interceptor in the chain, if any,
1383 or the RPC handler lookup logic, with the call details passed
1384 as an argument, and returns an RpcMethodHandler instance if
1385 the RPC is considered serviced, or None otherwise.
1386 handler_call_details: A HandlerCallDetails describing the RPC.
1389 An RpcMethodHandler with which the RPC may be serviced if the
1390 interceptor chooses to service this RPC, or None otherwise.
1392 raise NotImplementedError()
1395 ############################# Server Interface ###############################
1398 class Server(six.with_metaclass(abc.ABCMeta)):
1399 """Services RPCs."""
1402 def add_generic_rpc_handlers(self, generic_rpc_handlers):
1403 """Registers GenericRpcHandlers with this Server.
1405 This method is only safe to call before the server is started.
1408 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1409 used to service RPCs.
1411 raise NotImplementedError()
1414 def add_insecure_port(self, address):
1415 """Opens an insecure port for accepting RPCs.
1417 This method may only be called before starting the server.
1420 address: The address for which to open a port. If the port is 0,
1421 or not specified in the address, then gRPC runtime will choose a port.
1424 An integer port on which server will accept RPC requests.
1426 raise NotImplementedError()
1429 def add_secure_port(self, address, server_credentials):
1430 """Opens a secure port for accepting RPCs.
1432 This method may only be called before starting the server.
1435 address: The address for which to open a port.
1436 if the port is 0, or not specified in the address, then gRPC
1437 runtime will choose a port.
1438 server_credentials: A ServerCredentials object.
1441 An integer port on which server will accept RPC requests.
1443 raise NotImplementedError()
1447 """Starts this Server.
1449 This method may only be called once. (i.e. it is not idempotent).
1451 raise NotImplementedError()
1454 def stop(self, grace):
1455 """Stops this Server.
1457 This method immediately stop service of new RPCs in all cases.
1459 If a grace period is specified, this method returns immediately
1460 and all RPCs active at the end of the grace period are aborted.
1461 If a grace period is not specified (by passing None for `grace`),
1462 all existing RPCs are aborted immediately and this method
1463 blocks until the last RPC handler terminates.
1465 This method is idempotent and may be called at any time.
1466 Passing a smaller grace value in a subsequent call will have
1467 the effect of stopping the Server sooner (passing None will
1468 have the effect of stopping the server immediately). Passing
1469 a larger grace value in a subsequent call *will not* have the
1470 effect of stopping the server later (i.e. the most restrictive
1471 grace value is used).
1474 grace: A duration of time in seconds or None.
1477 A threading.Event that will be set when this Server has completely
1478 stopped, i.e. when running RPCs either complete or are aborted and
1479 all handlers have terminated.
1481 raise NotImplementedError()
1483 def wait_for_termination(self, timeout=None):
1484 """Block current thread until the server stops.
1486 This is an EXPERIMENTAL API.
1488 The wait will not consume computational resources during blocking, and
1489 it will block until one of the two following conditions are met:
1491 1) The server is stopped or terminated;
1492 2) A timeout occurs if timeout is not `None`.
1494 The timeout argument works in the same way as `threading.Event.wait()`.
1495 https://docs.python.org/3/library/threading.html#threading.Event.wait
1498 timeout: A floating point number specifying a timeout for the
1499 operation in seconds.
1502 A bool indicates if the operation times out.
1504 raise NotImplementedError()
1507 ################################# Functions ################################
1510 def unary_unary_rpc_method_handler(behavior,
1511 request_deserializer=None,
1512 response_serializer=None):
1513 """Creates an RpcMethodHandler for a unary-unary RPC method.
1516 behavior: The implementation of an RPC that accepts one request
1517 and returns one response.
1518 request_deserializer: An optional :term:`deserializer` for request deserialization.
1519 response_serializer: An optional :term:`serializer` for response serialization.
1522 An RpcMethodHandler object that is typically used by grpc.Server.
1524 from grpc import _utilities # pylint: disable=cyclic-import
1525 return _utilities.RpcMethodHandler(False, False, request_deserializer,
1526 response_serializer, behavior, None,
1530 def unary_stream_rpc_method_handler(behavior,
1531 request_deserializer=None,
1532 response_serializer=None):
1533 """Creates an RpcMethodHandler for a unary-stream RPC method.
1536 behavior: The implementation of an RPC that accepts one request
1537 and returns an iterator of response values.
1538 request_deserializer: An optional :term:`deserializer` for request deserialization.
1539 response_serializer: An optional :term:`serializer` for response serialization.
1542 An RpcMethodHandler object that is typically used by grpc.Server.
1544 from grpc import _utilities # pylint: disable=cyclic-import
1545 return _utilities.RpcMethodHandler(False, True, request_deserializer,
1546 response_serializer, None, behavior,
1550 def stream_unary_rpc_method_handler(behavior,
1551 request_deserializer=None,
1552 response_serializer=None):
1553 """Creates an RpcMethodHandler for a stream-unary RPC method.
1556 behavior: The implementation of an RPC that accepts an iterator of
1557 request values and returns a single response value.
1558 request_deserializer: An optional :term:`deserializer` for request deserialization.
1559 response_serializer: An optional :term:`serializer` for response serialization.
1562 An RpcMethodHandler object that is typically used by grpc.Server.
1564 from grpc import _utilities # pylint: disable=cyclic-import
1565 return _utilities.RpcMethodHandler(True, False, request_deserializer,
1566 response_serializer, None, None,
1570 def stream_stream_rpc_method_handler(behavior,
1571 request_deserializer=None,
1572 response_serializer=None):
1573 """Creates an RpcMethodHandler for a stream-stream RPC method.
1576 behavior: The implementation of an RPC that accepts an iterator of
1577 request values and returns an iterator of response values.
1578 request_deserializer: An optional :term:`deserializer` for request deserialization.
1579 response_serializer: An optional :term:`serializer` for response serialization.
1582 An RpcMethodHandler object that is typically used by grpc.Server.
1584 from grpc import _utilities # pylint: disable=cyclic-import
1585 return _utilities.RpcMethodHandler(True, True, request_deserializer,
1586 response_serializer, None, None, None,
1590 def method_handlers_generic_handler(service, method_handlers):
1591 """Creates a GenericRpcHandler from RpcMethodHandlers.
1594 service: The name of the service that is implemented by the
1596 method_handlers: A dictionary that maps method names to corresponding
1600 A GenericRpcHandler. This is typically added to the grpc.Server object
1601 with add_generic_rpc_handlers() before starting the server.
1603 from grpc import _utilities # pylint: disable=cyclic-import
1604 return _utilities.DictionaryGenericHandler(service, method_handlers)
1607 def ssl_channel_credentials(root_certificates=None,
1609 certificate_chain=None):
1610 """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1613 root_certificates: The PEM-encoded root certificates as a byte string,
1614 or None to retrieve them from a default location chosen by gRPC
1616 private_key: The PEM-encoded private key as a byte string, or None if no
1617 private key should be used.
1618 certificate_chain: The PEM-encoded certificate chain as a byte string
1619 to use or None if no certificate chain should be used.
1622 A ChannelCredentials for use with an SSL-enabled Channel.
1624 return ChannelCredentials(
1625 _cygrpc.SSLChannelCredentials(root_certificates, private_key,
1629 def xds_channel_credentials(fallback_credentials=None):
1630 """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL
1634 fallback_credentials: Credentials to use in case it is not possible to
1635 establish a secure connection via xDS. If no fallback_credentials
1636 argument is supplied, a default SSLChannelCredentials is used.
1638 fallback_credentials = ssl_channel_credentials(
1639 ) if fallback_credentials is None else fallback_credentials
1640 return ChannelCredentials(
1641 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials))
1644 def metadata_call_credentials(metadata_plugin, name=None):
1645 """Construct CallCredentials from an AuthMetadataPlugin.
1648 metadata_plugin: An AuthMetadataPlugin to use for authentication.
1649 name: An optional name for the plugin.
1654 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1655 return _plugin_wrapping.metadata_plugin_call_credentials(
1656 metadata_plugin, name)
1659 def access_token_call_credentials(access_token):
1660 """Construct CallCredentials from an access token.
1663 access_token: A string to place directly in the http request
1664 authorization header, for example
1665 "authorization: Bearer <access_token>".
1670 from grpc import _auth # pylint: disable=cyclic-import
1671 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1672 return _plugin_wrapping.metadata_plugin_call_credentials(
1673 _auth.AccessTokenAuthMetadataPlugin(access_token), None)
1676 def composite_call_credentials(*call_credentials):
1677 """Compose multiple CallCredentials to make a new CallCredentials.
1680 *call_credentials: At least two CallCredentials objects.
1683 A CallCredentials object composed of the given CallCredentials objects.
1685 return CallCredentials(
1686 _cygrpc.CompositeCallCredentials(
1687 tuple(single_call_credentials._credentials
1688 for single_call_credentials in call_credentials)))
1691 def composite_channel_credentials(channel_credentials, *call_credentials):
1692 """Compose a ChannelCredentials and one or more CallCredentials objects.
1695 channel_credentials: A ChannelCredentials object.
1696 *call_credentials: One or more CallCredentials objects.
1699 A ChannelCredentials composed of the given ChannelCredentials and
1700 CallCredentials objects.
1702 return ChannelCredentials(
1703 _cygrpc.CompositeChannelCredentials(
1704 tuple(single_call_credentials._credentials
1705 for single_call_credentials in call_credentials),
1706 channel_credentials._credentials))
1709 def ssl_server_credentials(private_key_certificate_chain_pairs,
1710 root_certificates=None,
1711 require_client_auth=False):
1712 """Creates a ServerCredentials for use with an SSL-enabled Server.
1715 private_key_certificate_chain_pairs: A list of pairs of the form
1716 [PEM-encoded private key, PEM-encoded certificate chain].
1717 root_certificates: An optional byte string of PEM-encoded client root
1718 certificates that the server will use to verify client authentication.
1719 If omitted, require_client_auth must also be False.
1720 require_client_auth: A boolean indicating whether or not to require
1721 clients to be authenticated. May only be True if root_certificates
1725 A ServerCredentials for use with an SSL-enabled Server. Typically, this
1726 object is an argument to add_secure_port() method during server setup.
1728 if not private_key_certificate_chain_pairs:
1730 'At least one private key-certificate chain pair is required!')
1731 elif require_client_auth and root_certificates is None:
1733 'Illegal to require client auth without providing root certificates!'
1736 return ServerCredentials(
1737 _cygrpc.server_credentials_ssl(root_certificates, [
1738 _cygrpc.SslPemKeyCertPair(key, pem)
1739 for key, pem in private_key_certificate_chain_pairs
1740 ], require_client_auth))
1743 def xds_server_credentials(fallback_credentials):
1744 """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL
1748 fallback_credentials: Credentials to use in case it is not possible to
1749 establish a secure connection via xDS. No default value is provided.
1751 return ServerCredentials(
1752 _cygrpc.xds_server_credentials(fallback_credentials._credentials))
1755 def insecure_server_credentials():
1756 """Creates a credentials object directing the server to use no credentials.
1757 This is an EXPERIMENTAL API.
1759 This object cannot be used directly in a call to `add_secure_port`.
1760 Instead, it should be used to construct other credentials objects, e.g.
1761 with xds_server_credentials.
1763 return ServerCredentials(_cygrpc.insecure_server_credentials())
1766 def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
1767 root_certificates=None):
1768 """Creates a ServerCertificateConfiguration for use with a Server.
1771 private_key_certificate_chain_pairs: A collection of pairs of
1772 the form [PEM-encoded private key, PEM-encoded certificate
1774 root_certificates: An optional byte string of PEM-encoded client root
1775 certificates that the server will use to verify client authentication.
1778 A ServerCertificateConfiguration that can be returned in the certificate
1779 configuration fetching callback.
1781 if private_key_certificate_chain_pairs:
1782 return ServerCertificateConfiguration(
1783 _cygrpc.server_certificate_config_ssl(root_certificates, [
1784 _cygrpc.SslPemKeyCertPair(key, pem)
1785 for key, pem in private_key_certificate_chain_pairs
1789 'At least one private key-certificate chain pair is required!')
1792 def dynamic_ssl_server_credentials(initial_certificate_configuration,
1793 certificate_configuration_fetcher,
1794 require_client_authentication=False):
1795 """Creates a ServerCredentials for use with an SSL-enabled Server.
1798 initial_certificate_configuration (ServerCertificateConfiguration): The
1799 certificate configuration with which the server will be initialized.
1800 certificate_configuration_fetcher (callable): A callable that takes no
1801 arguments and should return a ServerCertificateConfiguration to
1802 replace the server's current certificate, or None for no change
1803 (i.e., the server will continue its current certificate
1804 config). The library will call this callback on *every* new
1805 client connection before starting the TLS handshake with the
1806 client, thus allowing the user application to optionally
1807 return a new ServerCertificateConfiguration that the server will then
1808 use for the handshake.
1809 require_client_authentication: A boolean indicating whether or not to
1810 require clients to be authenticated.
1813 A ServerCredentials.
1815 return ServerCredentials(
1816 _cygrpc.server_credentials_ssl_dynamic_cert_config(
1817 initial_certificate_configuration,
1818 certificate_configuration_fetcher, require_client_authentication))
1822 class LocalConnectionType(enum.Enum):
1823 """Types of local connection for local credential creation.
1826 UDS: Unix domain socket connections
1827 LOCAL_TCP: Local TCP connections.
1829 UDS = _cygrpc.LocalConnectionType.uds
1830 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
1833 def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1834 """Creates a local ChannelCredentials used for local connections.
1836 This is an EXPERIMENTAL API.
1838 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1839 also UDS connections.
1841 The connections created by local channel credentials are not
1842 encrypted, but will be checked if they are local or not.
1843 The UDS connections are considered secure by providing peer authentication
1844 and data confidentiality while TCP connections are considered insecure.
1846 It is allowed to transmit call credentials over connections created by
1847 local channel credentials.
1849 Local channel credentials are useful for 1) eliminating insecure_channel usage;
1850 2) enable unit testing for call credentials without setting up secrets.
1853 local_connect_type: Local connection type (either
1854 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1857 A ChannelCredentials for use with a local Channel
1859 return ChannelCredentials(
1860 _cygrpc.channel_credentials_local(local_connect_type.value))
1863 def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1864 """Creates a local ServerCredentials used for local connections.
1866 This is an EXPERIMENTAL API.
1868 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1869 also UDS connections.
1871 The connections created by local server credentials are not
1872 encrypted, but will be checked if they are local or not.
1873 The UDS connections are considered secure by providing peer authentication
1874 and data confidentiality while TCP connections are considered insecure.
1876 It is allowed to transmit call credentials over connections created by local
1879 Local server credentials are useful for 1) eliminating insecure_channel usage;
1880 2) enable unit testing for call credentials without setting up secrets.
1883 local_connect_type: Local connection type (either
1884 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1887 A ServerCredentials for use with a local Server
1889 return ServerCredentials(
1890 _cygrpc.server_credentials_local(local_connect_type.value))
1893 def alts_channel_credentials(service_accounts=None):
1894 """Creates a ChannelCredentials for use with an ALTS-enabled Channel.
1896 This is an EXPERIMENTAL API.
1897 ALTS credentials API can only be used in GCP environment as it relies on
1898 handshaker service being available. For more info about ALTS see
1899 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1902 service_accounts: A list of server identities accepted by the client.
1903 If target service accounts are provided and none of them matches the
1904 peer identity of the server, handshake will fail. The arg can be empty
1905 if the client does not have any information about trusted server
1908 A ChannelCredentials for use with an ALTS-enabled Channel
1910 return ChannelCredentials(
1911 _cygrpc.channel_credentials_alts(service_accounts or []))
1914 def alts_server_credentials():
1915 """Creates a ServerCredentials for use with an ALTS-enabled connection.
1917 This is an EXPERIMENTAL API.
1918 ALTS credentials API can only be used in GCP environment as it relies on
1919 handshaker service being available. For more info about ALTS see
1920 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1923 A ServerCredentials for use with an ALTS-enabled Server
1925 return ServerCredentials(_cygrpc.server_credentials_alts())
1928 def compute_engine_channel_credentials(call_credentials):
1929 """Creates a compute engine channel credential.
1931 This credential can only be used in a GCP environment as it relies on
1932 a handshaker service. For more info about ALTS, see
1933 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1935 This channel credential is expected to be used as part of a composite
1936 credential in conjunction with a call credentials that authenticates the
1937 VM's default service account. If used with any other sort of call
1938 credential, the connection may suddenly and unexpectedly begin failing RPCs.
1940 return ChannelCredentials(
1941 _cygrpc.channel_credentials_compute_engine(
1942 call_credentials._credentials))
1945 def channel_ready_future(channel):
1946 """Creates a Future that tracks when a Channel is ready.
1948 Cancelling the Future does not affect the channel's state machine.
1949 It merely decouples the Future from channel state machine.
1952 channel: A Channel object.
1955 A Future object that matures when the channel connectivity is
1956 ChannelConnectivity.READY.
1958 from grpc import _utilities # pylint: disable=cyclic-import
1959 return _utilities.channel_ready_future(channel)
1962 def insecure_channel(target, options=None, compression=None):
1963 """Creates an insecure Channel to a server.
1965 The returned Channel is thread-safe.
1968 target: The server address
1969 options: An optional list of key-value pairs (:term:`channel_arguments`
1970 in gRPC Core runtime) to configure the channel.
1971 compression: An optional value indicating the compression method to be
1972 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1977 from grpc import _channel # pylint: disable=cyclic-import
1978 return _channel.Channel(target, () if options is None else options, None,
1982 def secure_channel(target, credentials, options=None, compression=None):
1983 """Creates a secure Channel to a server.
1985 The returned Channel is thread-safe.
1988 target: The server address.
1989 credentials: A ChannelCredentials instance.
1990 options: An optional list of key-value pairs (:term:`channel_arguments`
1991 in gRPC Core runtime) to configure the channel.
1992 compression: An optional value indicating the compression method to be
1993 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1998 from grpc import _channel # pylint: disable=cyclic-import
1999 from grpc.experimental import _insecure_channel_credentials
2000 if credentials._credentials is _insecure_channel_credentials:
2002 "secure_channel cannot be called with insecure credentials." +
2003 " Call insecure_channel instead.")
2004 return _channel.Channel(target, () if options is None else options,
2005 credentials._credentials, compression)
2008 def intercept_channel(channel, *interceptors):
2009 """Intercepts a channel through a set of interceptors.
2013 interceptors: Zero or more objects of type
2014 UnaryUnaryClientInterceptor,
2015 UnaryStreamClientInterceptor,
2016 StreamUnaryClientInterceptor, or
2017 StreamStreamClientInterceptor.
2018 Interceptors are given control in the order they are listed.
2021 A Channel that intercepts each invocation via the provided interceptors.
2024 TypeError: If interceptor does not derive from any of
2025 UnaryUnaryClientInterceptor,
2026 UnaryStreamClientInterceptor,
2027 StreamUnaryClientInterceptor, or
2028 StreamStreamClientInterceptor.
2030 from grpc import _interceptor # pylint: disable=cyclic-import
2031 return _interceptor.intercept_channel(channel, *interceptors)
2034 def server(thread_pool,
2038 maximum_concurrent_rpcs=None,
2041 """Creates a Server with which RPCs can be serviced.
2044 thread_pool: A futures.ThreadPoolExecutor to be used by the Server
2045 to execute RPC handlers.
2046 handlers: An optional list of GenericRpcHandlers used for executing RPCs.
2047 More handlers may be added by calling add_generic_rpc_handlers any time
2048 before the server is started.
2049 interceptors: An optional list of ServerInterceptor objects that observe
2050 and optionally manipulate the incoming RPCs before handing them over to
2051 handlers. The interceptors are given control in the order they are
2052 specified. This is an EXPERIMENTAL API.
2053 options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
2054 to configure the channel.
2055 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
2056 will service before returning RESOURCE_EXHAUSTED status, or None to
2058 compression: An element of grpc.compression, e.g.
2059 grpc.compression.Gzip. This compression algorithm will be used for the
2060 lifetime of the server unless overridden. This is an EXPERIMENTAL option.
2061 xds: If set to true, retrieves server configuration via xDS. This is an
2062 EXPERIMENTAL option.
2067 from grpc import _server # pylint: disable=cyclic-import
2068 return _server.create_server(thread_pool,
2069 () if handlers is None else handlers,
2070 () if interceptors is None else interceptors,
2071 () if options is None else options,
2072 maximum_concurrent_rpcs, compression, xds)
2075 @contextlib.contextmanager
2076 def _create_servicer_context(rpc_event, state, request_deserializer):
2077 from grpc import _server # pylint: disable=cyclic-import
2078 context = _server._Context(rpc_event, state, request_deserializer)
2080 context._finalize_state() # pylint: disable=protected-access
2084 class Compression(enum.IntEnum):
2085 """Indicates the compression method to be used for an RPC.
2087 This enumeration is part of an EXPERIMENTAL API.
2090 NoCompression: Do not use compression algorithm.
2091 Deflate: Use "Deflate" compression algorithm.
2092 Gzip: Use "Gzip" compression algorithm.
2094 NoCompression = _compression.NoCompression
2095 Deflate = _compression.Deflate
2096 Gzip = _compression.Gzip
2099 ################################### __all__ #################################
2102 'FutureTimeoutError',
2103 'FutureCancelledError',
2105 'ChannelConnectivity',
2111 'ChannelCredentials',
2113 'AuthMetadataContext',
2114 'AuthMetadataPluginCallback',
2115 'AuthMetadataPlugin',
2117 'ClientCallDetails',
2118 'ServerCertificateConfiguration',
2119 'ServerCredentials',
2120 'LocalConnectionType',
2121 'UnaryUnaryMultiCallable',
2122 'UnaryStreamMultiCallable',
2123 'StreamUnaryMultiCallable',
2124 'StreamStreamMultiCallable',
2125 'UnaryUnaryClientInterceptor',
2126 'UnaryStreamClientInterceptor',
2127 'StreamUnaryClientInterceptor',
2128 'StreamStreamClientInterceptor',
2132 'HandlerCallDetails',
2133 'GenericRpcHandler',
2134 'ServiceRpcHandler',
2136 'ServerInterceptor',
2137 'unary_unary_rpc_method_handler',
2138 'unary_stream_rpc_method_handler',
2139 'stream_unary_rpc_method_handler',
2140 'stream_stream_rpc_method_handler',
2141 'method_handlers_generic_handler',
2142 'ssl_channel_credentials',
2143 'metadata_call_credentials',
2144 'access_token_call_credentials',
2145 'composite_call_credentials',
2146 'composite_channel_credentials',
2147 'local_channel_credentials',
2148 'local_server_credentials',
2149 'alts_channel_credentials',
2150 'alts_server_credentials',
2151 'ssl_server_credentials',
2152 'ssl_server_certificate_configuration',
2153 'dynamic_ssl_server_credentials',
2154 'channel_ready_future',
2157 'intercept_channel',
2161 'protos_and_services',
2162 'xds_channel_credentials',
2163 'xds_server_credentials',
2164 'insecure_server_credentials',
2167 ############################### Extension Shims ################################
2169 # Here to maintain backwards compatibility; avoid using these in new code!
2172 sys.modules.update({'grpc.tools': grpc_tools})
2177 sys.modules.update({'grpc.health': grpc_health})
2181 import grpc_reflection
2182 sys.modules.update({'grpc.reflection': grpc_reflection})
2186 # Prevents import order issue in the case of renamed path.
2187 if sys.version_info >= (3, 6) and __name__ == "grpc":
2188 from grpc import aio # pylint: disable=ungrouped-imports
2189 sys.modules.update({'grpc.aio': aio})