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