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