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