Imported Upstream version 1.38.0
[platform/upstream/grpc.git] / src / python / grpcio / grpc / __init__.py
1 # Copyright 2015-2016 gRPC authors.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """gRPC's Python API."""
15
16 import abc
17 import contextlib
18 import enum
19 import logging
20 import sys
21 import six
22
23 from grpc._cython import cygrpc as _cygrpc
24 from grpc import _compression
25
26 logging.getLogger(__name__).addHandler(logging.NullHandler())
27
28 try:
29     from grpc._grpcio_metadata import __version__
30 except ImportError:
31     __version__ = "dev0"
32
33 ############################## Future Interface  ###############################
34
35
36 class FutureTimeoutError(Exception):
37     """Indicates that a method call on a Future timed out."""
38
39
40 class FutureCancelledError(Exception):
41     """Indicates that the computation underlying a Future was cancelled."""
42
43
44 class Future(six.with_metaclass(abc.ABCMeta)):
45     """A representation of a computation in another control flow.
46
47     Computations represented by a Future may be yet to be begun,
48     may be ongoing, or may have already completed.
49     """
50
51     @abc.abstractmethod
52     def cancel(self):
53         """Attempts to cancel the computation.
54
55         This method does not block.
56
57         Returns:
58             bool:
59             Returns True if the computation was canceled.
60
61             Returns False under all other circumstances, for example:
62
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.
67         """
68         raise NotImplementedError()
69
70     @abc.abstractmethod
71     def cancelled(self):
72         """Describes whether the computation was cancelled.
73
74         This method does not block.
75
76         Returns:
77             bool:
78             Returns True if the computation was cancelled before its result became
79             available.
80
81             Returns False under all other circumstances, for example:
82
83             1. computation was not cancelled.
84             2. computation's result is available.
85         """
86         raise NotImplementedError()
87
88     @abc.abstractmethod
89     def running(self):
90         """Describes whether the computation is taking place.
91
92         This method does not block.
93
94         Returns:
95             Returns True if the computation is scheduled for execution or
96             currently executing.
97
98             Returns False if the computation already executed or was cancelled.
99         """
100         raise NotImplementedError()
101
102     @abc.abstractmethod
103     def done(self):
104         """Describes whether the computation has taken place.
105
106         This method does not block.
107
108         Returns:
109             bool:
110             Returns True if the computation already executed or was cancelled.
111             Returns False if the computation is scheduled for execution or
112             currently executing.
113             This is exactly opposite of the running() method's result.
114         """
115         raise NotImplementedError()
116
117     @abc.abstractmethod
118     def result(self, timeout=None):
119         """Returns the result of the computation or raises its exception.
120
121         This method may return immediately or may block.
122
123         Args:
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.
127
128         Returns:
129           The return value of the computation.
130
131         Raises:
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.
137         """
138         raise NotImplementedError()
139
140     @abc.abstractmethod
141     def exception(self, timeout=None):
142         """Return the exception raised by the computation.
143
144         This method may return immediately or may block.
145
146         Args:
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.
150
151         Returns:
152             The exception raised by the computation, or None if the computation
153             did not raise an exception.
154
155         Raises:
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.
159         """
160         raise NotImplementedError()
161
162     @abc.abstractmethod
163     def traceback(self, timeout=None):
164         """Access the traceback of the exception raised by the computation.
165
166         This method may return immediately or may block.
167
168         Args:
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.
172
173         Returns:
174             The traceback of the exception raised by the computation, or None
175             if the computation did not raise an exception.
176
177         Raises:
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.
181         """
182         raise NotImplementedError()
183
184     @abc.abstractmethod
185     def add_done_callback(self, fn):
186         """Adds a function to be called at completion of the computation.
187
188         The callback will be passed this Future object describing the outcome
189         of the computation.  Callbacks will be invoked after the future is
190         terminated, whether successfully or not.
191
192         If the computation has already completed, the callback will be called
193         immediately.
194
195         Exceptions raised in the callback will be logged at ERROR level, but
196         will not terminate any threads of execution.
197
198         Args:
199           fn: A callable taking this Future object as its single parameter.
200         """
201         raise NotImplementedError()
202
203
204 ################################  gRPC Enums  ##################################
205
206
207 @enum.unique
208 class ChannelConnectivity(enum.Enum):
209     """Mirrors grpc_connectivity_state in the gRPC Core.
210
211     Attributes:
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
216         to recover.
217       SHUTDOWN: The channel has seen a failure from which it cannot recover.
218     """
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,
223                          'transient failure')
224     SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, 'shutdown')
225
226
227 @enum.unique
228 class StatusCode(enum.Enum):
229     """Mirrors grpc_status_code in the gRPC Core.
230
231     Attributes:
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)
239         already exists.
240       PERMISSION_DENIED: The caller does not have permission to execute the specified
241         operation.
242       UNAUTHENTICATED: The request does not have valid authentication credentials for the
243         operation.
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.
255     """
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,
261                          '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,
265                          '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')
277
278
279 #############################  gRPC Status  ################################
280
281
282 class Status(six.with_metaclass(abc.ABCMeta)):
283     """Describes the status of an RPC.
284
285     This is an EXPERIMENTAL API.
286
287     Attributes:
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.
292     """
293
294
295 #############################  gRPC Exceptions  ################################
296
297
298 class RpcError(Exception):
299     """Raised by the gRPC library to indicate non-OK-status RPC termination."""
300
301
302 ##############################  Shared Context  ################################
303
304
305 class RpcContext(six.with_metaclass(abc.ABCMeta)):
306     """Provides RPC-related information and action."""
307
308     @abc.abstractmethod
309     def is_active(self):
310         """Describes whether the RPC is active or has terminated.
311
312         Returns:
313           bool:
314           True if RPC is active, False otherwise.
315         """
316         raise NotImplementedError()
317
318     @abc.abstractmethod
319     def time_remaining(self):
320         """Describes the length of allowed time remaining for the RPC.
321
322         Returns:
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.
326         """
327         raise NotImplementedError()
328
329     @abc.abstractmethod
330     def cancel(self):
331         """Cancels the RPC.
332
333         Idempotent and has no effect if the RPC has already terminated.
334         """
335         raise NotImplementedError()
336
337     @abc.abstractmethod
338     def add_callback(self, callback):
339         """Registers a callback to be called on RPC termination.
340
341         Args:
342           callback: A no-parameter callable to be called on RPC termination.
343
344         Returns:
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).
348         """
349         raise NotImplementedError()
350
351
352 #########################  Invocation-Side Context  ############################
353
354
355 class Call(six.with_metaclass(abc.ABCMeta, RpcContext)):
356     """Invocation-side utility object for an RPC."""
357
358     @abc.abstractmethod
359     def initial_metadata(self):
360         """Accesses the initial metadata sent by the server.
361
362         This method blocks until the value is available.
363
364         Returns:
365           The initial :term:`metadata`.
366         """
367         raise NotImplementedError()
368
369     @abc.abstractmethod
370     def trailing_metadata(self):
371         """Accesses the trailing metadata sent by the server.
372
373         This method blocks until the value is available.
374
375         Returns:
376           The trailing :term:`metadata`.
377         """
378         raise NotImplementedError()
379
380     @abc.abstractmethod
381     def code(self):
382         """Accesses the status code sent by the server.
383
384         This method blocks until the value is available.
385
386         Returns:
387           The StatusCode value for the RPC.
388         """
389         raise NotImplementedError()
390
391     @abc.abstractmethod
392     def details(self):
393         """Accesses the details sent by the server.
394
395         This method blocks until the value is available.
396
397         Returns:
398           The details string of the RPC.
399         """
400         raise NotImplementedError()
401
402
403 ##############  Invocation-Side Interceptor Interfaces & Classes  ##############
404
405
406 class ClientCallDetails(six.with_metaclass(abc.ABCMeta)):
407     """Describes an RPC to be invoked.
408
409     Attributes:
410       method: The method name of the RPC.
411       timeout: An optional duration of time in seconds to allow for the RPC.
412       metadata: Optional :term:`metadata` to be transmitted to
413         the service-side of the RPC.
414       credentials: An optional CallCredentials for the RPC.
415       wait_for_ready: This is an EXPERIMENTAL argument. An optional
416             flag to enable :term:`wait_for_ready` mechanism.
417       compression: An element of grpc.compression, e.g.
418         grpc.compression.Gzip. This is an EXPERIMENTAL option.
419     """
420
421
422 class UnaryUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
423     """Affords intercepting unary-unary invocations."""
424
425     @abc.abstractmethod
426     def intercept_unary_unary(self, continuation, client_call_details, request):
427         """Intercepts a unary-unary invocation asynchronously.
428
429         Args:
430           continuation: A function that proceeds with the invocation by
431             executing the next interceptor in chain or invoking the
432             actual RPC on the underlying Channel. It is the interceptor's
433             responsibility to call it if it decides to move the RPC forward.
434             The interceptor can use
435             `response_future = continuation(client_call_details, request)`
436             to continue with the RPC. `continuation` returns an object that is
437             both a Call for the RPC and a Future. In the event of RPC
438             completion, the return Call-Future's result value will be
439             the response message of the RPC. Should the event terminate
440             with non-OK status, the returned Call-Future's exception value
441             will be an RpcError.
442           client_call_details: A ClientCallDetails object describing the
443             outgoing RPC.
444           request: The request value for the RPC.
445
446         Returns:
447             An object that is both a Call for the RPC and a Future.
448             In the event of RPC completion, the return Call-Future's
449             result value will be the response message of the RPC.
450             Should the event terminate with non-OK status, the returned
451             Call-Future's exception value will be an RpcError.
452         """
453         raise NotImplementedError()
454
455
456 class UnaryStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
457     """Affords intercepting unary-stream invocations."""
458
459     @abc.abstractmethod
460     def intercept_unary_stream(self, continuation, client_call_details,
461                                request):
462         """Intercepts a unary-stream invocation.
463
464         Args:
465           continuation: A function that proceeds with the invocation by
466             executing the next interceptor in chain or invoking the
467             actual RPC on the underlying Channel. It is the interceptor's
468             responsibility to call it if it decides to move the RPC forward.
469             The interceptor can use
470             `response_iterator = continuation(client_call_details, request)`
471             to continue with the RPC. `continuation` returns an object that is
472             both a Call for the RPC and an iterator for response values.
473             Drawing response values from the returned Call-iterator may
474             raise RpcError indicating termination of the RPC with non-OK
475             status.
476           client_call_details: A ClientCallDetails object describing the
477             outgoing RPC.
478           request: The request value for the RPC.
479
480         Returns:
481             An object that is both a Call for the RPC and an iterator of
482             response values. Drawing response values from the returned
483             Call-iterator may raise RpcError indicating termination of
484             the RPC with non-OK status. This object *should* also fulfill the
485             Future interface, though it may not.
486         """
487         raise NotImplementedError()
488
489
490 class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
491     """Affords intercepting stream-unary invocations."""
492
493     @abc.abstractmethod
494     def intercept_stream_unary(self, continuation, client_call_details,
495                                request_iterator):
496         """Intercepts a stream-unary invocation asynchronously.
497
498         Args:
499           continuation: A function that proceeds with the invocation by
500             executing the next interceptor in chain or invoking the
501             actual RPC on the underlying Channel. It is the interceptor's
502             responsibility to call it if it decides to move the RPC forward.
503             The interceptor can use
504             `response_future = continuation(client_call_details, request_iterator)`
505             to continue with the RPC. `continuation` returns an object that is
506             both a Call for the RPC and a Future. In the event of RPC completion,
507             the return Call-Future's result value will be the response message
508             of the RPC. Should the event terminate with non-OK status, the
509             returned Call-Future's exception value will be an RpcError.
510           client_call_details: A ClientCallDetails object describing the
511             outgoing RPC.
512           request_iterator: An iterator that yields request values for the RPC.
513
514         Returns:
515           An object that is both a Call for the RPC and a Future.
516           In the event of RPC completion, the return Call-Future's
517           result value will be the response message of the RPC.
518           Should the event terminate with non-OK status, the returned
519           Call-Future's exception value will be an RpcError.
520         """
521         raise NotImplementedError()
522
523
524 class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
525     """Affords intercepting stream-stream invocations."""
526
527     @abc.abstractmethod
528     def intercept_stream_stream(self, continuation, client_call_details,
529                                 request_iterator):
530         """Intercepts a stream-stream invocation.
531
532         Args:
533           continuation: A function that proceeds with the invocation by
534             executing the next interceptor in chain or invoking the
535             actual RPC on the underlying Channel. It is the interceptor's
536             responsibility to call it if it decides to move the RPC forward.
537             The interceptor can use
538             `response_iterator = continuation(client_call_details, request_iterator)`
539             to continue with the RPC. `continuation` returns an object that is
540             both a Call for the RPC and an iterator for response values.
541             Drawing response values from the returned Call-iterator may
542             raise RpcError indicating termination of the RPC with non-OK
543             status.
544           client_call_details: A ClientCallDetails object describing the
545             outgoing RPC.
546           request_iterator: An iterator that yields request values for the RPC.
547
548         Returns:
549           An object that is both a Call for the RPC and an iterator of
550           response values. Drawing response values from the returned
551           Call-iterator may raise RpcError indicating termination of
552           the RPC with non-OK status. This object *should* also fulfill the
553           Future interface, though it may not.
554         """
555         raise NotImplementedError()
556
557
558 ############  Authentication & Authorization Interfaces & Classes  #############
559
560
561 class ChannelCredentials(object):
562     """An encapsulation of the data required to create a secure Channel.
563
564     This class has no supported interface - it exists to define the type of its
565     instances and its instances exist to be passed to other functions. For
566     example, ssl_channel_credentials returns an instance of this class and
567     secure_channel requires an instance of this class.
568     """
569
570     def __init__(self, credentials):
571         self._credentials = credentials
572
573
574 class CallCredentials(object):
575     """An encapsulation of the data required to assert an identity over a call.
576
577     A CallCredentials has to be used with secure Channel, otherwise the
578     metadata will not be transmitted to the server.
579
580     A CallCredentials may be composed with ChannelCredentials to always assert
581     identity for every call over that Channel.
582
583     This class has no supported interface - it exists to define the type of its
584     instances and its instances exist to be passed to other functions.
585     """
586
587     def __init__(self, credentials):
588         self._credentials = credentials
589
590
591 class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
592     """Provides information to call credentials metadata plugins.
593
594     Attributes:
595       service_url: A string URL of the service being called into.
596       method_name: A string of the fully qualified method name being called.
597     """
598
599
600 class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)):
601     """Callback object received by a metadata plugin."""
602
603     def __call__(self, metadata, error):
604         """Passes to the gRPC runtime authentication metadata for an RPC.
605
606         Args:
607           metadata: The :term:`metadata` used to construct the CallCredentials.
608           error: An Exception to indicate error or None to indicate success.
609         """
610         raise NotImplementedError()
611
612
613 class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
614     """A specification for custom authentication."""
615
616     def __call__(self, context, callback):
617         """Implements authentication by passing metadata to a callback.
618
619         This method will be invoked asynchronously in a separate thread.
620
621         Args:
622           context: An AuthMetadataContext providing information on the RPC that
623             the plugin is being called to authenticate.
624           callback: An AuthMetadataPluginCallback to be invoked either
625             synchronously or asynchronously.
626         """
627         raise NotImplementedError()
628
629
630 class ServerCredentials(object):
631     """An encapsulation of the data required to open a secure port on a Server.
632
633     This class has no supported interface - it exists to define the type of its
634     instances and its instances exist to be passed to other functions.
635     """
636
637     def __init__(self, credentials):
638         self._credentials = credentials
639
640
641 class ServerCertificateConfiguration(object):
642     """A certificate configuration for use with an SSL-enabled Server.
643
644     Instances of this class can be returned in the certificate configuration
645     fetching callback.
646
647     This class has no supported interface -- it exists to define the
648     type of its instances and its instances exist to be passed to
649     other functions.
650     """
651
652     def __init__(self, certificate_configuration):
653         self._certificate_configuration = certificate_configuration
654
655
656 ########################  Multi-Callable Interfaces  ###########################
657
658
659 class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
660     """Affords invoking a unary-unary RPC from client-side."""
661
662     @abc.abstractmethod
663     def __call__(self,
664                  request,
665                  timeout=None,
666                  metadata=None,
667                  credentials=None,
668                  wait_for_ready=None,
669                  compression=None):
670         """Synchronously invokes the underlying RPC.
671
672         Args:
673           request: The request value for the RPC.
674           timeout: An optional duration of time in seconds to allow
675             for the RPC.
676           metadata: Optional :term:`metadata` to be transmitted to the
677             service-side of the RPC.
678           credentials: An optional CallCredentials for the RPC. Only valid for
679             secure Channel.
680           wait_for_ready: This is an EXPERIMENTAL argument. An optional
681             flag to enable :term:`wait_for_ready` mechanism.
682           compression: An element of grpc.compression, e.g.
683             grpc.compression.Gzip. This is an EXPERIMENTAL option.
684
685         Returns:
686           The response value for the RPC.
687
688         Raises:
689           RpcError: Indicating that the RPC terminated with non-OK status. The
690             raised RpcError will also be a Call for the RPC affording the RPC's
691             metadata, status code, and details.
692         """
693         raise NotImplementedError()
694
695     @abc.abstractmethod
696     def with_call(self,
697                   request,
698                   timeout=None,
699                   metadata=None,
700                   credentials=None,
701                   wait_for_ready=None,
702                   compression=None):
703         """Synchronously invokes the underlying RPC.
704
705         Args:
706           request: The request value for the RPC.
707           timeout: An optional durating of time in seconds to allow for
708             the RPC.
709           metadata: Optional :term:`metadata` to be transmitted to the
710             service-side of the RPC.
711           credentials: An optional CallCredentials for the RPC. Only valid for
712             secure Channel.
713           wait_for_ready: This is an EXPERIMENTAL argument. An optional
714             flag to enable :term:`wait_for_ready` mechanism.
715           compression: An element of grpc.compression, e.g.
716             grpc.compression.Gzip. This is an EXPERIMENTAL option.
717
718         Returns:
719           The response value for the RPC and a Call value for the RPC.
720
721         Raises:
722           RpcError: Indicating that the RPC terminated with non-OK status. The
723             raised RpcError will also be a Call for the RPC affording the RPC's
724             metadata, status code, and details.
725         """
726         raise NotImplementedError()
727
728     @abc.abstractmethod
729     def future(self,
730                request,
731                timeout=None,
732                metadata=None,
733                credentials=None,
734                wait_for_ready=None,
735                compression=None):
736         """Asynchronously invokes the underlying RPC.
737
738         Args:
739           request: The request value for the RPC.
740           timeout: An optional duration of time in seconds to allow for
741             the RPC.
742           metadata: Optional :term:`metadata` to be transmitted to the
743             service-side of the RPC.
744           credentials: An optional CallCredentials for the RPC. Only valid for
745             secure Channel.
746           wait_for_ready: This is an EXPERIMENTAL argument. An optional
747             flag to enable :term:`wait_for_ready` mechanism.
748           compression: An element of grpc.compression, e.g.
749             grpc.compression.Gzip. This is an EXPERIMENTAL option.
750
751         Returns:
752             An object that is both a Call for the RPC and a Future.
753             In the event of RPC completion, the return Call-Future's result
754             value will be the response message of the RPC.
755             Should the event terminate with non-OK status,
756             the returned Call-Future's exception value will be an RpcError.
757         """
758         raise NotImplementedError()
759
760
761 class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
762     """Affords invoking a unary-stream RPC from client-side."""
763
764     @abc.abstractmethod
765     def __call__(self,
766                  request,
767                  timeout=None,
768                  metadata=None,
769                  credentials=None,
770                  wait_for_ready=None,
771                  compression=None):
772         """Invokes the underlying RPC.
773
774         Args:
775           request: The request value for the RPC.
776           timeout: An optional duration of time in seconds to allow for
777             the RPC. If None, the timeout is considered infinite.
778           metadata: An optional :term:`metadata` to be transmitted to the
779             service-side of the RPC.
780           credentials: An optional CallCredentials for the RPC. Only valid for
781             secure Channel.
782           wait_for_ready: This is an EXPERIMENTAL argument. An optional
783             flag to enable :term:`wait_for_ready` mechanism.
784           compression: An element of grpc.compression, e.g.
785             grpc.compression.Gzip. This is an EXPERIMENTAL option.
786
787         Returns:
788             An object that is a Call for the RPC, an iterator of response
789             values, and a Future for the RPC. Drawing response values from the
790             returned Call-iterator may raise RpcError indicating termination of
791             the RPC with non-OK status.
792         """
793         raise NotImplementedError()
794
795
796 class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
797     """Affords invoking a stream-unary RPC from client-side."""
798
799     @abc.abstractmethod
800     def __call__(self,
801                  request_iterator,
802                  timeout=None,
803                  metadata=None,
804                  credentials=None,
805                  wait_for_ready=None,
806                  compression=None):
807         """Synchronously invokes the underlying RPC.
808
809         Args:
810           request_iterator: An iterator that yields request values for
811             the RPC.
812           timeout: An optional duration of time in seconds to allow for
813             the RPC. If None, the timeout is considered infinite.
814           metadata: Optional :term:`metadata` to be transmitted to the
815             service-side of the RPC.
816           credentials: An optional CallCredentials for the RPC. Only valid for
817             secure Channel.
818           wait_for_ready: This is an EXPERIMENTAL argument. An optional
819             flag to enable :term:`wait_for_ready` mechanism.
820           compression: An element of grpc.compression, e.g.
821             grpc.compression.Gzip. This is an EXPERIMENTAL option.
822
823         Returns:
824           The response value for the RPC.
825
826         Raises:
827           RpcError: Indicating that the RPC terminated with non-OK status. The
828             raised RpcError will also implement grpc.Call, affording methods
829             such as metadata, code, and details.
830         """
831         raise NotImplementedError()
832
833     @abc.abstractmethod
834     def with_call(self,
835                   request_iterator,
836                   timeout=None,
837                   metadata=None,
838                   credentials=None,
839                   wait_for_ready=None,
840                   compression=None):
841         """Synchronously invokes the underlying RPC on the client.
842
843         Args:
844           request_iterator: An iterator that yields request values for
845             the RPC.
846           timeout: An optional duration of time in seconds to allow for
847             the RPC. If None, the timeout is considered infinite.
848           metadata: Optional :term:`metadata` to be transmitted to the
849             service-side of the RPC.
850           credentials: An optional CallCredentials for the RPC. Only valid for
851             secure Channel.
852           wait_for_ready: This is an EXPERIMENTAL argument. An optional
853             flag to enable :term:`wait_for_ready` mechanism.
854           compression: An element of grpc.compression, e.g.
855             grpc.compression.Gzip. This is an EXPERIMENTAL option.
856
857         Returns:
858           The response value for the RPC and a Call object for the RPC.
859
860         Raises:
861           RpcError: Indicating that the RPC terminated with non-OK status. The
862             raised RpcError will also be a Call for the RPC affording the RPC's
863             metadata, status code, and details.
864         """
865         raise NotImplementedError()
866
867     @abc.abstractmethod
868     def future(self,
869                request_iterator,
870                timeout=None,
871                metadata=None,
872                credentials=None,
873                wait_for_ready=None,
874                compression=None):
875         """Asynchronously invokes the underlying RPC on the client.
876
877         Args:
878           request_iterator: An iterator that yields request values for the RPC.
879           timeout: An optional duration of time in seconds to allow for
880             the RPC. If None, the timeout is considered infinite.
881           metadata: Optional :term:`metadata` to be transmitted to the
882             service-side of the RPC.
883           credentials: An optional CallCredentials for the RPC. Only valid for
884             secure Channel.
885           wait_for_ready: This is an EXPERIMENTAL argument. An optional
886             flag to enable :term:`wait_for_ready` mechanism.
887           compression: An element of grpc.compression, e.g.
888             grpc.compression.Gzip. This is an EXPERIMENTAL option.
889
890         Returns:
891             An object that is both a Call for the RPC and a Future.
892             In the event of RPC completion, the return Call-Future's result value
893             will be the response message of the RPC. Should the event terminate
894             with non-OK status, the returned Call-Future's exception value will
895             be an RpcError.
896         """
897         raise NotImplementedError()
898
899
900 class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
901     """Affords invoking a stream-stream RPC on client-side."""
902
903     @abc.abstractmethod
904     def __call__(self,
905                  request_iterator,
906                  timeout=None,
907                  metadata=None,
908                  credentials=None,
909                  wait_for_ready=None,
910                  compression=None):
911         """Invokes the underlying RPC on the client.
912
913         Args:
914           request_iterator: An iterator that yields request values for the RPC.
915           timeout: An optional duration of time in seconds to allow for
916             the RPC. If not specified, the timeout is considered infinite.
917           metadata: Optional :term:`metadata` to be transmitted to the
918             service-side of the RPC.
919           credentials: An optional CallCredentials for the RPC. Only valid for
920             secure Channel.
921           wait_for_ready: This is an EXPERIMENTAL argument. An optional
922             flag to enable :term:`wait_for_ready` mechanism.
923           compression: An element of grpc.compression, e.g.
924             grpc.compression.Gzip. This is an EXPERIMENTAL option.
925
926         Returns:
927             An object that is a Call for the RPC, an iterator of response
928             values, and a Future for the RPC. Drawing response values from the
929             returned Call-iterator may raise RpcError indicating termination of
930             the RPC with non-OK status.
931         """
932         raise NotImplementedError()
933
934
935 #############################  Channel Interface  ##############################
936
937
938 class Channel(six.with_metaclass(abc.ABCMeta)):
939     """Affords RPC invocation via generic methods on client-side.
940
941     Channel objects implement the Context Manager type, although they need not
942     support being entered and exited multiple times.
943     """
944
945     @abc.abstractmethod
946     def subscribe(self, callback, try_to_connect=False):
947         """Subscribe to this Channel's connectivity state machine.
948
949         A Channel may be in any of the states described by ChannelConnectivity.
950         This method allows application to monitor the state transitions.
951         The typical use case is to debug or gain better visibility into gRPC
952         runtime's state.
953
954         Args:
955           callback: A callable to be invoked with ChannelConnectivity argument.
956             ChannelConnectivity describes current state of the channel.
957             The callable will be invoked immediately upon subscription
958             and again for every change to ChannelConnectivity until it
959             is unsubscribed or this Channel object goes out of scope.
960           try_to_connect: A boolean indicating whether or not this Channel
961             should attempt to connect immediately. If set to False, gRPC
962             runtime decides when to connect.
963         """
964         raise NotImplementedError()
965
966     @abc.abstractmethod
967     def unsubscribe(self, callback):
968         """Unsubscribes a subscribed callback from this Channel's connectivity.
969
970         Args:
971           callback: A callable previously registered with this Channel from
972           having been passed to its "subscribe" method.
973         """
974         raise NotImplementedError()
975
976     @abc.abstractmethod
977     def unary_unary(self,
978                     method,
979                     request_serializer=None,
980                     response_deserializer=None):
981         """Creates a UnaryUnaryMultiCallable for a unary-unary method.
982
983         Args:
984           method: The name of the RPC method.
985           request_serializer: Optional :term:`serializer` for serializing the request
986             message. Request goes unserialized in case None is passed.
987           response_deserializer: Optional :term:`deserializer` for deserializing the
988             response message. Response goes undeserialized in case None
989             is passed.
990
991         Returns:
992           A UnaryUnaryMultiCallable value for the named unary-unary method.
993         """
994         raise NotImplementedError()
995
996     @abc.abstractmethod
997     def unary_stream(self,
998                      method,
999                      request_serializer=None,
1000                      response_deserializer=None):
1001         """Creates a UnaryStreamMultiCallable for a unary-stream method.
1002
1003         Args:
1004           method: The name of the RPC method.
1005           request_serializer: Optional :term:`serializer` for serializing the request
1006             message. Request goes unserialized in case None is passed.
1007           response_deserializer: Optional :term:`deserializer` for deserializing the
1008             response message. Response goes undeserialized in case None is
1009             passed.
1010
1011         Returns:
1012           A UnaryStreamMultiCallable value for the name unary-stream method.
1013         """
1014         raise NotImplementedError()
1015
1016     @abc.abstractmethod
1017     def stream_unary(self,
1018                      method,
1019                      request_serializer=None,
1020                      response_deserializer=None):
1021         """Creates a StreamUnaryMultiCallable for a stream-unary method.
1022
1023         Args:
1024           method: The name of the RPC method.
1025           request_serializer: Optional :term:`serializer` for serializing the request
1026             message. Request goes unserialized in case None is passed.
1027           response_deserializer: Optional :term:`deserializer` for deserializing the
1028             response message. Response goes undeserialized in case None is
1029             passed.
1030
1031         Returns:
1032           A StreamUnaryMultiCallable value for the named stream-unary method.
1033         """
1034         raise NotImplementedError()
1035
1036     @abc.abstractmethod
1037     def stream_stream(self,
1038                       method,
1039                       request_serializer=None,
1040                       response_deserializer=None):
1041         """Creates a StreamStreamMultiCallable for a stream-stream method.
1042
1043         Args:
1044           method: The name of the RPC method.
1045           request_serializer: Optional :term:`serializer` for serializing the request
1046             message. Request goes unserialized in case None is passed.
1047           response_deserializer: Optional :term:`deserializer` for deserializing the
1048             response message. Response goes undeserialized in case None
1049             is passed.
1050
1051         Returns:
1052           A StreamStreamMultiCallable value for the named stream-stream method.
1053         """
1054         raise NotImplementedError()
1055
1056     @abc.abstractmethod
1057     def close(self):
1058         """Closes this Channel and releases all resources held by it.
1059
1060         Closing the Channel will immediately terminate all RPCs active with the
1061         Channel and it is not valid to invoke new RPCs with the Channel.
1062
1063         This method is idempotent.
1064         """
1065         raise NotImplementedError()
1066
1067     def __enter__(self):
1068         """Enters the runtime context related to the channel object."""
1069         raise NotImplementedError()
1070
1071     def __exit__(self, exc_type, exc_val, exc_tb):
1072         """Exits the runtime context related to the channel object."""
1073         raise NotImplementedError()
1074
1075
1076 ##########################  Service-Side Context  ##############################
1077
1078
1079 class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
1080     """A context object passed to method implementations."""
1081
1082     @abc.abstractmethod
1083     def invocation_metadata(self):
1084         """Accesses the metadata from the sent by the client.
1085
1086         Returns:
1087           The invocation :term:`metadata`.
1088         """
1089         raise NotImplementedError()
1090
1091     @abc.abstractmethod
1092     def peer(self):
1093         """Identifies the peer that invoked the RPC being serviced.
1094
1095         Returns:
1096           A string identifying the peer that invoked the RPC being serviced.
1097           The string format is determined by gRPC runtime.
1098         """
1099         raise NotImplementedError()
1100
1101     @abc.abstractmethod
1102     def peer_identities(self):
1103         """Gets one or more peer identity(s).
1104
1105         Equivalent to
1106         servicer_context.auth_context().get(servicer_context.peer_identity_key())
1107
1108         Returns:
1109           An iterable of the identities, or None if the call is not
1110           authenticated. Each identity is returned as a raw bytes type.
1111         """
1112         raise NotImplementedError()
1113
1114     @abc.abstractmethod
1115     def peer_identity_key(self):
1116         """The auth property used to identify the peer.
1117
1118         For example, "x509_common_name" or "x509_subject_alternative_name" are
1119         used to identify an SSL peer.
1120
1121         Returns:
1122           The auth property (string) that indicates the
1123           peer identity, or None if the call is not authenticated.
1124         """
1125         raise NotImplementedError()
1126
1127     @abc.abstractmethod
1128     def auth_context(self):
1129         """Gets the auth context for the call.
1130
1131         Returns:
1132           A map of strings to an iterable of bytes for each auth property.
1133         """
1134         raise NotImplementedError()
1135
1136     def set_compression(self, compression):
1137         """Set the compression algorithm to be used for the entire call.
1138
1139         This is an EXPERIMENTAL method.
1140
1141         Args:
1142           compression: An element of grpc.compression, e.g.
1143             grpc.compression.Gzip.
1144         """
1145         raise NotImplementedError()
1146
1147     @abc.abstractmethod
1148     def send_initial_metadata(self, initial_metadata):
1149         """Sends the initial metadata value to the client.
1150
1151         This method need not be called by implementations if they have no
1152         metadata to add to what the gRPC runtime will transmit.
1153
1154         Args:
1155           initial_metadata: The initial :term:`metadata`.
1156         """
1157         raise NotImplementedError()
1158
1159     @abc.abstractmethod
1160     def set_trailing_metadata(self, trailing_metadata):
1161         """Sets the trailing metadata for the RPC.
1162
1163         Sets the trailing metadata to be sent upon completion of the RPC.
1164
1165         If this method is invoked multiple times throughout the lifetime of an
1166         RPC, the value supplied in the final invocation will be the value sent
1167         over the wire.
1168
1169         This method need not be called by implementations if they have no
1170         metadata to add to what the gRPC runtime will transmit.
1171
1172         Args:
1173           trailing_metadata: The trailing :term:`metadata`.
1174         """
1175         raise NotImplementedError()
1176
1177     def trailing_metadata(self):
1178         """Access value to be used as trailing metadata upon RPC completion.
1179
1180         This is an EXPERIMENTAL API.
1181
1182         Returns:
1183           The trailing :term:`metadata` for the RPC.
1184         """
1185         raise NotImplementedError()
1186
1187     @abc.abstractmethod
1188     def abort(self, code, details):
1189         """Raises an exception to terminate the RPC with a non-OK status.
1190
1191         The code and details passed as arguments will supercede any existing
1192         ones.
1193
1194         Args:
1195           code: A StatusCode object to be sent to the client.
1196             It must not be StatusCode.OK.
1197           details: A UTF-8-encodable string to be sent to the client upon
1198             termination of the RPC.
1199
1200         Raises:
1201           Exception: An exception is always raised to signal the abortion the
1202             RPC to the gRPC runtime.
1203         """
1204         raise NotImplementedError()
1205
1206     @abc.abstractmethod
1207     def abort_with_status(self, status):
1208         """Raises an exception to terminate the RPC with a non-OK status.
1209
1210         The status passed as argument will supercede any existing status code,
1211         status message and trailing metadata.
1212
1213         This is an EXPERIMENTAL API.
1214
1215         Args:
1216           status: A grpc.Status object. The status code in it must not be
1217             StatusCode.OK.
1218
1219         Raises:
1220           Exception: An exception is always raised to signal the abortion the
1221             RPC to the gRPC runtime.
1222         """
1223         raise NotImplementedError()
1224
1225     @abc.abstractmethod
1226     def set_code(self, code):
1227         """Sets the value to be used as status code upon RPC completion.
1228
1229         This method need not be called by method implementations if they wish
1230         the gRPC runtime to determine the status code of the RPC.
1231
1232         Args:
1233           code: A StatusCode object to be sent to the client.
1234         """
1235         raise NotImplementedError()
1236
1237     @abc.abstractmethod
1238     def set_details(self, details):
1239         """Sets the value to be used as detail string upon RPC completion.
1240
1241         This method need not be called by method implementations if they have
1242         no details to transmit.
1243
1244         Args:
1245           details: A UTF-8-encodable string to be sent to the client upon
1246             termination of the RPC.
1247         """
1248         raise NotImplementedError()
1249
1250     def code(self):
1251         """Accesses the value to be used as status code upon RPC completion.
1252
1253         This is an EXPERIMENTAL API.
1254
1255         Returns:
1256           The StatusCode value for the RPC.
1257         """
1258         raise NotImplementedError()
1259
1260     def details(self):
1261         """Accesses the value to be used as detail string upon RPC completion.
1262
1263         This is an EXPERIMENTAL API.
1264
1265         Returns:
1266           The details string of the RPC.
1267         """
1268         raise NotImplementedError()
1269
1270     def disable_next_message_compression(self):
1271         """Disables compression for the next response message.
1272
1273         This is an EXPERIMENTAL method.
1274
1275         This method will override any compression configuration set during
1276         server creation or set on the call.
1277         """
1278         raise NotImplementedError()
1279
1280
1281 #####################  Service-Side Handler Interfaces  ########################
1282
1283
1284 class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
1285     """An implementation of a single RPC method.
1286
1287     Attributes:
1288       request_streaming: Whether the RPC supports exactly one request message
1289         or any arbitrary number of request messages.
1290       response_streaming: Whether the RPC supports exactly one response message
1291         or any arbitrary number of response messages.
1292       request_deserializer: A callable :term:`deserializer` that accepts a byte string and
1293         returns an object suitable to be passed to this object's business
1294         logic, or None to indicate that this object's business logic should be
1295         passed the raw request bytes.
1296       response_serializer: A callable :term:`serializer` that accepts an object produced
1297         by this object's business logic and returns a byte string, or None to
1298         indicate that the byte strings produced by this object's business logic
1299         should be transmitted on the wire as they are.
1300       unary_unary: This object's application-specific business logic as a
1301         callable value that takes a request value and a ServicerContext object
1302         and returns a response value. Only non-None if both request_streaming
1303         and response_streaming are False.
1304       unary_stream: This object's application-specific business logic as a
1305         callable value that takes a request value and a ServicerContext object
1306         and returns an iterator of response values. Only non-None if
1307         request_streaming is False and response_streaming is True.
1308       stream_unary: This object's application-specific business logic as a
1309         callable value that takes an iterator of request values and a
1310         ServicerContext object and returns a response value. Only non-None if
1311         request_streaming is True and response_streaming is False.
1312       stream_stream: 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 an iterator of response values.
1315         Only non-None if request_streaming and response_streaming are both
1316         True.
1317     """
1318
1319
1320 class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
1321     """Describes an RPC that has just arrived for service.
1322
1323     Attributes:
1324       method: The method name of the RPC.
1325       invocation_metadata: The :term:`metadata` sent by the client.
1326     """
1327
1328
1329 class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
1330     """An implementation of arbitrarily many RPC methods."""
1331
1332     @abc.abstractmethod
1333     def service(self, handler_call_details):
1334         """Returns the handler for servicing the RPC.
1335
1336         Args:
1337           handler_call_details: A HandlerCallDetails describing the RPC.
1338
1339         Returns:
1340           An RpcMethodHandler with which the RPC may be serviced if the
1341           implementation chooses to service this RPC, or None otherwise.
1342         """
1343         raise NotImplementedError()
1344
1345
1346 class ServiceRpcHandler(six.with_metaclass(abc.ABCMeta, GenericRpcHandler)):
1347     """An implementation of RPC methods belonging to a service.
1348
1349     A service handles RPC methods with structured names of the form
1350     '/Service.Name/Service.Method', where 'Service.Name' is the value
1351     returned by service_name(), and 'Service.Method' is the method
1352     name.  A service can have multiple method names, but only a single
1353     service name.
1354     """
1355
1356     @abc.abstractmethod
1357     def service_name(self):
1358         """Returns this service's name.
1359
1360         Returns:
1361           The service name.
1362         """
1363         raise NotImplementedError()
1364
1365
1366 ####################  Service-Side Interceptor Interfaces  #####################
1367
1368
1369 class ServerInterceptor(six.with_metaclass(abc.ABCMeta)):
1370     """Affords intercepting incoming RPCs on the service-side."""
1371
1372     @abc.abstractmethod
1373     def intercept_service(self, continuation, handler_call_details):
1374         """Intercepts incoming RPCs before handing them over to a handler.
1375
1376         Args:
1377           continuation: A function that takes a HandlerCallDetails and
1378             proceeds to invoke the next interceptor in the chain, if any,
1379             or the RPC handler lookup logic, with the call details passed
1380             as an argument, and returns an RpcMethodHandler instance if
1381             the RPC is considered serviced, or None otherwise.
1382           handler_call_details: A HandlerCallDetails describing the RPC.
1383
1384         Returns:
1385           An RpcMethodHandler with which the RPC may be serviced if the
1386           interceptor chooses to service this RPC, or None otherwise.
1387         """
1388         raise NotImplementedError()
1389
1390
1391 #############################  Server Interface  ###############################
1392
1393
1394 class Server(six.with_metaclass(abc.ABCMeta)):
1395     """Services RPCs."""
1396
1397     @abc.abstractmethod
1398     def add_generic_rpc_handlers(self, generic_rpc_handlers):
1399         """Registers GenericRpcHandlers with this Server.
1400
1401         This method is only safe to call before the server is started.
1402
1403         Args:
1404           generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1405           used to service RPCs.
1406         """
1407         raise NotImplementedError()
1408
1409     @abc.abstractmethod
1410     def add_insecure_port(self, address):
1411         """Opens an insecure port for accepting RPCs.
1412
1413         This method may only be called before starting the server.
1414
1415         Args:
1416           address: The address for which to open a port. If the port is 0,
1417             or not specified in the address, then gRPC runtime will choose a port.
1418
1419         Returns:
1420           An integer port on which server will accept RPC requests.
1421         """
1422         raise NotImplementedError()
1423
1424     @abc.abstractmethod
1425     def add_secure_port(self, address, server_credentials):
1426         """Opens a secure port for accepting RPCs.
1427
1428         This method may only be called before starting the server.
1429
1430         Args:
1431           address: The address for which to open a port.
1432             if the port is 0, or not specified in the address, then gRPC
1433             runtime will choose a port.
1434           server_credentials: A ServerCredentials object.
1435
1436         Returns:
1437           An integer port on which server will accept RPC requests.
1438         """
1439         raise NotImplementedError()
1440
1441     @abc.abstractmethod
1442     def start(self):
1443         """Starts this Server.
1444
1445         This method may only be called once. (i.e. it is not idempotent).
1446         """
1447         raise NotImplementedError()
1448
1449     @abc.abstractmethod
1450     def stop(self, grace):
1451         """Stops this Server.
1452
1453         This method immediately stop service of new RPCs in all cases.
1454
1455         If a grace period is specified, this method returns immediately
1456         and all RPCs active at the end of the grace period are aborted.
1457         If a grace period is not specified (by passing None for `grace`),
1458         all existing RPCs are aborted immediately and this method
1459         blocks until the last RPC handler terminates.
1460
1461         This method is idempotent and may be called at any time.
1462         Passing a smaller grace value in a subsequent call will have
1463         the effect of stopping the Server sooner (passing None will
1464         have the effect of stopping the server immediately). Passing
1465         a larger grace value in a subsequent call *will not* have the
1466         effect of stopping the server later (i.e. the most restrictive
1467         grace value is used).
1468
1469         Args:
1470           grace: A duration of time in seconds or None.
1471
1472         Returns:
1473           A threading.Event that will be set when this Server has completely
1474           stopped, i.e. when running RPCs either complete or are aborted and
1475           all handlers have terminated.
1476         """
1477         raise NotImplementedError()
1478
1479     def wait_for_termination(self, timeout=None):
1480         """Block current thread until the server stops.
1481
1482         This is an EXPERIMENTAL API.
1483
1484         The wait will not consume computational resources during blocking, and
1485         it will block until one of the two following conditions are met:
1486
1487         1) The server is stopped or terminated;
1488         2) A timeout occurs if timeout is not `None`.
1489
1490         The timeout argument works in the same way as `threading.Event.wait()`.
1491         https://docs.python.org/3/library/threading.html#threading.Event.wait
1492
1493         Args:
1494           timeout: A floating point number specifying a timeout for the
1495             operation in seconds.
1496
1497         Returns:
1498           A bool indicates if the operation times out.
1499         """
1500         raise NotImplementedError()
1501
1502
1503 #################################  Functions    ################################
1504
1505
1506 def unary_unary_rpc_method_handler(behavior,
1507                                    request_deserializer=None,
1508                                    response_serializer=None):
1509     """Creates an RpcMethodHandler for a unary-unary RPC method.
1510
1511     Args:
1512       behavior: The implementation of an RPC that accepts one request
1513         and returns one response.
1514       request_deserializer: An optional :term:`deserializer` for request deserialization.
1515       response_serializer: An optional :term:`serializer` for response serialization.
1516
1517     Returns:
1518       An RpcMethodHandler object that is typically used by grpc.Server.
1519     """
1520     from grpc import _utilities  # pylint: disable=cyclic-import
1521     return _utilities.RpcMethodHandler(False, False, request_deserializer,
1522                                        response_serializer, behavior, None,
1523                                        None, None)
1524
1525
1526 def unary_stream_rpc_method_handler(behavior,
1527                                     request_deserializer=None,
1528                                     response_serializer=None):
1529     """Creates an RpcMethodHandler for a unary-stream RPC method.
1530
1531     Args:
1532       behavior: The implementation of an RPC that accepts one request
1533         and returns an iterator of response values.
1534       request_deserializer: An optional :term:`deserializer` for request deserialization.
1535       response_serializer: An optional :term:`serializer` for response serialization.
1536
1537     Returns:
1538       An RpcMethodHandler object that is typically used by grpc.Server.
1539     """
1540     from grpc import _utilities  # pylint: disable=cyclic-import
1541     return _utilities.RpcMethodHandler(False, True, request_deserializer,
1542                                        response_serializer, None, behavior,
1543                                        None, None)
1544
1545
1546 def stream_unary_rpc_method_handler(behavior,
1547                                     request_deserializer=None,
1548                                     response_serializer=None):
1549     """Creates an RpcMethodHandler for a stream-unary RPC method.
1550
1551     Args:
1552       behavior: The implementation of an RPC that accepts an iterator of
1553         request values and returns a single response value.
1554       request_deserializer: An optional :term:`deserializer` for request deserialization.
1555       response_serializer: An optional :term:`serializer` for response serialization.
1556
1557     Returns:
1558       An RpcMethodHandler object that is typically used by grpc.Server.
1559     """
1560     from grpc import _utilities  # pylint: disable=cyclic-import
1561     return _utilities.RpcMethodHandler(True, False, request_deserializer,
1562                                        response_serializer, None, None,
1563                                        behavior, None)
1564
1565
1566 def stream_stream_rpc_method_handler(behavior,
1567                                      request_deserializer=None,
1568                                      response_serializer=None):
1569     """Creates an RpcMethodHandler for a stream-stream RPC method.
1570
1571     Args:
1572       behavior: The implementation of an RPC that accepts an iterator of
1573         request values and returns an iterator of response values.
1574       request_deserializer: An optional :term:`deserializer` for request deserialization.
1575       response_serializer: An optional :term:`serializer` for response serialization.
1576
1577     Returns:
1578       An RpcMethodHandler object that is typically used by grpc.Server.
1579     """
1580     from grpc import _utilities  # pylint: disable=cyclic-import
1581     return _utilities.RpcMethodHandler(True, True, request_deserializer,
1582                                        response_serializer, None, None, None,
1583                                        behavior)
1584
1585
1586 def method_handlers_generic_handler(service, method_handlers):
1587     """Creates a GenericRpcHandler from RpcMethodHandlers.
1588
1589     Args:
1590       service: The name of the service that is implemented by the
1591         method_handlers.
1592       method_handlers: A dictionary that maps method names to corresponding
1593         RpcMethodHandler.
1594
1595     Returns:
1596       A GenericRpcHandler. This is typically added to the grpc.Server object
1597       with add_generic_rpc_handlers() before starting the server.
1598     """
1599     from grpc import _utilities  # pylint: disable=cyclic-import
1600     return _utilities.DictionaryGenericHandler(service, method_handlers)
1601
1602
1603 def ssl_channel_credentials(root_certificates=None,
1604                             private_key=None,
1605                             certificate_chain=None):
1606     """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1607
1608     Args:
1609       root_certificates: The PEM-encoded root certificates as a byte string,
1610         or None to retrieve them from a default location chosen by gRPC
1611         runtime.
1612       private_key: The PEM-encoded private key as a byte string, or None if no
1613         private key should be used.
1614       certificate_chain: The PEM-encoded certificate chain as a byte string
1615         to use or None if no certificate chain should be used.
1616
1617     Returns:
1618       A ChannelCredentials for use with an SSL-enabled Channel.
1619     """
1620     return ChannelCredentials(
1621         _cygrpc.SSLChannelCredentials(root_certificates, private_key,
1622                                       certificate_chain))
1623
1624
1625 def xds_channel_credentials(fallback_credentials=None):
1626     """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL
1627       API.
1628
1629     Args:
1630       fallback_credentials: Credentials to use in case it is not possible to
1631         establish a secure connection via xDS. If no fallback_credentials
1632         argument is supplied, a default SSLChannelCredentials is used.
1633     """
1634     fallback_credentials = ssl_channel_credentials(
1635     ) if fallback_credentials is None else fallback_credentials
1636     return ChannelCredentials(
1637         _cygrpc.XDSChannelCredentials(fallback_credentials._credentials))
1638
1639
1640 def metadata_call_credentials(metadata_plugin, name=None):
1641     """Construct CallCredentials from an AuthMetadataPlugin.
1642
1643     Args:
1644       metadata_plugin: An AuthMetadataPlugin to use for authentication.
1645       name: An optional name for the plugin.
1646
1647     Returns:
1648       A CallCredentials.
1649     """
1650     from grpc import _plugin_wrapping  # pylint: disable=cyclic-import
1651     return _plugin_wrapping.metadata_plugin_call_credentials(
1652         metadata_plugin, name)
1653
1654
1655 def access_token_call_credentials(access_token):
1656     """Construct CallCredentials from an access token.
1657
1658     Args:
1659       access_token: A string to place directly in the http request
1660         authorization header, for example
1661         "authorization: Bearer <access_token>".
1662
1663     Returns:
1664       A CallCredentials.
1665     """
1666     from grpc import _auth  # pylint: disable=cyclic-import
1667     from grpc import _plugin_wrapping  # pylint: disable=cyclic-import
1668     return _plugin_wrapping.metadata_plugin_call_credentials(
1669         _auth.AccessTokenAuthMetadataPlugin(access_token), None)
1670
1671
1672 def composite_call_credentials(*call_credentials):
1673     """Compose multiple CallCredentials to make a new CallCredentials.
1674
1675     Args:
1676       *call_credentials: At least two CallCredentials objects.
1677
1678     Returns:
1679       A CallCredentials object composed of the given CallCredentials objects.
1680     """
1681     return CallCredentials(
1682         _cygrpc.CompositeCallCredentials(
1683             tuple(single_call_credentials._credentials
1684                   for single_call_credentials in call_credentials)))
1685
1686
1687 def composite_channel_credentials(channel_credentials, *call_credentials):
1688     """Compose a ChannelCredentials and one or more CallCredentials objects.
1689
1690     Args:
1691       channel_credentials: A ChannelCredentials object.
1692       *call_credentials: One or more CallCredentials objects.
1693
1694     Returns:
1695       A ChannelCredentials composed of the given ChannelCredentials and
1696         CallCredentials objects.
1697     """
1698     return ChannelCredentials(
1699         _cygrpc.CompositeChannelCredentials(
1700             tuple(single_call_credentials._credentials
1701                   for single_call_credentials in call_credentials),
1702             channel_credentials._credentials))
1703
1704
1705 def ssl_server_credentials(private_key_certificate_chain_pairs,
1706                            root_certificates=None,
1707                            require_client_auth=False):
1708     """Creates a ServerCredentials for use with an SSL-enabled Server.
1709
1710     Args:
1711       private_key_certificate_chain_pairs: A list of pairs of the form
1712         [PEM-encoded private key, PEM-encoded certificate chain].
1713       root_certificates: An optional byte string of PEM-encoded client root
1714         certificates that the server will use to verify client authentication.
1715         If omitted, require_client_auth must also be False.
1716       require_client_auth: A boolean indicating whether or not to require
1717         clients to be authenticated. May only be True if root_certificates
1718         is not None.
1719
1720     Returns:
1721       A ServerCredentials for use with an SSL-enabled Server. Typically, this
1722       object is an argument to add_secure_port() method during server setup.
1723     """
1724     if not private_key_certificate_chain_pairs:
1725         raise ValueError(
1726             'At least one private key-certificate chain pair is required!')
1727     elif require_client_auth and root_certificates is None:
1728         raise ValueError(
1729             'Illegal to require client auth without providing root certificates!'
1730         )
1731     else:
1732         return ServerCredentials(
1733             _cygrpc.server_credentials_ssl(root_certificates, [
1734                 _cygrpc.SslPemKeyCertPair(key, pem)
1735                 for key, pem in private_key_certificate_chain_pairs
1736             ], require_client_auth))
1737
1738
1739 def xds_server_credentials(fallback_credentials):
1740     """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL
1741       API.
1742
1743     Args:
1744       fallback_credentials: Credentials to use in case it is not possible to
1745         establish a secure connection via xDS. No default value is provided.
1746     """
1747     return ServerCredentials(
1748         _cygrpc.xds_server_credentials(fallback_credentials._credentials))
1749
1750
1751 def insecure_server_credentials():
1752     """Creates a credentials object directing the server to use no credentials.
1753       This is an EXPERIMENTAL API.
1754
1755     This object cannot be used directly in a call to `add_secure_port`.
1756     Instead, it should be used to construct other credentials objects, e.g.
1757     with xds_server_credentials.
1758     """
1759     return ServerCredentials(_cygrpc.insecure_server_credentials())
1760
1761
1762 def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
1763                                          root_certificates=None):
1764     """Creates a ServerCertificateConfiguration for use with a Server.
1765
1766     Args:
1767       private_key_certificate_chain_pairs: A collection of pairs of
1768         the form [PEM-encoded private key, PEM-encoded certificate
1769         chain].
1770       root_certificates: An optional byte string of PEM-encoded client root
1771         certificates that the server will use to verify client authentication.
1772
1773     Returns:
1774       A ServerCertificateConfiguration that can be returned in the certificate
1775         configuration fetching callback.
1776     """
1777     if private_key_certificate_chain_pairs:
1778         return ServerCertificateConfiguration(
1779             _cygrpc.server_certificate_config_ssl(root_certificates, [
1780                 _cygrpc.SslPemKeyCertPair(key, pem)
1781                 for key, pem in private_key_certificate_chain_pairs
1782             ]))
1783     else:
1784         raise ValueError(
1785             'At least one private key-certificate chain pair is required!')
1786
1787
1788 def dynamic_ssl_server_credentials(initial_certificate_configuration,
1789                                    certificate_configuration_fetcher,
1790                                    require_client_authentication=False):
1791     """Creates a ServerCredentials for use with an SSL-enabled Server.
1792
1793     Args:
1794       initial_certificate_configuration (ServerCertificateConfiguration): The
1795         certificate configuration with which the server will be initialized.
1796       certificate_configuration_fetcher (callable): A callable that takes no
1797         arguments and should return a ServerCertificateConfiguration to
1798         replace the server's current certificate, or None for no change
1799         (i.e., the server will continue its current certificate
1800         config). The library will call this callback on *every* new
1801         client connection before starting the TLS handshake with the
1802         client, thus allowing the user application to optionally
1803         return a new ServerCertificateConfiguration that the server will then
1804         use for the handshake.
1805       require_client_authentication: A boolean indicating whether or not to
1806         require clients to be authenticated.
1807
1808     Returns:
1809       A ServerCredentials.
1810     """
1811     return ServerCredentials(
1812         _cygrpc.server_credentials_ssl_dynamic_cert_config(
1813             initial_certificate_configuration,
1814             certificate_configuration_fetcher, require_client_authentication))
1815
1816
1817 @enum.unique
1818 class LocalConnectionType(enum.Enum):
1819     """Types of local connection for local credential creation.
1820
1821     Attributes:
1822       UDS: Unix domain socket connections
1823       LOCAL_TCP: Local TCP connections.
1824     """
1825     UDS = _cygrpc.LocalConnectionType.uds
1826     LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
1827
1828
1829 def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1830     """Creates a local ChannelCredentials used for local connections.
1831
1832     This is an EXPERIMENTAL API.
1833
1834     Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1835     also UDS connections.
1836
1837     The connections created by local channel credentials are not
1838     encrypted, but will be checked if they are local or not.
1839     The UDS connections are considered secure by providing peer authentication
1840     and data confidentiality while TCP connections are considered insecure.
1841
1842     It is allowed to transmit call credentials over connections created by
1843     local channel credentials.
1844
1845     Local channel credentials are useful for 1) eliminating insecure_channel usage;
1846     2) enable unit testing for call credentials without setting up secrets.
1847
1848     Args:
1849       local_connect_type: Local connection type (either
1850         grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1851
1852     Returns:
1853       A ChannelCredentials for use with a local Channel
1854     """
1855     return ChannelCredentials(
1856         _cygrpc.channel_credentials_local(local_connect_type.value))
1857
1858
1859 def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1860     """Creates a local ServerCredentials used for local connections.
1861
1862     This is an EXPERIMENTAL API.
1863
1864     Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1865     also UDS connections.
1866
1867     The connections created by local server credentials are not
1868     encrypted, but will be checked if they are local or not.
1869     The UDS connections are considered secure by providing peer authentication
1870     and data confidentiality while TCP connections are considered insecure.
1871
1872     It is allowed to transmit call credentials over connections created by local
1873     server credentials.
1874
1875     Local server credentials are useful for 1) eliminating insecure_channel usage;
1876     2) enable unit testing for call credentials without setting up secrets.
1877
1878     Args:
1879       local_connect_type: Local connection type (either
1880         grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1881
1882     Returns:
1883       A ServerCredentials for use with a local Server
1884     """
1885     return ServerCredentials(
1886         _cygrpc.server_credentials_local(local_connect_type.value))
1887
1888
1889 def alts_channel_credentials(service_accounts=None):
1890     """Creates a ChannelCredentials for use with an ALTS-enabled Channel.
1891
1892     This is an EXPERIMENTAL API.
1893     ALTS credentials API can only be used in GCP environment as it relies on
1894     handshaker service being available. For more info about ALTS see
1895     https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1896
1897     Args:
1898       service_accounts: A list of server identities accepted by the client.
1899         If target service accounts are provided and none of them matches the
1900         peer identity of the server, handshake will fail. The arg can be empty
1901         if the client does not have any information about trusted server
1902         identity.
1903     Returns:
1904       A ChannelCredentials for use with an ALTS-enabled Channel
1905     """
1906     return ChannelCredentials(
1907         _cygrpc.channel_credentials_alts(service_accounts or []))
1908
1909
1910 def alts_server_credentials():
1911     """Creates a ServerCredentials for use with an ALTS-enabled connection.
1912
1913     This is an EXPERIMENTAL API.
1914     ALTS credentials API can only be used in GCP environment as it relies on
1915     handshaker service being available. For more info about ALTS see
1916     https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1917
1918     Returns:
1919       A ServerCredentials for use with an ALTS-enabled Server
1920     """
1921     return ServerCredentials(_cygrpc.server_credentials_alts())
1922
1923
1924 def compute_engine_channel_credentials(call_credentials):
1925     """Creates a compute engine channel credential.
1926
1927     This credential can only be used in a GCP environment as it relies on
1928     a handshaker service. For more info about ALTS, see
1929     https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1930
1931     This channel credential is expected to be used as part of a composite
1932     credential in conjunction with a call credentials that authenticates the
1933     VM's default service account. If used with any other sort of call
1934     credential, the connection may suddenly and unexpectedly begin failing RPCs.
1935     """
1936     return ChannelCredentials(
1937         _cygrpc.channel_credentials_compute_engine(
1938             call_credentials._credentials))
1939
1940
1941 def channel_ready_future(channel):
1942     """Creates a Future that tracks when a Channel is ready.
1943
1944     Cancelling the Future does not affect the channel's state machine.
1945     It merely decouples the Future from channel state machine.
1946
1947     Args:
1948       channel: A Channel object.
1949
1950     Returns:
1951       A Future object that matures when the channel connectivity is
1952       ChannelConnectivity.READY.
1953     """
1954     from grpc import _utilities  # pylint: disable=cyclic-import
1955     return _utilities.channel_ready_future(channel)
1956
1957
1958 def insecure_channel(target, options=None, compression=None):
1959     """Creates an insecure Channel to a server.
1960
1961     The returned Channel is thread-safe.
1962
1963     Args:
1964       target: The server address
1965       options: An optional list of key-value pairs (:term:`channel_arguments`
1966         in gRPC Core runtime) to configure the channel.
1967       compression: An optional value indicating the compression method to be
1968         used over the lifetime of the channel. This is an EXPERIMENTAL option.
1969
1970     Returns:
1971       A Channel.
1972     """
1973     from grpc import _channel  # pylint: disable=cyclic-import
1974     return _channel.Channel(target, () if options is None else options, None,
1975                             compression)
1976
1977
1978 def secure_channel(target, credentials, options=None, compression=None):
1979     """Creates a secure Channel to a server.
1980
1981     The returned Channel is thread-safe.
1982
1983     Args:
1984       target: The server address.
1985       credentials: A ChannelCredentials instance.
1986       options: An optional list of key-value pairs (:term:`channel_arguments`
1987         in gRPC Core runtime) to configure the channel.
1988       compression: An optional value indicating the compression method to be
1989         used over the lifetime of the channel. This is an EXPERIMENTAL option.
1990
1991     Returns:
1992       A Channel.
1993     """
1994     from grpc import _channel  # pylint: disable=cyclic-import
1995     from grpc.experimental import _insecure_channel_credentials
1996     if credentials._credentials is _insecure_channel_credentials:
1997         raise ValueError(
1998             "secure_channel cannot be called with insecure credentials." +
1999             " Call insecure_channel instead.")
2000     return _channel.Channel(target, () if options is None else options,
2001                             credentials._credentials, compression)
2002
2003
2004 def intercept_channel(channel, *interceptors):
2005     """Intercepts a channel through a set of interceptors.
2006
2007     Args:
2008       channel: A Channel.
2009       interceptors: Zero or more objects of type
2010         UnaryUnaryClientInterceptor,
2011         UnaryStreamClientInterceptor,
2012         StreamUnaryClientInterceptor, or
2013         StreamStreamClientInterceptor.
2014         Interceptors are given control in the order they are listed.
2015
2016     Returns:
2017       A Channel that intercepts each invocation via the provided interceptors.
2018
2019     Raises:
2020       TypeError: If interceptor does not derive from any of
2021         UnaryUnaryClientInterceptor,
2022         UnaryStreamClientInterceptor,
2023         StreamUnaryClientInterceptor, or
2024         StreamStreamClientInterceptor.
2025     """
2026     from grpc import _interceptor  # pylint: disable=cyclic-import
2027     return _interceptor.intercept_channel(channel, *interceptors)
2028
2029
2030 def server(thread_pool,
2031            handlers=None,
2032            interceptors=None,
2033            options=None,
2034            maximum_concurrent_rpcs=None,
2035            compression=None,
2036            xds=False):
2037     """Creates a Server with which RPCs can be serviced.
2038
2039     Args:
2040       thread_pool: A futures.ThreadPoolExecutor to be used by the Server
2041         to execute RPC handlers.
2042       handlers: An optional list of GenericRpcHandlers used for executing RPCs.
2043         More handlers may be added by calling add_generic_rpc_handlers any time
2044         before the server is started.
2045       interceptors: An optional list of ServerInterceptor objects that observe
2046         and optionally manipulate the incoming RPCs before handing them over to
2047         handlers. The interceptors are given control in the order they are
2048         specified. This is an EXPERIMENTAL API.
2049       options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
2050         to configure the channel.
2051       maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
2052         will service before returning RESOURCE_EXHAUSTED status, or None to
2053         indicate no limit.
2054       compression: An element of grpc.compression, e.g.
2055         grpc.compression.Gzip. This compression algorithm will be used for the
2056         lifetime of the server unless overridden. This is an EXPERIMENTAL option.
2057       xds: If set to true, retrieves server configuration via xDS. This is an
2058         EXPERIMENTAL option.
2059
2060     Returns:
2061       A Server object.
2062     """
2063     from grpc import _server  # pylint: disable=cyclic-import
2064     return _server.create_server(thread_pool,
2065                                  () if handlers is None else handlers,
2066                                  () if interceptors is None else interceptors,
2067                                  () if options is None else options,
2068                                  maximum_concurrent_rpcs, compression, xds)
2069
2070
2071 @contextlib.contextmanager
2072 def _create_servicer_context(rpc_event, state, request_deserializer):
2073     from grpc import _server  # pylint: disable=cyclic-import
2074     context = _server._Context(rpc_event, state, request_deserializer)
2075     yield context
2076     context._finalize_state()  # pylint: disable=protected-access
2077
2078
2079 @enum.unique
2080 class Compression(enum.IntEnum):
2081     """Indicates the compression method to be used for an RPC.
2082
2083        This enumeration is part of an EXPERIMENTAL API.
2084
2085        Attributes:
2086         NoCompression: Do not use compression algorithm.
2087         Deflate: Use "Deflate" compression algorithm.
2088         Gzip: Use "Gzip" compression algorithm.
2089     """
2090     NoCompression = _compression.NoCompression
2091     Deflate = _compression.Deflate
2092     Gzip = _compression.Gzip
2093
2094
2095 from grpc._runtime_protos import protos, services, protos_and_services  # pylint: disable=wrong-import-position
2096
2097 ###################################  __all__  #################################
2098
2099 __all__ = (
2100     'FutureTimeoutError',
2101     'FutureCancelledError',
2102     'Future',
2103     'ChannelConnectivity',
2104     'StatusCode',
2105     'Status',
2106     'RpcError',
2107     'RpcContext',
2108     'Call',
2109     'ChannelCredentials',
2110     'CallCredentials',
2111     'AuthMetadataContext',
2112     'AuthMetadataPluginCallback',
2113     'AuthMetadataPlugin',
2114     'Compression',
2115     'ClientCallDetails',
2116     'ServerCertificateConfiguration',
2117     'ServerCredentials',
2118     'LocalConnectionType',
2119     'UnaryUnaryMultiCallable',
2120     'UnaryStreamMultiCallable',
2121     'StreamUnaryMultiCallable',
2122     'StreamStreamMultiCallable',
2123     'UnaryUnaryClientInterceptor',
2124     'UnaryStreamClientInterceptor',
2125     'StreamUnaryClientInterceptor',
2126     'StreamStreamClientInterceptor',
2127     'Channel',
2128     'ServicerContext',
2129     'RpcMethodHandler',
2130     'HandlerCallDetails',
2131     'GenericRpcHandler',
2132     'ServiceRpcHandler',
2133     'Server',
2134     'ServerInterceptor',
2135     'unary_unary_rpc_method_handler',
2136     'unary_stream_rpc_method_handler',
2137     'stream_unary_rpc_method_handler',
2138     'stream_stream_rpc_method_handler',
2139     'method_handlers_generic_handler',
2140     'ssl_channel_credentials',
2141     'metadata_call_credentials',
2142     'access_token_call_credentials',
2143     'composite_call_credentials',
2144     'composite_channel_credentials',
2145     'local_channel_credentials',
2146     'local_server_credentials',
2147     'alts_channel_credentials',
2148     'alts_server_credentials',
2149     'ssl_server_credentials',
2150     'ssl_server_certificate_configuration',
2151     'dynamic_ssl_server_credentials',
2152     'channel_ready_future',
2153     'insecure_channel',
2154     'secure_channel',
2155     'intercept_channel',
2156     'server',
2157     'protos',
2158     'services',
2159     'protos_and_services',
2160     'xds_channel_credentials',
2161     'xds_server_credentials',
2162     'insecure_server_credentials',
2163 )
2164
2165 ############################### Extension Shims ################################
2166
2167 # Here to maintain backwards compatibility; avoid using these in new code!
2168 try:
2169     import grpc_tools
2170     sys.modules.update({'grpc.tools': grpc_tools})
2171 except ImportError:
2172     pass
2173 try:
2174     import grpc_health
2175     sys.modules.update({'grpc.health': grpc_health})
2176 except ImportError:
2177     pass
2178 try:
2179     import grpc_reflection
2180     sys.modules.update({'grpc.reflection': grpc_reflection})
2181 except ImportError:
2182     pass
2183
2184 # Prevents import order issue in the case of renamed path.
2185 if sys.version_info >= (3, 6) and __name__ == "grpc":
2186     from grpc import aio  # pylint: disable=ungrouped-imports
2187     sys.modules.update({'grpc.aio': aio})