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