Imported Upstream version 1.20.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
25 logging.getLogger(__name__).addHandler(logging.NullHandler())
26
27 try:
28     from grpc._grpcio_metadata import __version__
29 except ImportError:
30     __version__ = "dev0"
31
32 ############################## Future Interface  ###############################
33
34
35 class FutureTimeoutError(Exception):
36     """Indicates that a method call on a Future timed out."""
37
38
39 class FutureCancelledError(Exception):
40     """Indicates that the computation underlying a Future was cancelled."""
41
42
43 class Future(six.with_metaclass(abc.ABCMeta)):
44     """A representation of a computation in another control flow.
45
46     Computations represented by a Future may be yet to be begun,
47     may be ongoing, or may have already completed.
48     """
49
50     @abc.abstractmethod
51     def cancel(self):
52         """Attempts to cancel the computation.
53
54         This method does not block.
55
56         Returns:
57             bool:
58             Returns True if the computation was canceled.
59
60             Returns False under all other circumstances, for example:
61
62             1. computation has begun and could not be canceled.
63             2. computation has finished
64             3. computation is scheduled for execution and it is impossible
65                 to determine its state without blocking.
66         """
67         raise NotImplementedError()
68
69     @abc.abstractmethod
70     def cancelled(self):
71         """Describes whether the computation was cancelled.
72
73         This method does not block.
74
75         Returns:
76             bool:
77             Returns True if the computation was cancelled before its result became
78             available.
79
80             Returns False under all other circumstances, for example:
81
82             1. computation was not cancelled.
83             2. computation's result is available.
84         """
85         raise NotImplementedError()
86
87     @abc.abstractmethod
88     def running(self):
89         """Describes whether the computation is taking place.
90
91         This method does not block.
92
93         Returns:
94             Returns True if the computation is scheduled for execution or
95             currently executing.
96
97             Returns False if the computation already executed or was cancelled.
98         """
99         raise NotImplementedError()
100
101     @abc.abstractmethod
102     def done(self):
103         """Describes whether the computation has taken place.
104
105         This method does not block.
106
107         Returns:
108             bool:
109             Returns True if the computation already executed or was cancelled.
110             Returns False if the computation is scheduled for execution or
111             currently executing.
112             This is exactly opposite of the running() method's result.
113         """
114         raise NotImplementedError()
115
116     @abc.abstractmethod
117     def result(self, timeout=None):
118         """Returns the result of the computation or raises its exception.
119
120         This method may return immediately or may block.
121
122         Args:
123           timeout: The length of time in seconds to wait for the computation to
124             finish or be cancelled. If None, the call will block until the
125             computations's termination.
126
127         Returns:
128           The return value of the computation.
129
130         Raises:
131           FutureTimeoutError: If a timeout value is passed and the computation
132             does not terminate within the allotted time.
133           FutureCancelledError: If the computation was cancelled.
134           Exception: If the computation raised an exception, this call will
135             raise the same exception.
136         """
137         raise NotImplementedError()
138
139     @abc.abstractmethod
140     def exception(self, timeout=None):
141         """Return the exception raised by the computation.
142
143         This method may return immediately or may block.
144
145         Args:
146           timeout: The length of time in seconds to wait for the computation to
147             terminate or be cancelled. If None, the call will block until the
148             computations's termination.
149
150         Returns:
151             The exception raised by the computation, or None if the computation
152             did not raise an exception.
153
154         Raises:
155           FutureTimeoutError: If a timeout value is passed and the computation
156             does not terminate within the allotted time.
157           FutureCancelledError: If the computation was cancelled.
158         """
159         raise NotImplementedError()
160
161     @abc.abstractmethod
162     def traceback(self, timeout=None):
163         """Access the traceback of the exception raised by the computation.
164
165         This method may return immediately or may block.
166
167         Args:
168           timeout: The length of time in seconds to wait for the computation
169             to terminate or be cancelled. If None, the call will block until
170             the computation's termination.
171
172         Returns:
173             The traceback of the exception raised by the computation, or None
174             if the computation did not raise an exception.
175
176         Raises:
177           FutureTimeoutError: If a timeout value is passed and the computation
178             does not terminate within the allotted time.
179           FutureCancelledError: If the computation was cancelled.
180         """
181         raise NotImplementedError()
182
183     @abc.abstractmethod
184     def add_done_callback(self, fn):
185         """Adds a function to be called at completion of the computation.
186
187         The callback will be passed this Future object describing the outcome
188         of the computation.  Callbacks will be invoked after the future is
189         terimated, whether successfully or not.
190
191         If the computation has already completed, the callback will be called
192         immediately.
193
194         Args:
195           fn: A callable taking this Future object as its single parameter.
196         """
197         raise NotImplementedError()
198
199
200 ################################  gRPC Enums  ##################################
201
202
203 @enum.unique
204 class ChannelConnectivity(enum.Enum):
205     """Mirrors grpc_connectivity_state in the gRPC Core.
206
207     Attributes:
208       IDLE: The channel is idle.
209       CONNECTING: The channel is connecting.
210       READY: The channel is ready to conduct RPCs.
211       TRANSIENT_FAILURE: The channel has seen a failure from which it expects
212         to recover.
213       SHUTDOWN: The channel has seen a failure from which it cannot recover.
214     """
215     IDLE = (_cygrpc.ConnectivityState.idle, 'idle')
216     CONNECTING = (_cygrpc.ConnectivityState.connecting, 'connecting')
217     READY = (_cygrpc.ConnectivityState.ready, 'ready')
218     TRANSIENT_FAILURE = (_cygrpc.ConnectivityState.transient_failure,
219                          'transient failure')
220     SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, 'shutdown')
221
222
223 @enum.unique
224 class StatusCode(enum.Enum):
225     """Mirrors grpc_status_code in the gRPC Core.
226
227     Attributes:
228       OK: Not an error; returned on success
229       CANCELLED: The operation was cancelled (typically by the caller).
230       UNKNOWN: Unknown error.
231       INVALID_ARGUMENT: Client specified an invalid argument.
232       DEADLINE_EXCEEDED: Deadline expired before operation could complete.
233       NOT_FOUND: Some requested entity (e.g., file or directory) was not found.
234       ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory)
235         already exists.
236       PERMISSION_DENIED: The caller does not have permission to execute the specified
237         operation.
238       UNAUTHENTICATED: The request does not have valid authentication credentials for the
239         operation.
240       RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or
241         perhaps the entire file system is out of space.
242       FAILED_PRECONDITION: Operation was rejected because the system is not in a state
243         required for the operation's execution.
244       ABORTED: The operation was aborted, typically due to a concurrency issue
245         like sequencer check failures, transaction aborts, etc.
246       UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service.
247       INTERNAL: Internal errors.  Means some invariants expected by underlying
248         system has been broken.
249       UNAVAILABLE: The service is currently unavailable.
250       DATA_LOSS: Unrecoverable data loss or corruption.
251     """
252     OK = (_cygrpc.StatusCode.ok, 'ok')
253     CANCELLED = (_cygrpc.StatusCode.cancelled, 'cancelled')
254     UNKNOWN = (_cygrpc.StatusCode.unknown, 'unknown')
255     INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, 'invalid argument')
256     DEADLINE_EXCEEDED = (_cygrpc.StatusCode.deadline_exceeded,
257                          'deadline exceeded')
258     NOT_FOUND = (_cygrpc.StatusCode.not_found, 'not found')
259     ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, 'already exists')
260     PERMISSION_DENIED = (_cygrpc.StatusCode.permission_denied,
261                          'permission denied')
262     RESOURCE_EXHAUSTED = (_cygrpc.StatusCode.resource_exhausted,
263                           'resource exhausted')
264     FAILED_PRECONDITION = (_cygrpc.StatusCode.failed_precondition,
265                            'failed precondition')
266     ABORTED = (_cygrpc.StatusCode.aborted, 'aborted')
267     OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, 'out of range')
268     UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, 'unimplemented')
269     INTERNAL = (_cygrpc.StatusCode.internal, 'internal')
270     UNAVAILABLE = (_cygrpc.StatusCode.unavailable, 'unavailable')
271     DATA_LOSS = (_cygrpc.StatusCode.data_loss, 'data loss')
272     UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, 'unauthenticated')
273
274
275 #############################  gRPC Status  ################################
276
277
278 class Status(six.with_metaclass(abc.ABCMeta)):
279     """Describes the status of an RPC.
280
281     This is an EXPERIMENTAL API.
282
283     Attributes:
284       code: A StatusCode object to be sent to the client.
285       details: A UTF-8-encodable string to be sent to the client upon
286         termination of the RPC.
287       trailing_metadata: The trailing :term:`metadata` in the RPC.
288     """
289
290
291 #############################  gRPC Exceptions  ################################
292
293
294 class RpcError(Exception):
295     """Raised by the gRPC library to indicate non-OK-status RPC termination."""
296
297
298 ##############################  Shared Context  ################################
299
300
301 class RpcContext(six.with_metaclass(abc.ABCMeta)):
302     """Provides RPC-related information and action."""
303
304     @abc.abstractmethod
305     def is_active(self):
306         """Describes whether the RPC is active or has terminated.
307
308         Returns:
309           bool:
310           True if RPC is active, False otherwise.
311         """
312         raise NotImplementedError()
313
314     @abc.abstractmethod
315     def time_remaining(self):
316         """Describes the length of allowed time remaining for the RPC.
317
318         Returns:
319           A nonnegative float indicating the length of allowed time in seconds
320           remaining for the RPC to complete before it is considered to have
321           timed out, or None if no deadline was specified for the RPC.
322         """
323         raise NotImplementedError()
324
325     @abc.abstractmethod
326     def cancel(self):
327         """Cancels the RPC.
328
329         Idempotent and has no effect if the RPC has already terminated.
330         """
331         raise NotImplementedError()
332
333     @abc.abstractmethod
334     def add_callback(self, callback):
335         """Registers a callback to be called on RPC termination.
336
337         Args:
338           callback: A no-parameter callable to be called on RPC termination.
339
340         Returns:
341           bool:
342             True if the callback was added and will be called later; False if
343             the callback was not added and will not be called (because the RPC
344             already terminated or some other reason).
345         """
346         raise NotImplementedError()
347
348
349 #########################  Invocation-Side Context  ############################
350
351
352 class Call(six.with_metaclass(abc.ABCMeta, RpcContext)):
353     """Invocation-side utility object for an RPC."""
354
355     @abc.abstractmethod
356     def initial_metadata(self):
357         """Accesses the initial metadata sent by the server.
358
359         This method blocks until the value is available.
360
361         Returns:
362           The initial :term:`metadata`.
363         """
364         raise NotImplementedError()
365
366     @abc.abstractmethod
367     def trailing_metadata(self):
368         """Accesses the trailing metadata sent by the server.
369
370         This method blocks until the value is available.
371
372         Returns:
373           The trailing :term:`metadata`.
374         """
375         raise NotImplementedError()
376
377     @abc.abstractmethod
378     def code(self):
379         """Accesses the status code sent by the server.
380
381         This method blocks until the value is available.
382
383         Returns:
384           The StatusCode value for the RPC.
385         """
386         raise NotImplementedError()
387
388     @abc.abstractmethod
389     def details(self):
390         """Accesses the details sent by the server.
391
392         This method blocks until the value is available.
393
394         Returns:
395           The details string of the RPC.
396         """
397         raise NotImplementedError()
398
399
400 ##############  Invocation-Side Interceptor Interfaces & Classes  ##############
401
402
403 class ClientCallDetails(six.with_metaclass(abc.ABCMeta)):
404     """Describes an RPC to be invoked.
405
406     This is an EXPERIMENTAL API.
407
408     Attributes:
409       method: The method name of the RPC.
410       timeout: An optional duration of time in seconds to allow for the RPC.
411       metadata: Optional :term:`metadata` to be transmitted to
412         the service-side of the RPC.
413       credentials: An optional CallCredentials for the RPC.
414       wait_for_ready: This is an EXPERIMENTAL argument. An optional flag t
415         enable wait for ready mechanism.
416     """
417
418
419 class UnaryUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
420     """Affords intercepting unary-unary invocations.
421
422     This is an EXPERIMENTAL API.
423     """
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     This is an EXPERIMENTAL API.
460     """
461
462     @abc.abstractmethod
463     def intercept_unary_stream(self, continuation, client_call_details,
464                                request):
465         """Intercepts a unary-stream invocation.
466
467         Args:
468           continuation: A function that proceeds with the invocation by
469             executing the next interceptor in chain or invoking the
470             actual RPC on the underlying Channel. It is the interceptor's
471             responsibility to call it if it decides to move the RPC forward.
472             The interceptor can use
473             `response_iterator = continuation(client_call_details, request)`
474             to continue with the RPC. `continuation` returns an object that is
475             both a Call for the RPC and an iterator for response values.
476             Drawing response values from the returned Call-iterator may
477             raise RpcError indicating termination of the RPC with non-OK
478             status.
479           client_call_details: A ClientCallDetails object describing the
480             outgoing RPC.
481           request: The request value for the RPC.
482
483         Returns:
484             An object that is both a Call for the RPC and an iterator of
485             response values. Drawing response values from the returned
486             Call-iterator may raise RpcError indicating termination of
487             the RPC with non-OK status.
488         """
489         raise NotImplementedError()
490
491
492 class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
493     """Affords intercepting stream-unary invocations.
494
495     This is an EXPERIMENTAL API.
496     """
497
498     @abc.abstractmethod
499     def intercept_stream_unary(self, continuation, client_call_details,
500                                request_iterator):
501         """Intercepts a stream-unary invocation asynchronously.
502
503         Args:
504           continuation: A function that proceeds with the invocation by
505             executing the next interceptor in chain or invoking the
506             actual RPC on the underlying Channel. It is the interceptor's
507             responsibility to call it if it decides to move the RPC forward.
508             The interceptor can use
509             `response_future = continuation(client_call_details, request_iterator)`
510             to continue with the RPC. `continuation` returns an object that is
511             both a Call for the RPC and a Future. In the event of RPC completion,
512             the return Call-Future's result value will be the response message
513             of the RPC. Should the event terminate with non-OK status, the
514             returned Call-Future's exception value will be an RpcError.
515           client_call_details: A ClientCallDetails object describing the
516             outgoing RPC.
517           request_iterator: An iterator that yields request values for the RPC.
518
519         Returns:
520           An object that is both a Call for the RPC and a Future.
521           In the event of RPC completion, the return Call-Future's
522           result value will be the response message of the RPC.
523           Should the event terminate with non-OK status, the returned
524           Call-Future's exception value will be an RpcError.
525         """
526         raise NotImplementedError()
527
528
529 class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
530     """Affords intercepting stream-stream invocations.
531
532     This is an EXPERIMENTAL API.
533     """
534
535     @abc.abstractmethod
536     def intercept_stream_stream(self, continuation, client_call_details,
537                                 request_iterator):
538         """Intercepts a stream-stream invocation.
539
540         Args:
541           continuation: A function that proceeds with the invocation by
542             executing the next interceptor in chain or invoking the
543             actual RPC on the underlying Channel. It is the interceptor's
544             responsibility to call it if it decides to move the RPC forward.
545             The interceptor can use
546             `response_iterator = continuation(client_call_details, request_iterator)`
547             to continue with the RPC. `continuation` returns an object that is
548             both a Call for the RPC and an iterator for response values.
549             Drawing response values from the returned Call-iterator may
550             raise RpcError indicating termination of the RPC with non-OK
551             status.
552           client_call_details: A ClientCallDetails object describing the
553             outgoing RPC.
554           request_iterator: An iterator that yields request values for the RPC.
555
556         Returns:
557           An object that is both a Call for the RPC and an iterator of
558           response values. Drawing response values from the returned
559           Call-iterator may raise RpcError indicating termination of
560           the RPC with non-OK status.
561         """
562         raise NotImplementedError()
563
564
565 ############  Authentication & Authorization Interfaces & Classes  #############
566
567
568 class ChannelCredentials(object):
569     """An encapsulation of the data required to create a secure Channel.
570
571     This class has no supported interface - it exists to define the type of its
572     instances and its instances exist to be passed to other functions. For
573     example, ssl_channel_credentials returns an instance of this class and
574     secure_channel requires an instance of this class.
575     """
576
577     def __init__(self, credentials):
578         self._credentials = credentials
579
580
581 class CallCredentials(object):
582     """An encapsulation of the data required to assert an identity over a call.
583
584     A CallCredentials may be composed with ChannelCredentials to always assert
585     identity for every call over that Channel.
586
587     This class has no supported interface - it exists to define the type of its
588     instances and its instances exist to be passed to other functions.
589     """
590
591     def __init__(self, credentials):
592         self._credentials = credentials
593
594
595 class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
596     """Provides information to call credentials metadata plugins.
597
598     Attributes:
599       service_url: A string URL of the service being called into.
600       method_name: A string of the fully qualified method name being called.
601     """
602
603
604 class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)):
605     """Callback object received by a metadata plugin."""
606
607     def __call__(self, metadata, error):
608         """Passes to the gRPC runtime authentication metadata for an RPC.
609
610         Args:
611           metadata: The :term:`metadata` used to construct the CallCredentials.
612           error: An Exception to indicate error or None to indicate success.
613         """
614         raise NotImplementedError()
615
616
617 class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
618     """A specification for custom authentication."""
619
620     def __call__(self, context, callback):
621         """Implements authentication by passing metadata to a callback.
622
623         Implementations of this method must not block.
624
625         Args:
626           context: An AuthMetadataContext providing information on the RPC that
627             the plugin is being called to authenticate.
628           callback: An AuthMetadataPluginCallback to be invoked either
629             synchronously or asynchronously.
630         """
631         raise NotImplementedError()
632
633
634 class ServerCredentials(object):
635     """An encapsulation of the data required to open a secure port on a Server.
636
637     This class has no supported interface - it exists to define the type of its
638     instances and its instances exist to be passed to other functions.
639     """
640
641     def __init__(self, credentials):
642         self._credentials = credentials
643
644
645 class ServerCertificateConfiguration(object):
646     """A certificate configuration for use with an SSL-enabled Server.
647
648     Instances of this class can be returned in the certificate configuration
649     fetching callback.
650
651     This class has no supported interface -- it exists to define the
652     type of its instances and its instances exist to be passed to
653     other functions.
654     """
655
656     def __init__(self, certificate_configuration):
657         self._certificate_configuration = certificate_configuration
658
659
660 ########################  Multi-Callable Interfaces  ###########################
661
662
663 class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
664     """Affords invoking a unary-unary RPC from client-side."""
665
666     @abc.abstractmethod
667     def __call__(self,
668                  request,
669                  timeout=None,
670                  metadata=None,
671                  credentials=None,
672                  wait_for_ready=None):
673         """Synchronously invokes the underlying RPC.
674
675         Args:
676           request: The request value for the RPC.
677           timeout: An optional duration of time in seconds to allow
678             for the RPC.
679           metadata: Optional :term:`metadata` to be transmitted to the
680             service-side of the RPC.
681           credentials: An optional CallCredentials for the RPC.
682           wait_for_ready: This is an EXPERIMENTAL argument. An optional
683             flag to enable wait for ready mechanism
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         """Synchronously invokes the underlying RPC.
703
704         Args:
705           request: The request value for the RPC.
706           timeout: An optional durating of time in seconds to allow for
707             the RPC.
708           metadata: Optional :term:`metadata` to be transmitted to the
709             service-side of the RPC.
710           credentials: An optional CallCredentials for the RPC.
711           wait_for_ready: This is an EXPERIMENTAL argument. An optional
712             flag to enable wait for ready mechanism
713
714         Returns:
715           The response value for the RPC and a Call value for the RPC.
716
717         Raises:
718           RpcError: Indicating that the RPC terminated with non-OK status. The
719             raised RpcError will also be a Call for the RPC affording the RPC's
720             metadata, status code, and details.
721         """
722         raise NotImplementedError()
723
724     @abc.abstractmethod
725     def future(self,
726                request,
727                timeout=None,
728                metadata=None,
729                credentials=None,
730                wait_for_ready=None):
731         """Asynchronously invokes the underlying RPC.
732
733         Args:
734           request: The request value for the RPC.
735           timeout: An optional duration of time in seconds to allow for
736             the RPC.
737           metadata: Optional :term:`metadata` to be transmitted to the
738             service-side of the RPC.
739           credentials: An optional CallCredentials for the RPC.
740           wait_for_ready: This is an EXPERIMENTAL argument. An optional
741             flag to enable wait for ready mechanism
742
743         Returns:
744             An object that is both a Call for the RPC and a Future.
745             In the event of RPC completion, the return Call-Future's result
746             value will be the response message of the RPC.
747             Should the event terminate with non-OK status,
748             the returned Call-Future's exception value will be an RpcError.
749         """
750         raise NotImplementedError()
751
752
753 class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
754     """Affords invoking a unary-stream RPC from client-side."""
755
756     @abc.abstractmethod
757     def __call__(self,
758                  request,
759                  timeout=None,
760                  metadata=None,
761                  credentials=None,
762                  wait_for_ready=None):
763         """Invokes the underlying RPC.
764
765         Args:
766           request: The request value for the RPC.
767           timeout: An optional duration of time in seconds to allow for
768             the RPC. If None, the timeout is considered infinite.
769           metadata: An optional :term:`metadata` to be transmitted to the
770             service-side of the RPC.
771           credentials: An optional CallCredentials for the RPC.
772           wait_for_ready: This is an EXPERIMENTAL argument. An optional
773             flag to enable wait for ready mechanism
774
775         Returns:
776             An object that is both a Call for the RPC and an iterator of
777             response values. Drawing response values from the returned
778             Call-iterator may raise RpcError indicating termination of the
779             RPC with non-OK status.
780         """
781         raise NotImplementedError()
782
783
784 class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
785     """Affords invoking a stream-unary RPC from client-side."""
786
787     @abc.abstractmethod
788     def __call__(self,
789                  request_iterator,
790                  timeout=None,
791                  metadata=None,
792                  credentials=None,
793                  wait_for_ready=None):
794         """Synchronously invokes the underlying RPC.
795
796         Args:
797           request_iterator: An iterator that yields request values for
798             the RPC.
799           timeout: An optional duration of time in seconds to allow for
800             the RPC. If None, the timeout is considered infinite.
801           metadata: Optional :term:`metadata` to be transmitted to the
802             service-side of the RPC.
803           credentials: An optional CallCredentials for the RPC.
804           wait_for_ready: This is an EXPERIMENTAL argument. An optional
805             flag to enable wait for ready mechanism
806
807         Returns:
808           The response value for the RPC.
809
810         Raises:
811           RpcError: Indicating that the RPC terminated with non-OK status. The
812             raised RpcError will also implement grpc.Call, affording methods
813             such as metadata, code, and details.
814         """
815         raise NotImplementedError()
816
817     @abc.abstractmethod
818     def with_call(self,
819                   request_iterator,
820                   timeout=None,
821                   metadata=None,
822                   credentials=None,
823                   wait_for_ready=None):
824         """Synchronously invokes the underlying RPC on the client.
825
826         Args:
827           request_iterator: An iterator that yields request values for
828             the RPC.
829           timeout: An optional duration of time in seconds to allow for
830             the RPC. If None, the timeout is considered infinite.
831           metadata: Optional :term:`metadata` to be transmitted to the
832             service-side of the RPC.
833           credentials: An optional CallCredentials for the RPC.
834           wait_for_ready: This is an EXPERIMENTAL argument. An optional
835             flag to enable wait for ready mechanism
836
837         Returns:
838           The response value for the RPC and a Call object for the RPC.
839
840         Raises:
841           RpcError: Indicating that the RPC terminated with non-OK status. The
842             raised RpcError will also be a Call for the RPC affording the RPC's
843             metadata, status code, and details.
844         """
845         raise NotImplementedError()
846
847     @abc.abstractmethod
848     def future(self,
849                request_iterator,
850                timeout=None,
851                metadata=None,
852                credentials=None,
853                wait_for_ready=None):
854         """Asynchronously invokes the underlying RPC on the client.
855
856         Args:
857           request_iterator: An iterator that yields request values for 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.
863           wait_for_ready: This is an EXPERIMENTAL argument. An optional
864             flag to enable wait for ready mechanism
865
866         Returns:
867             An object that is both a Call for the RPC and a Future.
868             In the event of RPC completion, the return Call-Future's result value
869             will be the response message of the RPC. Should the event terminate
870             with non-OK status, the returned Call-Future's exception value will
871             be an RpcError.
872         """
873         raise NotImplementedError()
874
875
876 class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
877     """Affords invoking a stream-stream RPC on client-side."""
878
879     @abc.abstractmethod
880     def __call__(self,
881                  request_iterator,
882                  timeout=None,
883                  metadata=None,
884                  credentials=None,
885                  wait_for_ready=None):
886         """Invokes the underlying RPC on the client.
887
888         Args:
889           request_iterator: An iterator that yields request values for the RPC.
890           timeout: An optional duration of time in seconds to allow for
891             the RPC. If not specified, the timeout is considered infinite.
892           metadata: Optional :term:`metadata` to be transmitted to the
893             service-side of the RPC.
894           credentials: An optional CallCredentials for the RPC.
895           wait_for_ready: This is an EXPERIMENTAL argument. An optional
896             flag to enable wait for ready mechanism
897
898         Returns:
899             An object that is both a Call for the RPC and an iterator of
900             response values. Drawing response values from the returned
901             Call-iterator may raise RpcError indicating termination of the
902             RPC with non-OK status.
903         """
904         raise NotImplementedError()
905
906
907 #############################  Channel Interface  ##############################
908
909
910 class Channel(six.with_metaclass(abc.ABCMeta)):
911     """Affords RPC invocation via generic methods on client-side.
912
913     Channel objects implement the Context Manager type, although they need not
914     support being entered and exited multiple times.
915     """
916
917     @abc.abstractmethod
918     def subscribe(self, callback, try_to_connect=False):
919         """Subscribe to this Channel's connectivity state machine.
920
921         A Channel may be in any of the states described by ChannelConnectivity.
922         This method allows application to monitor the state transitions.
923         The typical use case is to debug or gain better visibility into gRPC
924         runtime's state.
925
926         Args:
927           callback: A callable to be invoked with ChannelConnectivity argument.
928             ChannelConnectivity describes current state of the channel.
929             The callable will be invoked immediately upon subscription
930             and again for every change to ChannelConnectivity until it
931             is unsubscribed or this Channel object goes out of scope.
932           try_to_connect: A boolean indicating whether or not this Channel
933             should attempt to connect immediately. If set to False, gRPC
934             runtime decides when to connect.
935         """
936         raise NotImplementedError()
937
938     @abc.abstractmethod
939     def unsubscribe(self, callback):
940         """Unsubscribes a subscribed callback from this Channel's connectivity.
941
942         Args:
943           callback: A callable previously registered with this Channel from
944           having been passed to its "subscribe" method.
945         """
946         raise NotImplementedError()
947
948     @abc.abstractmethod
949     def unary_unary(self,
950                     method,
951                     request_serializer=None,
952                     response_deserializer=None):
953         """Creates a UnaryUnaryMultiCallable for a unary-unary method.
954
955         Args:
956           method: The name of the RPC method.
957           request_serializer: Optional behaviour for serializing the request
958             message. Request goes unserialized in case None is passed.
959           response_deserializer: Optional behaviour for deserializing the
960             response message. Response goes undeserialized in case None
961             is passed.
962
963         Returns:
964           A UnaryUnaryMultiCallable value for the named unary-unary method.
965         """
966         raise NotImplementedError()
967
968     @abc.abstractmethod
969     def unary_stream(self,
970                      method,
971                      request_serializer=None,
972                      response_deserializer=None):
973         """Creates a UnaryStreamMultiCallable for a unary-stream method.
974
975         Args:
976           method: The name of the RPC method.
977           request_serializer: Optional behaviour for serializing the request
978             message. Request goes unserialized in case None is passed.
979           response_deserializer: Optional behaviour for deserializing the
980             response message. Response goes undeserialized in case None is
981             passed.
982
983         Returns:
984           A UnaryStreamMultiCallable value for the name unary-stream method.
985         """
986         raise NotImplementedError()
987
988     @abc.abstractmethod
989     def stream_unary(self,
990                      method,
991                      request_serializer=None,
992                      response_deserializer=None):
993         """Creates a StreamUnaryMultiCallable for a stream-unary method.
994
995         Args:
996           method: The name of the RPC method.
997           request_serializer: Optional behaviour for serializing the request
998             message. Request goes unserialized in case None is passed.
999           response_deserializer: Optional behaviour for deserializing the
1000             response message. Response goes undeserialized in case None is
1001             passed.
1002
1003         Returns:
1004           A StreamUnaryMultiCallable value for the named stream-unary method.
1005         """
1006         raise NotImplementedError()
1007
1008     @abc.abstractmethod
1009     def stream_stream(self,
1010                       method,
1011                       request_serializer=None,
1012                       response_deserializer=None):
1013         """Creates a StreamStreamMultiCallable for a stream-stream method.
1014
1015         Args:
1016           method: The name of the RPC method.
1017           request_serializer: Optional behaviour for serializing the request
1018             message. Request goes unserialized in case None is passed.
1019           response_deserializer: Optional behaviour for deserializing the
1020             response message. Response goes undeserialized in case None
1021             is passed.
1022
1023         Returns:
1024           A StreamStreamMultiCallable value for the named stream-stream method.
1025         """
1026         raise NotImplementedError()
1027
1028     @abc.abstractmethod
1029     def close(self):
1030         """Closes this Channel and releases all resources held by it.
1031
1032         Closing the Channel will immediately terminate all RPCs active with the
1033         Channel and it is not valid to invoke new RPCs with the Channel.
1034
1035         This method is idempotent.
1036         """
1037         raise NotImplementedError()
1038
1039
1040 ##########################  Service-Side Context  ##############################
1041
1042
1043 class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
1044     """A context object passed to method implementations."""
1045
1046     @abc.abstractmethod
1047     def invocation_metadata(self):
1048         """Accesses the metadata from the sent by the client.
1049
1050         Returns:
1051           The invocation :term:`metadata`.
1052         """
1053         raise NotImplementedError()
1054
1055     @abc.abstractmethod
1056     def peer(self):
1057         """Identifies the peer that invoked the RPC being serviced.
1058
1059         Returns:
1060           A string identifying the peer that invoked the RPC being serviced.
1061           The string format is determined by gRPC runtime.
1062         """
1063         raise NotImplementedError()
1064
1065     @abc.abstractmethod
1066     def peer_identities(self):
1067         """Gets one or more peer identity(s).
1068
1069         Equivalent to
1070         servicer_context.auth_context().get(servicer_context.peer_identity_key())
1071
1072         Returns:
1073           An iterable of the identities, or None if the call is not
1074           authenticated. Each identity is returned as a raw bytes type.
1075         """
1076         raise NotImplementedError()
1077
1078     @abc.abstractmethod
1079     def peer_identity_key(self):
1080         """The auth property used to identify the peer.
1081
1082         For example, "x509_common_name" or "x509_subject_alternative_name" are
1083         used to identify an SSL peer.
1084
1085         Returns:
1086           The auth property (string) that indicates the
1087           peer identity, or None if the call is not authenticated.
1088         """
1089         raise NotImplementedError()
1090
1091     @abc.abstractmethod
1092     def auth_context(self):
1093         """Gets the auth context for the call.
1094
1095         Returns:
1096           A map of strings to an iterable of bytes for each auth property.
1097         """
1098         raise NotImplementedError()
1099
1100     @abc.abstractmethod
1101     def send_initial_metadata(self, initial_metadata):
1102         """Sends the initial metadata value to the client.
1103
1104         This method need not be called by implementations if they have no
1105         metadata to add to what the gRPC runtime will transmit.
1106
1107         Args:
1108           initial_metadata: The initial :term:`metadata`.
1109         """
1110         raise NotImplementedError()
1111
1112     @abc.abstractmethod
1113     def set_trailing_metadata(self, trailing_metadata):
1114         """Sends the trailing metadata for the RPC.
1115
1116         This method need not be called by implementations if they have no
1117         metadata to add to what the gRPC runtime will transmit.
1118
1119         Args:
1120           trailing_metadata: The trailing :term:`metadata`.
1121         """
1122         raise NotImplementedError()
1123
1124     @abc.abstractmethod
1125     def abort(self, code, details):
1126         """Raises an exception to terminate the RPC with a non-OK status.
1127
1128         The code and details passed as arguments will supercede any existing
1129         ones.
1130
1131         Args:
1132           code: A StatusCode object to be sent to the client.
1133             It must not be StatusCode.OK.
1134           details: A UTF-8-encodable string to be sent to the client upon
1135             termination of the RPC.
1136
1137         Raises:
1138           Exception: An exception is always raised to signal the abortion the
1139             RPC to the gRPC runtime.
1140         """
1141         raise NotImplementedError()
1142
1143     @abc.abstractmethod
1144     def abort_with_status(self, status):
1145         """Raises an exception to terminate the RPC with a non-OK status.
1146
1147         The status passed as argument will supercede any existing status code,
1148         status message and trailing metadata.
1149
1150         This is an EXPERIMENTAL API.
1151
1152         Args:
1153           status: A grpc.Status object. The status code in it must not be
1154             StatusCode.OK.
1155
1156         Raises:
1157           Exception: An exception is always raised to signal the abortion the
1158             RPC to the gRPC runtime.
1159         """
1160         raise NotImplementedError()
1161
1162     @abc.abstractmethod
1163     def set_code(self, code):
1164         """Sets the value to be used as status code upon RPC completion.
1165
1166         This method need not be called by method implementations if they wish
1167         the gRPC runtime to determine the status code of the RPC.
1168
1169         Args:
1170           code: A StatusCode object to be sent to the client.
1171         """
1172         raise NotImplementedError()
1173
1174     @abc.abstractmethod
1175     def set_details(self, details):
1176         """Sets the value to be used as detail string upon RPC completion.
1177
1178         This method need not be called by method implementations if they have
1179         no details to transmit.
1180
1181         Args:
1182           details: A UTF-8-encodable string to be sent to the client upon
1183             termination of the RPC.
1184         """
1185         raise NotImplementedError()
1186
1187
1188 #####################  Service-Side Handler Interfaces  ########################
1189
1190
1191 class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
1192     """An implementation of a single RPC method.
1193
1194     Attributes:
1195       request_streaming: Whether the RPC supports exactly one request message
1196         or any arbitrary number of request messages.
1197       response_streaming: Whether the RPC supports exactly one response message
1198         or any arbitrary number of response messages.
1199       request_deserializer: A callable behavior that accepts a byte string and
1200         returns an object suitable to be passed to this object's business
1201         logic, or None to indicate that this object's business logic should be
1202         passed the raw request bytes.
1203       response_serializer: A callable behavior that accepts an object produced
1204         by this object's business logic and returns a byte string, or None to
1205         indicate that the byte strings produced by this object's business logic
1206         should be transmitted on the wire as they are.
1207       unary_unary: This object's application-specific business logic as a
1208         callable value that takes a request value and a ServicerContext object
1209         and returns a response value. Only non-None if both request_streaming
1210         and response_streaming are False.
1211       unary_stream: This object's application-specific business logic as a
1212         callable value that takes a request value and a ServicerContext object
1213         and returns an iterator of response values. Only non-None if
1214         request_streaming is False and response_streaming is True.
1215       stream_unary: This object's application-specific business logic as a
1216         callable value that takes an iterator of request values and a
1217         ServicerContext object and returns a response value. Only non-None if
1218         request_streaming is True and response_streaming is False.
1219       stream_stream: This object's application-specific business logic as a
1220         callable value that takes an iterator of request values and a
1221         ServicerContext object and returns an iterator of response values.
1222         Only non-None if request_streaming and response_streaming are both
1223         True.
1224     """
1225
1226
1227 class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
1228     """Describes an RPC that has just arrived for service.
1229     Attributes:
1230       method: The method name of the RPC.
1231       invocation_metadata: The :term:`metadata` sent by the client.
1232     """
1233
1234
1235 class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
1236     """An implementation of arbitrarily many RPC methods."""
1237
1238     @abc.abstractmethod
1239     def service(self, handler_call_details):
1240         """Returns the handler for servicing the RPC.
1241
1242         Args:
1243           handler_call_details: A HandlerCallDetails describing the RPC.
1244
1245         Returns:
1246           An RpcMethodHandler with which the RPC may be serviced if the
1247           implementation chooses to service this RPC, or None otherwise.
1248         """
1249         raise NotImplementedError()
1250
1251
1252 class ServiceRpcHandler(six.with_metaclass(abc.ABCMeta, GenericRpcHandler)):
1253     """An implementation of RPC methods belonging to a service.
1254
1255     A service handles RPC methods with structured names of the form
1256     '/Service.Name/Service.Method', where 'Service.Name' is the value
1257     returned by service_name(), and 'Service.Method' is the method
1258     name.  A service can have multiple method names, but only a single
1259     service name.
1260     """
1261
1262     @abc.abstractmethod
1263     def service_name(self):
1264         """Returns this service's name.
1265
1266         Returns:
1267           The service name.
1268         """
1269         raise NotImplementedError()
1270
1271
1272 ####################  Service-Side Interceptor Interfaces  #####################
1273
1274
1275 class ServerInterceptor(six.with_metaclass(abc.ABCMeta)):
1276     """Affords intercepting incoming RPCs on the service-side.
1277
1278     This is an EXPERIMENTAL API.
1279     """
1280
1281     @abc.abstractmethod
1282     def intercept_service(self, continuation, handler_call_details):
1283         """Intercepts incoming RPCs before handing them over to a handler.
1284
1285         Args:
1286           continuation: A function that takes a HandlerCallDetails and
1287             proceeds to invoke the next interceptor in the chain, if any,
1288             or the RPC handler lookup logic, with the call details passed
1289             as an argument, and returns an RpcMethodHandler instance if
1290             the RPC is considered serviced, or None otherwise.
1291           handler_call_details: A HandlerCallDetails describing the RPC.
1292
1293         Returns:
1294           An RpcMethodHandler with which the RPC may be serviced if the
1295           interceptor chooses to service this RPC, or None otherwise.
1296         """
1297         raise NotImplementedError()
1298
1299
1300 #############################  Server Interface  ###############################
1301
1302
1303 class Server(six.with_metaclass(abc.ABCMeta)):
1304     """Services RPCs."""
1305
1306     @abc.abstractmethod
1307     def add_generic_rpc_handlers(self, generic_rpc_handlers):
1308         """Registers GenericRpcHandlers with this Server.
1309
1310         This method is only safe to call before the server is started.
1311
1312         Args:
1313           generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1314           used to service RPCs.
1315         """
1316         raise NotImplementedError()
1317
1318     @abc.abstractmethod
1319     def add_insecure_port(self, address):
1320         """Opens an insecure port for accepting RPCs.
1321
1322         This method may only be called before starting the server.
1323
1324         Args:
1325           address: The address for which to open a port.
1326           if the port is 0, or not specified in the address, then gRPC runtime
1327           will choose a port.
1328
1329         Returns:
1330           integer:
1331           An integer port on which server will accept RPC requests.
1332         """
1333         raise NotImplementedError()
1334
1335     @abc.abstractmethod
1336     def add_secure_port(self, address, server_credentials):
1337         """Opens a secure port for accepting RPCs.
1338
1339         This method may only be called before starting the server.
1340
1341         Args:
1342           address: The address for which to open a port.
1343             if the port is 0, or not specified in the address, then gRPC
1344             runtime will choose a port.
1345           server_credentials: A ServerCredentials object.
1346
1347         Returns:
1348           integer:
1349           An integer port on which server will accept RPC requests.
1350         """
1351         raise NotImplementedError()
1352
1353     @abc.abstractmethod
1354     def start(self):
1355         """Starts this Server.
1356
1357         This method may only be called once. (i.e. it is not idempotent).
1358         """
1359         raise NotImplementedError()
1360
1361     @abc.abstractmethod
1362     def stop(self, grace):
1363         """Stops this Server.
1364
1365         This method immediately stop service of new RPCs in all cases.
1366
1367         If a grace period is specified, this method returns immediately
1368         and all RPCs active at the end of the grace period are aborted.
1369         If a grace period is not specified (by passing None for `grace`),
1370         all existing RPCs are aborted immediately and this method
1371         blocks until the last RPC handler terminates.
1372
1373         This method is idempotent and may be called at any time.
1374         Passing a smaller grace value in a subsequent call will have
1375         the effect of stopping the Server sooner (passing None will
1376         have the effect of stopping the server immediately). Passing
1377         a larger grace value in a subsequent call *will not* have the
1378         effect of stopping the server later (i.e. the most restrictive
1379         grace value is used).
1380
1381         Args:
1382           grace: A duration of time in seconds or None.
1383
1384         Returns:
1385           A threading.Event that will be set when this Server has completely
1386           stopped, i.e. when running RPCs either complete or are aborted and
1387           all handlers have terminated.
1388         """
1389         raise NotImplementedError()
1390
1391
1392 #################################  Functions    ################################
1393
1394
1395 def unary_unary_rpc_method_handler(behavior,
1396                                    request_deserializer=None,
1397                                    response_serializer=None):
1398     """Creates an RpcMethodHandler for a unary-unary RPC method.
1399
1400     Args:
1401       behavior: The implementation of an RPC that accepts one request
1402         and returns one response.
1403       request_deserializer: An optional behavior for request deserialization.
1404       response_serializer: An optional behavior for response serialization.
1405
1406     Returns:
1407       An RpcMethodHandler object that is typically used by grpc.Server.
1408     """
1409     from grpc import _utilities  # pylint: disable=cyclic-import
1410     return _utilities.RpcMethodHandler(False, False, request_deserializer,
1411                                        response_serializer, behavior, None,
1412                                        None, None)
1413
1414
1415 def unary_stream_rpc_method_handler(behavior,
1416                                     request_deserializer=None,
1417                                     response_serializer=None):
1418     """Creates an RpcMethodHandler for a unary-stream RPC method.
1419
1420     Args:
1421       behavior: The implementation of an RPC that accepts one request
1422         and returns an iterator of response values.
1423       request_deserializer: An optional behavior for request deserialization.
1424       response_serializer: An optional behavior for response serialization.
1425
1426     Returns:
1427       An RpcMethodHandler object that is typically used by grpc.Server.
1428     """
1429     from grpc import _utilities  # pylint: disable=cyclic-import
1430     return _utilities.RpcMethodHandler(False, True, request_deserializer,
1431                                        response_serializer, None, behavior,
1432                                        None, None)
1433
1434
1435 def stream_unary_rpc_method_handler(behavior,
1436                                     request_deserializer=None,
1437                                     response_serializer=None):
1438     """Creates an RpcMethodHandler for a stream-unary RPC method.
1439
1440     Args:
1441       behavior: The implementation of an RPC that accepts an iterator of
1442         request values and returns a single response value.
1443       request_deserializer: An optional behavior for request deserialization.
1444       response_serializer: An optional behavior for response serialization.
1445
1446     Returns:
1447       An RpcMethodHandler object that is typically used by grpc.Server.
1448     """
1449     from grpc import _utilities  # pylint: disable=cyclic-import
1450     return _utilities.RpcMethodHandler(True, False, request_deserializer,
1451                                        response_serializer, None, None,
1452                                        behavior, None)
1453
1454
1455 def stream_stream_rpc_method_handler(behavior,
1456                                      request_deserializer=None,
1457                                      response_serializer=None):
1458     """Creates an RpcMethodHandler for a stream-stream RPC method.
1459
1460     Args:
1461       behavior: The implementation of an RPC that accepts an iterator of
1462         request values and returns an iterator of response values.
1463       request_deserializer: An optional behavior for request deserialization.
1464       response_serializer: An optional behavior for response serialization.
1465
1466     Returns:
1467       An RpcMethodHandler object that is typically used by grpc.Server.
1468     """
1469     from grpc import _utilities  # pylint: disable=cyclic-import
1470     return _utilities.RpcMethodHandler(True, True, request_deserializer,
1471                                        response_serializer, None, None, None,
1472                                        behavior)
1473
1474
1475 def method_handlers_generic_handler(service, method_handlers):
1476     """Creates a GenericRpcHandler from RpcMethodHandlers.
1477
1478     Args:
1479       service: The name of the service that is implemented by the
1480         method_handlers.
1481       method_handlers: A dictionary that maps method names to corresponding
1482         RpcMethodHandler.
1483
1484     Returns:
1485       A GenericRpcHandler. This is typically added to the grpc.Server object
1486       with add_generic_rpc_handlers() before starting the server.
1487     """
1488     from grpc import _utilities  # pylint: disable=cyclic-import
1489     return _utilities.DictionaryGenericHandler(service, method_handlers)
1490
1491
1492 def ssl_channel_credentials(root_certificates=None,
1493                             private_key=None,
1494                             certificate_chain=None):
1495     """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1496
1497     Args:
1498       root_certificates: The PEM-encoded root certificates as a byte string,
1499         or None to retrieve them from a default location chosen by gRPC
1500         runtime.
1501       private_key: The PEM-encoded private key as a byte string, or None if no
1502         private key should be used.
1503       certificate_chain: The PEM-encoded certificate chain as a byte string
1504         to use or or None if no certificate chain should be used.
1505
1506     Returns:
1507       A ChannelCredentials for use with an SSL-enabled Channel.
1508     """
1509     return ChannelCredentials(
1510         _cygrpc.SSLChannelCredentials(root_certificates, private_key,
1511                                       certificate_chain))
1512
1513
1514 def metadata_call_credentials(metadata_plugin, name=None):
1515     """Construct CallCredentials from an AuthMetadataPlugin.
1516
1517     Args:
1518       metadata_plugin: An AuthMetadataPlugin to use for authentication.
1519       name: An optional name for the plugin.
1520
1521     Returns:
1522       A CallCredentials.
1523     """
1524     from grpc import _plugin_wrapping  # pylint: disable=cyclic-import
1525     return _plugin_wrapping.metadata_plugin_call_credentials(
1526         metadata_plugin, name)
1527
1528
1529 def access_token_call_credentials(access_token):
1530     """Construct CallCredentials from an access token.
1531
1532     Args:
1533       access_token: A string to place directly in the http request
1534         authorization header, for example
1535         "authorization: Bearer <access_token>".
1536
1537     Returns:
1538       A CallCredentials.
1539     """
1540     from grpc import _auth  # pylint: disable=cyclic-import
1541     from grpc import _plugin_wrapping  # pylint: disable=cyclic-import
1542     return _plugin_wrapping.metadata_plugin_call_credentials(
1543         _auth.AccessTokenAuthMetadataPlugin(access_token), None)
1544
1545
1546 def composite_call_credentials(*call_credentials):
1547     """Compose multiple CallCredentials to make a new CallCredentials.
1548
1549     Args:
1550       *call_credentials: At least two CallCredentials objects.
1551
1552     Returns:
1553       A CallCredentials object composed of the given CallCredentials objects.
1554     """
1555     return CallCredentials(
1556         _cygrpc.CompositeCallCredentials(
1557             tuple(single_call_credentials._credentials
1558                   for single_call_credentials in call_credentials)))
1559
1560
1561 def composite_channel_credentials(channel_credentials, *call_credentials):
1562     """Compose a ChannelCredentials and one or more CallCredentials objects.
1563
1564     Args:
1565       channel_credentials: A ChannelCredentials object.
1566       *call_credentials: One or more CallCredentials objects.
1567
1568     Returns:
1569       A ChannelCredentials composed of the given ChannelCredentials and
1570         CallCredentials objects.
1571     """
1572     return ChannelCredentials(
1573         _cygrpc.CompositeChannelCredentials(
1574             tuple(single_call_credentials._credentials
1575                   for single_call_credentials in call_credentials),
1576             channel_credentials._credentials))
1577
1578
1579 def ssl_server_credentials(private_key_certificate_chain_pairs,
1580                            root_certificates=None,
1581                            require_client_auth=False):
1582     """Creates a ServerCredentials for use with an SSL-enabled Server.
1583
1584     Args:
1585       private_key_certificate_chain_pairs: A list of pairs of the form
1586         [PEM-encoded private key, PEM-encoded certificate chain].
1587       root_certificates: An optional byte string of PEM-encoded client root
1588         certificates that the server will use to verify client authentication.
1589         If omitted, require_client_auth must also be False.
1590       require_client_auth: A boolean indicating whether or not to require
1591         clients to be authenticated. May only be True if root_certificates
1592         is not None.
1593
1594     Returns:
1595       A ServerCredentials for use with an SSL-enabled Server. Typically, this
1596       object is an argument to add_secure_port() method during server setup.
1597     """
1598     if not private_key_certificate_chain_pairs:
1599         raise ValueError(
1600             'At least one private key-certificate chain pair is required!')
1601     elif require_client_auth and root_certificates is None:
1602         raise ValueError(
1603             'Illegal to require client auth without providing root certificates!'
1604         )
1605     else:
1606         return ServerCredentials(
1607             _cygrpc.server_credentials_ssl(root_certificates, [
1608                 _cygrpc.SslPemKeyCertPair(key, pem)
1609                 for key, pem in private_key_certificate_chain_pairs
1610             ], require_client_auth))
1611
1612
1613 def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
1614                                          root_certificates=None):
1615     """Creates a ServerCertificateConfiguration for use with a Server.
1616
1617     Args:
1618       private_key_certificate_chain_pairs: A collection of pairs of
1619         the form [PEM-encoded private key, PEM-encoded certificate
1620         chain].
1621       root_certificates: An optional byte string of PEM-encoded client root
1622         certificates that the server will use to verify client authentication.
1623
1624     Returns:
1625       A ServerCertificateConfiguration that can be returned in the certificate
1626         configuration fetching callback.
1627     """
1628     if private_key_certificate_chain_pairs:
1629         return ServerCertificateConfiguration(
1630             _cygrpc.server_certificate_config_ssl(root_certificates, [
1631                 _cygrpc.SslPemKeyCertPair(key, pem)
1632                 for key, pem in private_key_certificate_chain_pairs
1633             ]))
1634     else:
1635         raise ValueError(
1636             'At least one private key-certificate chain pair is required!')
1637
1638
1639 def dynamic_ssl_server_credentials(initial_certificate_configuration,
1640                                    certificate_configuration_fetcher,
1641                                    require_client_authentication=False):
1642     """Creates a ServerCredentials for use with an SSL-enabled Server.
1643
1644     Args:
1645       initial_certificate_configuration (ServerCertificateConfiguration): The
1646         certificate configuration with which the server will be initialized.
1647       certificate_configuration_fetcher (callable): A callable that takes no
1648         arguments and should return a ServerCertificateConfiguration to
1649         replace the server's current certificate, or None for no change
1650         (i.e., the server will continue its current certificate
1651         config). The library will call this callback on *every* new
1652         client connection before starting the TLS handshake with the
1653         client, thus allowing the user application to optionally
1654         return a new ServerCertificateConfiguration that the server will then
1655         use for the handshake.
1656       require_client_authentication: A boolean indicating whether or not to
1657         require clients to be authenticated.
1658
1659     Returns:
1660       A ServerCredentials.
1661     """
1662     return ServerCredentials(
1663         _cygrpc.server_credentials_ssl_dynamic_cert_config(
1664             initial_certificate_configuration,
1665             certificate_configuration_fetcher, require_client_authentication))
1666
1667
1668 def channel_ready_future(channel):
1669     """Creates a Future that tracks when a Channel is ready.
1670
1671     Cancelling the Future does not affect the channel's state machine.
1672     It merely decouples the Future from channel state machine.
1673
1674     Args:
1675       channel: A Channel object.
1676
1677     Returns:
1678       A Future object that matures when the channel connectivity is
1679       ChannelConnectivity.READY.
1680     """
1681     from grpc import _utilities  # pylint: disable=cyclic-import
1682     return _utilities.channel_ready_future(channel)
1683
1684
1685 def insecure_channel(target, options=None):
1686     """Creates an insecure Channel to a server.
1687
1688     The returned Channel is thread-safe.
1689
1690     Args:
1691       target: The server address
1692       options: An optional list of key-value pairs (channel args
1693         in gRPC Core runtime) to configure the channel.
1694
1695     Returns:
1696       A Channel.
1697     """
1698     from grpc import _channel  # pylint: disable=cyclic-import
1699     return _channel.Channel(target, () if options is None else options, None)
1700
1701
1702 def secure_channel(target, credentials, options=None):
1703     """Creates a secure Channel to a server.
1704
1705     The returned Channel is thread-safe.
1706
1707     Args:
1708       target: The server address.
1709       credentials: A ChannelCredentials instance.
1710       options: An optional list of key-value pairs (channel args
1711         in gRPC Core runtime) to configure the channel.
1712
1713     Returns:
1714       A Channel.
1715     """
1716     from grpc import _channel  # pylint: disable=cyclic-import
1717     return _channel.Channel(target, () if options is None else options,
1718                             credentials._credentials)
1719
1720
1721 def intercept_channel(channel, *interceptors):
1722     """Intercepts a channel through a set of interceptors.
1723
1724     This is an EXPERIMENTAL API.
1725
1726     Args:
1727       channel: A Channel.
1728       interceptors: Zero or more objects of type
1729         UnaryUnaryClientInterceptor,
1730         UnaryStreamClientInterceptor,
1731         StreamUnaryClientInterceptor, or
1732         StreamStreamClientInterceptor.
1733         Interceptors are given control in the order they are listed.
1734
1735     Returns:
1736       A Channel that intercepts each invocation via the provided interceptors.
1737
1738     Raises:
1739       TypeError: If interceptor does not derive from any of
1740         UnaryUnaryClientInterceptor,
1741         UnaryStreamClientInterceptor,
1742         StreamUnaryClientInterceptor, or
1743         StreamStreamClientInterceptor.
1744     """
1745     from grpc import _interceptor  # pylint: disable=cyclic-import
1746     return _interceptor.intercept_channel(channel, *interceptors)
1747
1748
1749 def server(thread_pool,
1750            handlers=None,
1751            interceptors=None,
1752            options=None,
1753            maximum_concurrent_rpcs=None):
1754     """Creates a Server with which RPCs can be serviced.
1755
1756     Args:
1757       thread_pool: A futures.ThreadPoolExecutor to be used by the Server
1758         to execute RPC handlers.
1759       handlers: An optional list of GenericRpcHandlers used for executing RPCs.
1760         More handlers may be added by calling add_generic_rpc_handlers any time
1761         before the server is started.
1762       interceptors: An optional list of ServerInterceptor objects that observe
1763         and optionally manipulate the incoming RPCs before handing them over to
1764         handlers. The interceptors are given control in the order they are
1765         specified. This is an EXPERIMENTAL API.
1766       options: An optional list of key-value pairs (channel args in gRPC runtime)
1767         to configure the channel.
1768       maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
1769         will service before returning RESOURCE_EXHAUSTED status, or None to
1770         indicate no limit.
1771
1772     Returns:
1773       A Server object.
1774     """
1775     from grpc import _server  # pylint: disable=cyclic-import
1776     return _server.create_server(thread_pool, ()
1777                                  if handlers is None else handlers, ()
1778                                  if interceptors is None else interceptors, ()
1779                                  if options is None else options,
1780                                  maximum_concurrent_rpcs)
1781
1782
1783 @contextlib.contextmanager
1784 def _create_servicer_context(rpc_event, state, request_deserializer):
1785     from grpc import _server  # pylint: disable=cyclic-import
1786     context = _server._Context(rpc_event, state, request_deserializer)
1787     yield context
1788     context._finalize_state()  # pylint: disable=protected-access
1789
1790
1791 ###################################  __all__  #################################
1792
1793 __all__ = (
1794     'FutureTimeoutError',
1795     'FutureCancelledError',
1796     'Future',
1797     'ChannelConnectivity',
1798     'StatusCode',
1799     'Status',
1800     'RpcError',
1801     'RpcContext',
1802     'Call',
1803     'ChannelCredentials',
1804     'CallCredentials',
1805     'AuthMetadataContext',
1806     'AuthMetadataPluginCallback',
1807     'AuthMetadataPlugin',
1808     'ClientCallDetails',
1809     'ServerCertificateConfiguration',
1810     'ServerCredentials',
1811     'UnaryUnaryMultiCallable',
1812     'UnaryStreamMultiCallable',
1813     'StreamUnaryMultiCallable',
1814     'StreamStreamMultiCallable',
1815     'UnaryUnaryClientInterceptor',
1816     'UnaryStreamClientInterceptor',
1817     'StreamUnaryClientInterceptor',
1818     'StreamStreamClientInterceptor',
1819     'Channel',
1820     'ServicerContext',
1821     'RpcMethodHandler',
1822     'HandlerCallDetails',
1823     'GenericRpcHandler',
1824     'ServiceRpcHandler',
1825     'Server',
1826     'ServerInterceptor',
1827     'unary_unary_rpc_method_handler',
1828     'unary_stream_rpc_method_handler',
1829     'stream_unary_rpc_method_handler',
1830     'stream_stream_rpc_method_handler',
1831     'method_handlers_generic_handler',
1832     'ssl_channel_credentials',
1833     'metadata_call_credentials',
1834     'access_token_call_credentials',
1835     'composite_call_credentials',
1836     'composite_channel_credentials',
1837     'ssl_server_credentials',
1838     'ssl_server_certificate_configuration',
1839     'dynamic_ssl_server_credentials',
1840     'channel_ready_future',
1841     'insecure_channel',
1842     'secure_channel',
1843     'intercept_channel',
1844     'server',
1845 )
1846
1847 ############################### Extension Shims ################################
1848
1849 # Here to maintain backwards compatibility; avoid using these in new code!
1850 try:
1851     import grpc_tools
1852     sys.modules.update({'grpc.tools': grpc_tools})
1853 except ImportError:
1854     pass
1855 try:
1856     import grpc_health
1857     sys.modules.update({'grpc.health': grpc_health})
1858 except ImportError:
1859     pass
1860 try:
1861     import grpc_reflection
1862     sys.modules.update({'grpc.reflection': grpc_reflection})
1863 except ImportError:
1864     pass