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