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