Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/grpc/__init__.py: 2%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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."""
16import abc
17import contextlib
18import enum
19import logging
20import sys
22from grpc import _compression
23from grpc._cython import cygrpc as _cygrpc
24from grpc._runtime_protos import protos
25from grpc._runtime_protos import protos_and_services
26from grpc._runtime_protos import services
28logging.getLogger(__name__).addHandler(logging.NullHandler())
30try:
31 # pylint: disable=ungrouped-imports
32 from grpc._grpcio_metadata import __version__
33except ImportError:
34 __version__ = "dev0"
36############################## Future Interface ###############################
39class FutureTimeoutError(Exception):
40 """Indicates that a method call on a Future timed out."""
43class FutureCancelledError(Exception):
44 """Indicates that the computation underlying a Future was cancelled."""
47class Future(abc.ABC):
48 """A representation of a computation in another control flow.
50 Computations represented by a Future may be yet to be begun,
51 may be ongoing, or may have already completed.
52 """
54 @abc.abstractmethod
55 def cancel(self):
56 """Attempts to cancel the computation.
58 This method does not block.
60 Returns:
61 bool:
62 Returns True if the computation was canceled.
64 Returns False under all other circumstances, for example:
66 1. computation has begun and could not be canceled.
67 2. computation has finished
68 3. computation is scheduled for execution and it is impossible
69 to determine its state without blocking.
70 """
71 raise NotImplementedError()
73 @abc.abstractmethod
74 def cancelled(self):
75 """Describes whether the computation was cancelled.
77 This method does not block.
79 Returns:
80 bool:
81 Returns True if the computation was cancelled before its result became
82 available.
84 Returns False under all other circumstances, for example:
86 1. computation was not cancelled.
87 2. computation's result is available.
88 """
89 raise NotImplementedError()
91 @abc.abstractmethod
92 def running(self):
93 """Describes whether the computation is taking place.
95 This method does not block.
97 Returns:
98 Returns True if the computation is scheduled for execution or
99 currently executing.
101 Returns False if the computation already executed or was cancelled.
102 """
103 raise NotImplementedError()
105 @abc.abstractmethod
106 def done(self):
107 """Describes whether the computation has taken place.
109 This method does not block.
111 Returns:
112 bool:
113 Returns True if the computation already executed or was cancelled.
114 Returns False if the computation is scheduled for execution or
115 currently executing.
116 This is exactly opposite of the running() method's result.
117 """
118 raise NotImplementedError()
120 @abc.abstractmethod
121 def result(self, timeout=None):
122 """Returns the result of the computation or raises its exception.
124 This method may return immediately or may block.
126 Args:
127 timeout: The length of time in seconds to wait for the computation to
128 finish or be cancelled. If None, the call will block until the
129 computations's termination.
131 Returns:
132 The return value of the computation.
134 Raises:
135 FutureTimeoutError: If a timeout value is passed and the computation
136 does not terminate within the allotted time.
137 FutureCancelledError: If the computation was cancelled.
138 Exception: If the computation raised an exception, this call will
139 raise the same exception.
140 """
141 raise NotImplementedError()
143 @abc.abstractmethod
144 def exception(self, timeout=None):
145 """Return the exception raised by the computation.
147 This method may return immediately or may block.
149 Args:
150 timeout: The length of time in seconds to wait for the computation to
151 terminate or be cancelled. If None, the call will block until the
152 computations's termination.
154 Returns:
155 The exception raised by the computation, or None if the computation
156 did not raise an exception.
158 Raises:
159 FutureTimeoutError: If a timeout value is passed and the computation
160 does not terminate within the allotted time.
161 FutureCancelledError: If the computation was cancelled.
162 """
163 raise NotImplementedError()
165 @abc.abstractmethod
166 def traceback(self, timeout=None):
167 """Access the traceback of the exception raised by the computation.
169 This method may return immediately or may block.
171 Args:
172 timeout: The length of time in seconds to wait for the computation
173 to terminate or be cancelled. If None, the call will block until
174 the computation's termination.
176 Returns:
177 The traceback of the exception raised by the computation, or None
178 if the computation did not raise an exception.
180 Raises:
181 FutureTimeoutError: If a timeout value is passed and the computation
182 does not terminate within the allotted time.
183 FutureCancelledError: If the computation was cancelled.
184 """
185 raise NotImplementedError()
187 @abc.abstractmethod
188 def add_done_callback(self, fn):
189 """Adds a function to be called at completion of the computation.
191 The callback will be passed this Future object describing the outcome
192 of the computation. Callbacks will be invoked after the future is
193 terminated, whether successfully or not.
195 If the computation has already completed, the callback will be called
196 immediately.
198 Exceptions raised in the callback will be logged at ERROR level, but
199 will not terminate any threads of execution.
201 Args:
202 fn: A callable taking this Future object as its single parameter.
203 """
204 raise NotImplementedError()
207################################ gRPC Enums ##################################
210@enum.unique
211class ChannelConnectivity(enum.Enum):
212 """Mirrors grpc_connectivity_state in the gRPC Core.
214 Attributes:
215 IDLE: The channel is idle.
216 CONNECTING: The channel is connecting.
217 READY: The channel is ready to conduct RPCs.
218 TRANSIENT_FAILURE: The channel has seen a failure from which it expects
219 to recover.
220 SHUTDOWN: The channel has seen a failure from which it cannot recover.
221 """
223 IDLE = (_cygrpc.ConnectivityState.idle, "idle")
224 CONNECTING = (_cygrpc.ConnectivityState.connecting, "connecting")
225 READY = (_cygrpc.ConnectivityState.ready, "ready")
226 TRANSIENT_FAILURE = (
227 _cygrpc.ConnectivityState.transient_failure,
228 "transient failure",
229 )
230 SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, "shutdown")
233@enum.unique
234class StatusCode(enum.Enum):
235 """Mirrors grpc_status_code in the gRPC Core.
237 Attributes:
238 OK: Not an error; returned on success
239 CANCELLED: The operation was cancelled (typically by the caller).
240 UNKNOWN: Unknown error.
241 INVALID_ARGUMENT: Client specified an invalid argument.
242 DEADLINE_EXCEEDED: Deadline expired before operation could complete.
243 NOT_FOUND: Some requested entity (e.g., file or directory) was not found.
244 ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory)
245 already exists.
246 PERMISSION_DENIED: The caller does not have permission to execute the specified
247 operation.
248 UNAUTHENTICATED: The request does not have valid authentication credentials for the
249 operation.
250 RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or
251 perhaps the entire file system is out of space.
252 FAILED_PRECONDITION: Operation was rejected because the system is not in a state
253 required for the operation's execution.
254 ABORTED: The operation was aborted, typically due to a concurrency issue
255 like sequencer check failures, transaction aborts, etc.
256 UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service.
257 INTERNAL: Internal errors. Means some invariants expected by underlying
258 system has been broken.
259 UNAVAILABLE: The service is currently unavailable.
260 DATA_LOSS: Unrecoverable data loss or corruption.
261 """
263 OK = (_cygrpc.StatusCode.ok, "ok")
264 CANCELLED = (_cygrpc.StatusCode.cancelled, "cancelled")
265 UNKNOWN = (_cygrpc.StatusCode.unknown, "unknown")
266 INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, "invalid argument")
267 DEADLINE_EXCEEDED = (
268 _cygrpc.StatusCode.deadline_exceeded,
269 "deadline exceeded",
270 )
271 NOT_FOUND = (_cygrpc.StatusCode.not_found, "not found")
272 ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, "already exists")
273 PERMISSION_DENIED = (
274 _cygrpc.StatusCode.permission_denied,
275 "permission denied",
276 )
277 RESOURCE_EXHAUSTED = (
278 _cygrpc.StatusCode.resource_exhausted,
279 "resource exhausted",
280 )
281 FAILED_PRECONDITION = (
282 _cygrpc.StatusCode.failed_precondition,
283 "failed precondition",
284 )
285 ABORTED = (_cygrpc.StatusCode.aborted, "aborted")
286 OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, "out of range")
287 UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, "unimplemented")
288 INTERNAL = (_cygrpc.StatusCode.internal, "internal")
289 UNAVAILABLE = (_cygrpc.StatusCode.unavailable, "unavailable")
290 DATA_LOSS = (_cygrpc.StatusCode.data_loss, "data loss")
291 UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, "unauthenticated")
294############################# gRPC Status ################################
297class Status(abc.ABC):
298 """Describes the status of an RPC.
300 This is an EXPERIMENTAL API.
302 Attributes:
303 code: A StatusCode object to be sent to the client.
304 details: A UTF-8-encodable string to be sent to the client upon
305 termination of the RPC.
306 trailing_metadata: The trailing :term:`metadata` in the RPC.
307 """
310############################# gRPC Exceptions ################################
313class RpcError(Exception):
314 """Raised by the gRPC library to indicate non-OK-status RPC termination."""
317############################## Shared Context ################################
320class RpcContext(abc.ABC):
321 """Provides RPC-related information and action."""
323 @abc.abstractmethod
324 def is_active(self):
325 """Describes whether the RPC is active or has terminated.
327 Returns:
328 bool:
329 True if RPC is active, False otherwise.
330 """
331 raise NotImplementedError()
333 @abc.abstractmethod
334 def time_remaining(self):
335 """Describes the length of allowed time remaining for the RPC.
337 Returns:
338 A nonnegative float indicating the length of allowed time in seconds
339 remaining for the RPC to complete before it is considered to have
340 timed out, or None if no deadline was specified for the RPC.
341 """
342 raise NotImplementedError()
344 @abc.abstractmethod
345 def cancel(self):
346 """Cancels the RPC.
348 Idempotent and has no effect if the RPC has already terminated.
349 """
350 raise NotImplementedError()
352 @abc.abstractmethod
353 def add_callback(self, callback):
354 """Registers a callback to be called on RPC termination.
356 Args:
357 callback: A no-parameter callable to be called on RPC termination.
359 Returns:
360 True if the callback was added and will be called later; False if
361 the callback was not added and will not be called (because the RPC
362 already terminated or some other reason).
363 """
364 raise NotImplementedError()
367######################### Invocation-Side Context ############################
370class Call(RpcContext, metaclass=abc.ABCMeta):
371 """Invocation-side utility object for an RPC."""
373 @abc.abstractmethod
374 def initial_metadata(self):
375 """Accesses the initial metadata sent by the server.
377 This method blocks until the value is available.
379 Returns:
380 The initial :term:`metadata`.
381 """
382 raise NotImplementedError()
384 @abc.abstractmethod
385 def trailing_metadata(self):
386 """Accesses the trailing metadata sent by the server.
388 This method blocks until the value is available.
390 Returns:
391 The trailing :term:`metadata`.
392 """
393 raise NotImplementedError()
395 @abc.abstractmethod
396 def code(self):
397 """Accesses the status code sent by the server.
399 This method blocks until the value is available.
401 Returns:
402 The StatusCode value for the RPC.
403 """
404 raise NotImplementedError()
406 @abc.abstractmethod
407 def details(self):
408 """Accesses the details sent by the server.
410 This method blocks until the value is available.
412 Returns:
413 The details string of the RPC.
414 """
415 raise NotImplementedError()
418############## Invocation-Side Interceptor Interfaces & Classes ##############
421class ClientCallDetails(abc.ABC):
422 """Describes an RPC to be invoked.
424 Attributes:
425 method: The method name of the RPC.
426 timeout: An optional duration of time in seconds to allow for the RPC.
427 metadata: Optional :term:`metadata` to be transmitted to
428 the service-side of the RPC.
429 credentials: An optional CallCredentials for the RPC.
430 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
431 compression: An element of grpc.compression, e.g.
432 grpc.compression.Gzip.
433 """
436class UnaryUnaryClientInterceptor(abc.ABC):
437 """Affords intercepting unary-unary invocations."""
439 @abc.abstractmethod
440 def intercept_unary_unary(self, continuation, client_call_details, request):
441 """Intercepts a unary-unary invocation asynchronously.
443 Args:
444 continuation: A function that proceeds with the invocation by
445 executing the next interceptor in chain or invoking the
446 actual RPC on the underlying Channel. It is the interceptor's
447 responsibility to call it if it decides to move the RPC forward.
448 The interceptor can use
449 `response_future = continuation(client_call_details, request)`
450 to continue with the RPC. `continuation` returns an object that is
451 both a Call for the RPC and a Future. In the event of RPC
452 completion, the return Call-Future's result value will be
453 the response message of the RPC. Should the event terminate
454 with non-OK status, the returned Call-Future's exception value
455 will be an RpcError.
456 client_call_details: A ClientCallDetails object describing the
457 outgoing RPC.
458 request: The request value for the RPC.
460 Returns:
461 An object that is both a Call for the RPC and a Future.
462 In the event of RPC completion, the return Call-Future's
463 result value will be the response message of the RPC.
464 Should the event terminate with non-OK status, the returned
465 Call-Future's exception value will be an RpcError.
466 """
467 raise NotImplementedError()
470class UnaryStreamClientInterceptor(abc.ABC):
471 """Affords intercepting unary-stream invocations."""
473 @abc.abstractmethod
474 def intercept_unary_stream(
475 self, continuation, client_call_details, request
476 ):
477 """Intercepts a unary-stream invocation.
479 Args:
480 continuation: A function that proceeds with the invocation by
481 executing the next interceptor in chain or invoking the
482 actual RPC on the underlying Channel. It is the interceptor's
483 responsibility to call it if it decides to move the RPC forward.
484 The interceptor can use
485 `response_iterator = continuation(client_call_details, request)`
486 to continue with the RPC. `continuation` returns an object that is
487 both a Call for the RPC and an iterator for response values.
488 Drawing response values from the returned Call-iterator may
489 raise RpcError indicating termination of the RPC with non-OK
490 status.
491 client_call_details: A ClientCallDetails object describing the
492 outgoing RPC.
493 request: The request value for the RPC.
495 Returns:
496 An object that is both a Call for the RPC and an iterator of
497 response values. Drawing response values from the returned
498 Call-iterator may raise RpcError indicating termination of
499 the RPC with non-OK status. This object *should* also fulfill the
500 Future interface, though it may not.
501 """
502 raise NotImplementedError()
505class StreamUnaryClientInterceptor(abc.ABC):
506 """Affords intercepting stream-unary invocations."""
508 @abc.abstractmethod
509 def intercept_stream_unary(
510 self, continuation, client_call_details, request_iterator
511 ):
512 """Intercepts a stream-unary invocation asynchronously.
514 Args:
515 continuation: A function that proceeds with the invocation by
516 executing the next interceptor in chain or invoking the
517 actual RPC on the underlying Channel. It is the interceptor's
518 responsibility to call it if it decides to move the RPC forward.
519 The interceptor can use
520 `response_future = continuation(client_call_details, request_iterator)`
521 to continue with the RPC. `continuation` returns an object that is
522 both a Call for the RPC and a Future. In the event of RPC completion,
523 the return Call-Future's result value will be the response message
524 of the RPC. Should the event terminate with non-OK status, the
525 returned Call-Future's exception value will be an RpcError.
526 client_call_details: A ClientCallDetails object describing the
527 outgoing RPC.
528 request_iterator: An iterator that yields request values for the RPC.
530 Returns:
531 An object that is both a Call for the RPC and a Future.
532 In the event of RPC completion, the return Call-Future's
533 result value will be the response message of the RPC.
534 Should the event terminate with non-OK status, the returned
535 Call-Future's exception value will be an RpcError.
536 """
537 raise NotImplementedError()
540class StreamStreamClientInterceptor(abc.ABC):
541 """Affords intercepting stream-stream invocations."""
543 @abc.abstractmethod
544 def intercept_stream_stream(
545 self, continuation, client_call_details, request_iterator
546 ):
547 """Intercepts a stream-stream invocation.
549 Args:
550 continuation: A function that proceeds with the invocation by
551 executing the next interceptor in chain or invoking the
552 actual RPC on the underlying Channel. It is the interceptor's
553 responsibility to call it if it decides to move the RPC forward.
554 The interceptor can use
555 `response_iterator = continuation(client_call_details, request_iterator)`
556 to continue with the RPC. `continuation` returns an object that is
557 both a Call for the RPC and an iterator for response values.
558 Drawing response values from the returned Call-iterator may
559 raise RpcError indicating termination of the RPC with non-OK
560 status.
561 client_call_details: A ClientCallDetails object describing the
562 outgoing RPC.
563 request_iterator: An iterator that yields request values for the RPC.
565 Returns:
566 An object that is both a Call for the RPC and an iterator of
567 response values. Drawing response values from the returned
568 Call-iterator may raise RpcError indicating termination of
569 the RPC with non-OK status. This object *should* also fulfill the
570 Future interface, though it may not.
571 """
572 raise NotImplementedError()
575############ Authentication & Authorization Interfaces & Classes #############
578class ChannelCredentials(object):
579 """An encapsulation of the data required to create a secure Channel.
581 This class has no supported interface - it exists to define the type of its
582 instances and its instances exist to be passed to other functions. For
583 example, ssl_channel_credentials returns an instance of this class and
584 secure_channel requires an instance of this class.
585 """
587 def __init__(self, credentials):
588 self._credentials = credentials
591class CallCredentials(object):
592 """An encapsulation of the data required to assert an identity over a call.
594 A CallCredentials has to be used with secure Channel, otherwise the
595 metadata will not be transmitted to the server.
597 A CallCredentials may be composed with ChannelCredentials to always assert
598 identity for every call over that Channel.
600 This class has no supported interface - it exists to define the type of its
601 instances and its instances exist to be passed to other functions.
602 """
604 def __init__(self, credentials):
605 self._credentials = credentials
608class AuthMetadataContext(abc.ABC):
609 """Provides information to call credentials metadata plugins.
611 Attributes:
612 service_url: A string URL of the service being called into.
613 method_name: A string of the fully qualified method name being called.
614 """
617class AuthMetadataPluginCallback(abc.ABC):
618 """Callback object received by a metadata plugin."""
620 def __call__(self, metadata, error):
621 """Passes to the gRPC runtime authentication metadata for an RPC.
623 Args:
624 metadata: The :term:`metadata` used to construct the CallCredentials.
625 error: An Exception to indicate error or None to indicate success.
626 """
627 raise NotImplementedError()
630class AuthMetadataPlugin(abc.ABC):
631 """A specification for custom authentication."""
633 def __call__(self, context, callback):
634 """Implements authentication by passing metadata to a callback.
636 This method will be invoked asynchronously in a separate thread.
638 Args:
639 context: An AuthMetadataContext providing information on the RPC that
640 the plugin is being called to authenticate.
641 callback: An AuthMetadataPluginCallback to be invoked either
642 synchronously or asynchronously.
643 """
644 raise NotImplementedError()
647class ServerCredentials(object):
648 """An encapsulation of the data required to open a secure port on a Server.
650 This class has no supported interface - it exists to define the type of its
651 instances and its instances exist to be passed to other functions.
652 """
654 def __init__(self, credentials):
655 self._credentials = credentials
658class ServerCertificateConfiguration(object):
659 """A certificate configuration for use with an SSL-enabled Server.
661 Instances of this class can be returned in the certificate configuration
662 fetching callback.
664 This class has no supported interface -- it exists to define the
665 type of its instances and its instances exist to be passed to
666 other functions.
667 """
669 def __init__(self, certificate_configuration):
670 self._certificate_configuration = certificate_configuration
673######################## Multi-Callable Interfaces ###########################
676class UnaryUnaryMultiCallable(abc.ABC):
677 """Affords invoking a unary-unary RPC from client-side."""
679 @abc.abstractmethod
680 def __call__(
681 self,
682 request,
683 timeout=None,
684 metadata=None,
685 credentials=None,
686 wait_for_ready=None,
687 compression=None,
688 ):
689 """Synchronously invokes the underlying RPC.
691 Args:
692 request: The request value for the RPC.
693 timeout: An optional duration of time in seconds to allow
694 for the RPC.
695 metadata: Optional :term:`metadata` to be transmitted to the
696 service-side of the RPC.
697 credentials: An optional CallCredentials for the RPC. Only valid for
698 secure Channel.
699 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
700 compression: An element of grpc.compression, e.g.
701 grpc.compression.Gzip.
703 Returns:
704 The response value for the RPC.
706 Raises:
707 RpcError: Indicating that the RPC terminated with non-OK status. The
708 raised RpcError will also be a Call for the RPC affording the RPC's
709 metadata, status code, and details.
710 """
711 raise NotImplementedError()
713 @abc.abstractmethod
714 def with_call(
715 self,
716 request,
717 timeout=None,
718 metadata=None,
719 credentials=None,
720 wait_for_ready=None,
721 compression=None,
722 ):
723 """Synchronously invokes the underlying RPC.
725 Args:
726 request: The request value for the RPC.
727 timeout: An optional durating of time in seconds to allow for
728 the RPC.
729 metadata: Optional :term:`metadata` to be transmitted to the
730 service-side of the RPC.
731 credentials: An optional CallCredentials for the RPC. Only valid for
732 secure Channel.
733 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
734 compression: An element of grpc.compression, e.g.
735 grpc.compression.Gzip.
737 Returns:
738 The response value for the RPC and a Call value for the RPC.
740 Raises:
741 RpcError: Indicating that the RPC terminated with non-OK status. The
742 raised RpcError will also be a Call for the RPC affording the RPC's
743 metadata, status code, and details.
744 """
745 raise NotImplementedError()
747 @abc.abstractmethod
748 def future(
749 self,
750 request,
751 timeout=None,
752 metadata=None,
753 credentials=None,
754 wait_for_ready=None,
755 compression=None,
756 ):
757 """Asynchronously invokes the underlying RPC.
759 Args:
760 request: The request value for the RPC.
761 timeout: An optional duration of time in seconds to allow for
762 the RPC.
763 metadata: Optional :term:`metadata` to be transmitted to the
764 service-side of the RPC.
765 credentials: An optional CallCredentials for the RPC. Only valid for
766 secure Channel.
767 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
768 compression: An element of grpc.compression, e.g.
769 grpc.compression.Gzip.
771 Returns:
772 An object that is both a Call for the RPC and a Future.
773 In the event of RPC completion, the return Call-Future's result
774 value will be the response message of the RPC.
775 Should the event terminate with non-OK status,
776 the returned Call-Future's exception value will be an RpcError.
777 """
778 raise NotImplementedError()
781class UnaryStreamMultiCallable(abc.ABC):
782 """Affords invoking a unary-stream RPC from client-side."""
784 @abc.abstractmethod
785 def __call__(
786 self,
787 request,
788 timeout=None,
789 metadata=None,
790 credentials=None,
791 wait_for_ready=None,
792 compression=None,
793 ):
794 """Invokes the underlying RPC.
796 Args:
797 request: The request value for the RPC.
798 timeout: An optional duration of time in seconds to allow for
799 the RPC. If None, the timeout is considered infinite.
800 metadata: An optional :term:`metadata` to be transmitted to the
801 service-side of the RPC.
802 credentials: An optional CallCredentials for the RPC. Only valid for
803 secure Channel.
804 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
805 compression: An element of grpc.compression, e.g.
806 grpc.compression.Gzip.
808 Returns:
809 An object that is a Call for the RPC, an iterator of response
810 values, and a Future for the RPC. Drawing response values from the
811 returned Call-iterator may raise RpcError indicating termination of
812 the RPC with non-OK status.
813 """
814 raise NotImplementedError()
817class StreamUnaryMultiCallable(abc.ABC):
818 """Affords invoking a stream-unary RPC from client-side."""
820 @abc.abstractmethod
821 def __call__(
822 self,
823 request_iterator,
824 timeout=None,
825 metadata=None,
826 credentials=None,
827 wait_for_ready=None,
828 compression=None,
829 ):
830 """Synchronously invokes the underlying RPC.
832 Args:
833 request_iterator: An iterator that yields request values for
834 the RPC.
835 timeout: An optional duration of time in seconds to allow for
836 the RPC. If None, the timeout is considered infinite.
837 metadata: Optional :term:`metadata` to be transmitted to the
838 service-side of the RPC.
839 credentials: An optional CallCredentials for the RPC. Only valid for
840 secure Channel.
841 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
842 compression: An element of grpc.compression, e.g.
843 grpc.compression.Gzip.
845 Returns:
846 The response value for the RPC.
848 Raises:
849 RpcError: Indicating that the RPC terminated with non-OK status. The
850 raised RpcError will also implement grpc.Call, affording methods
851 such as metadata, code, and details.
852 """
853 raise NotImplementedError()
855 @abc.abstractmethod
856 def with_call(
857 self,
858 request_iterator,
859 timeout=None,
860 metadata=None,
861 credentials=None,
862 wait_for_ready=None,
863 compression=None,
864 ):
865 """Synchronously invokes the underlying RPC on the client.
867 Args:
868 request_iterator: An iterator that yields request values for
869 the RPC.
870 timeout: An optional duration of time in seconds to allow for
871 the RPC. If None, the timeout is considered infinite.
872 metadata: Optional :term:`metadata` to be transmitted to the
873 service-side of the RPC.
874 credentials: An optional CallCredentials for the RPC. Only valid for
875 secure Channel.
876 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
877 compression: An element of grpc.compression, e.g.
878 grpc.compression.Gzip.
880 Returns:
881 The response value for the RPC and a Call object for the RPC.
883 Raises:
884 RpcError: Indicating that the RPC terminated with non-OK status. The
885 raised RpcError will also be a Call for the RPC affording the RPC's
886 metadata, status code, and details.
887 """
888 raise NotImplementedError()
890 @abc.abstractmethod
891 def future(
892 self,
893 request_iterator,
894 timeout=None,
895 metadata=None,
896 credentials=None,
897 wait_for_ready=None,
898 compression=None,
899 ):
900 """Asynchronously invokes the underlying RPC on the client.
902 Args:
903 request_iterator: An iterator that yields request values for the RPC.
904 timeout: An optional duration of time in seconds to allow for
905 the RPC. If None, the timeout is considered infinite.
906 metadata: Optional :term:`metadata` to be transmitted to the
907 service-side of the RPC.
908 credentials: An optional CallCredentials for the RPC. Only valid for
909 secure Channel.
910 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
911 compression: An element of grpc.compression, e.g.
912 grpc.compression.Gzip.
914 Returns:
915 An object that is both a Call for the RPC and a Future.
916 In the event of RPC completion, the return Call-Future's result value
917 will be the response message of the RPC. Should the event terminate
918 with non-OK status, the returned Call-Future's exception value will
919 be an RpcError.
920 """
921 raise NotImplementedError()
924class StreamStreamMultiCallable(abc.ABC):
925 """Affords invoking a stream-stream RPC on client-side."""
927 @abc.abstractmethod
928 def __call__(
929 self,
930 request_iterator,
931 timeout=None,
932 metadata=None,
933 credentials=None,
934 wait_for_ready=None,
935 compression=None,
936 ):
937 """Invokes the underlying RPC on the client.
939 Args:
940 request_iterator: An iterator that yields request values for the RPC.
941 timeout: An optional duration of time in seconds to allow for
942 the RPC. If not specified, the timeout is considered infinite.
943 metadata: Optional :term:`metadata` to be transmitted to the
944 service-side of the RPC.
945 credentials: An optional CallCredentials for the RPC. Only valid for
946 secure Channel.
947 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
948 compression: An element of grpc.compression, e.g.
949 grpc.compression.Gzip.
951 Returns:
952 An object that is a Call for the RPC, an iterator of response
953 values, and a Future for the RPC. Drawing response values from the
954 returned Call-iterator may raise RpcError indicating termination of
955 the RPC with non-OK status.
956 """
957 raise NotImplementedError()
960############################# Channel Interface ##############################
963class Channel(abc.ABC):
964 """Affords RPC invocation via generic methods on client-side.
966 Channel objects implement the Context Manager type, although they need not
967 support being entered and exited multiple times.
968 """
970 @abc.abstractmethod
971 def subscribe(self, callback, try_to_connect=False):
972 """Subscribe to this Channel's connectivity state machine.
974 A Channel may be in any of the states described by ChannelConnectivity.
975 This method allows application to monitor the state transitions.
976 The typical use case is to debug or gain better visibility into gRPC
977 runtime's state.
979 Args:
980 callback: A callable to be invoked with ChannelConnectivity argument.
981 ChannelConnectivity describes current state of the channel.
982 The callable will be invoked immediately upon subscription
983 and again for every change to ChannelConnectivity until it
984 is unsubscribed or this Channel object goes out of scope.
985 try_to_connect: A boolean indicating whether or not this Channel
986 should attempt to connect immediately. If set to False, gRPC
987 runtime decides when to connect.
988 """
989 raise NotImplementedError()
991 @abc.abstractmethod
992 def unsubscribe(self, callback):
993 """Unsubscribes a subscribed callback from this Channel's connectivity.
995 Args:
996 callback: A callable previously registered with this Channel from
997 having been passed to its "subscribe" method.
998 """
999 raise NotImplementedError()
1001 @abc.abstractmethod
1002 def unary_unary(
1003 self,
1004 method,
1005 request_serializer=None,
1006 response_deserializer=None,
1007 _registered_method=False,
1008 ):
1009 """Creates a UnaryUnaryMultiCallable for a unary-unary method.
1011 Args:
1012 method: The name of the RPC method.
1013 request_serializer: Optional :term:`serializer` for serializing the request
1014 message. Request goes unserialized in case None is passed.
1015 response_deserializer: Optional :term:`deserializer` for deserializing the
1016 response message. Response goes undeserialized in case None
1017 is passed.
1018 _registered_method: Implementation Private. A bool representing whether the method
1019 is registered.
1021 Returns:
1022 A UnaryUnaryMultiCallable value for the named unary-unary method.
1023 """
1024 raise NotImplementedError()
1026 @abc.abstractmethod
1027 def unary_stream(
1028 self,
1029 method,
1030 request_serializer=None,
1031 response_deserializer=None,
1032 _registered_method=False,
1033 ):
1034 """Creates a UnaryStreamMultiCallable for a unary-stream method.
1036 Args:
1037 method: The name of the RPC method.
1038 request_serializer: Optional :term:`serializer` for serializing the request
1039 message. Request goes unserialized in case None is passed.
1040 response_deserializer: Optional :term:`deserializer` for deserializing the
1041 response message. Response goes undeserialized in case None is
1042 passed.
1043 _registered_method: Implementation Private. A bool representing whether the method
1044 is registered.
1046 Returns:
1047 A UnaryStreamMultiCallable value for the name unary-stream method.
1048 """
1049 raise NotImplementedError()
1051 @abc.abstractmethod
1052 def stream_unary(
1053 self,
1054 method,
1055 request_serializer=None,
1056 response_deserializer=None,
1057 _registered_method=False,
1058 ):
1059 """Creates a StreamUnaryMultiCallable for a stream-unary method.
1061 Args:
1062 method: The name of the RPC method.
1063 request_serializer: Optional :term:`serializer` for serializing the request
1064 message. Request goes unserialized in case None is passed.
1065 response_deserializer: Optional :term:`deserializer` for deserializing the
1066 response message. Response goes undeserialized in case None is
1067 passed.
1068 _registered_method: Implementation Private. A bool representing whether the method
1069 is registered.
1071 Returns:
1072 A StreamUnaryMultiCallable value for the named stream-unary method.
1073 """
1074 raise NotImplementedError()
1076 @abc.abstractmethod
1077 def stream_stream(
1078 self,
1079 method,
1080 request_serializer=None,
1081 response_deserializer=None,
1082 _registered_method=False,
1083 ):
1084 """Creates a StreamStreamMultiCallable for a stream-stream method.
1086 Args:
1087 method: The name of the RPC method.
1088 request_serializer: Optional :term:`serializer` for serializing the request
1089 message. Request goes unserialized in case None is passed.
1090 response_deserializer: Optional :term:`deserializer` for deserializing the
1091 response message. Response goes undeserialized in case None
1092 is passed.
1093 _registered_method: Implementation Private. A bool representing whether the method
1094 is registered.
1096 Returns:
1097 A StreamStreamMultiCallable value for the named stream-stream method.
1098 """
1099 raise NotImplementedError()
1101 @abc.abstractmethod
1102 def close(self):
1103 """Closes this Channel and releases all resources held by it.
1105 Closing the Channel will immediately terminate all RPCs active with the
1106 Channel and it is not valid to invoke new RPCs with the Channel.
1108 This method is idempotent.
1109 """
1110 raise NotImplementedError()
1112 def __enter__(self):
1113 """Enters the runtime context related to the channel object."""
1114 raise NotImplementedError()
1116 def __exit__(self, exc_type, exc_val, exc_tb):
1117 """Exits the runtime context related to the channel object."""
1118 raise NotImplementedError()
1121########################## Service-Side Context ##############################
1124class ServicerContext(RpcContext, metaclass=abc.ABCMeta):
1125 """A context object passed to method implementations."""
1127 @abc.abstractmethod
1128 def invocation_metadata(self):
1129 """Accesses the metadata sent by the client.
1131 Returns:
1132 The invocation :term:`metadata`.
1133 """
1134 raise NotImplementedError()
1136 @abc.abstractmethod
1137 def peer(self):
1138 """Identifies the peer that invoked the RPC being serviced.
1140 Returns:
1141 A string identifying the peer that invoked the RPC being serviced.
1142 The string format is determined by gRPC runtime.
1143 """
1144 raise NotImplementedError()
1146 @abc.abstractmethod
1147 def peer_identities(self):
1148 """Gets one or more peer identity(s).
1150 Equivalent to
1151 servicer_context.auth_context().get(servicer_context.peer_identity_key())
1153 Returns:
1154 An iterable of the identities, or None if the call is not
1155 authenticated. Each identity is returned as a raw bytes type.
1156 """
1157 raise NotImplementedError()
1159 @abc.abstractmethod
1160 def peer_identity_key(self):
1161 """The auth property used to identify the peer.
1163 For example, "x509_common_name" or "x509_subject_alternative_name" are
1164 used to identify an SSL peer.
1166 Returns:
1167 The auth property (string) that indicates the
1168 peer identity, or None if the call is not authenticated.
1169 """
1170 raise NotImplementedError()
1172 @abc.abstractmethod
1173 def auth_context(self):
1174 """Gets the auth context for the call.
1176 Returns:
1177 A map of strings to an iterable of bytes for each auth property.
1178 """
1179 raise NotImplementedError()
1181 def set_compression(self, compression):
1182 """Set the compression algorithm to be used for the entire call.
1184 Args:
1185 compression: An element of grpc.compression, e.g.
1186 grpc.compression.Gzip.
1187 """
1188 raise NotImplementedError()
1190 @abc.abstractmethod
1191 def send_initial_metadata(self, initial_metadata):
1192 """Sends the initial metadata value to the client.
1194 This method need not be called by implementations if they have no
1195 metadata to add to what the gRPC runtime will transmit.
1197 Args:
1198 initial_metadata: The initial :term:`metadata`.
1199 """
1200 raise NotImplementedError()
1202 @abc.abstractmethod
1203 def set_trailing_metadata(self, trailing_metadata):
1204 """Sets the trailing metadata for the RPC.
1206 Sets the trailing metadata to be sent upon completion of the RPC.
1208 If this method is invoked multiple times throughout the lifetime of an
1209 RPC, the value supplied in the final invocation will be the value sent
1210 over the wire.
1212 This method need not be called by implementations if they have no
1213 metadata to add to what the gRPC runtime will transmit.
1215 Args:
1216 trailing_metadata: The trailing :term:`metadata`.
1217 """
1218 raise NotImplementedError()
1220 def trailing_metadata(self):
1221 """Access value to be used as trailing metadata upon RPC completion.
1223 This is an EXPERIMENTAL API.
1225 Returns:
1226 The trailing :term:`metadata` for the RPC.
1227 """
1228 raise NotImplementedError()
1230 @abc.abstractmethod
1231 def abort(self, code, details):
1232 """Raises an exception to terminate the RPC with a non-OK status.
1234 The code and details passed as arguments will supercede any existing
1235 ones.
1237 Args:
1238 code: A StatusCode object to be sent to the client.
1239 It must not be StatusCode.OK.
1240 details: A UTF-8-encodable string to be sent to the client upon
1241 termination of the RPC.
1243 Raises:
1244 Exception: An exception is always raised to signal the abortion the
1245 RPC to the gRPC runtime.
1246 """
1247 raise NotImplementedError()
1249 @abc.abstractmethod
1250 def abort_with_status(self, status):
1251 """Raises an exception to terminate the RPC with a non-OK status.
1253 The status passed as argument will supercede any existing status code,
1254 status message and trailing metadata.
1256 This is an EXPERIMENTAL API.
1258 Args:
1259 status: A grpc.Status object. The status code in it must not be
1260 StatusCode.OK.
1262 Raises:
1263 Exception: An exception is always raised to signal the abortion the
1264 RPC to the gRPC runtime.
1265 """
1266 raise NotImplementedError()
1268 @abc.abstractmethod
1269 def set_code(self, code):
1270 """Sets the value to be used as status code upon RPC completion.
1272 This method need not be called by method implementations if they wish
1273 the gRPC runtime to determine the status code of the RPC.
1275 Args:
1276 code: A StatusCode object to be sent to the client.
1277 """
1278 raise NotImplementedError()
1280 @abc.abstractmethod
1281 def set_details(self, details):
1282 """Sets the value to be used as detail string upon RPC completion.
1284 This method need not be called by method implementations if they have
1285 no details to transmit.
1287 Args:
1288 details: A UTF-8-encodable string to be sent to the client upon
1289 termination of the RPC.
1290 """
1291 raise NotImplementedError()
1293 def code(self):
1294 """Accesses the value to be used as status code upon RPC completion.
1296 This is an EXPERIMENTAL API.
1298 Returns:
1299 The StatusCode value for the RPC.
1300 """
1301 raise NotImplementedError()
1303 def details(self):
1304 """Accesses the value to be used as detail string upon RPC completion.
1306 This is an EXPERIMENTAL API.
1308 Returns:
1309 The details string of the RPC.
1310 """
1311 raise NotImplementedError()
1313 def disable_next_message_compression(self):
1314 """Disables compression for the next response message.
1316 This method will override any compression configuration set during
1317 server creation or set on the call.
1318 """
1319 raise NotImplementedError()
1322##################### Service-Side Handler Interfaces ########################
1325class RpcMethodHandler(abc.ABC):
1326 """An implementation of a single RPC method.
1328 Attributes:
1329 request_streaming: Whether the RPC supports exactly one request message
1330 or any arbitrary number of request messages.
1331 response_streaming: Whether the RPC supports exactly one response message
1332 or any arbitrary number of response messages.
1333 request_deserializer: A callable :term:`deserializer` that accepts a byte string and
1334 returns an object suitable to be passed to this object's business
1335 logic, or None to indicate that this object's business logic should be
1336 passed the raw request bytes.
1337 response_serializer: A callable :term:`serializer` that accepts an object produced
1338 by this object's business logic and returns a byte string, or None to
1339 indicate that the byte strings produced by this object's business logic
1340 should be transmitted on the wire as they are.
1341 unary_unary: This object's application-specific business logic as a
1342 callable value that takes a request value and a ServicerContext object
1343 and returns a response value. Only non-None if both request_streaming
1344 and response_streaming are False.
1345 unary_stream: This object's application-specific business logic as a
1346 callable value that takes a request value and a ServicerContext object
1347 and returns an iterator of response values. Only non-None if
1348 request_streaming is False and response_streaming is True.
1349 stream_unary: This object's application-specific business logic as a
1350 callable value that takes an iterator of request values and a
1351 ServicerContext object and returns a response value. Only non-None if
1352 request_streaming is True and response_streaming is False.
1353 stream_stream: This object's application-specific business logic as a
1354 callable value that takes an iterator of request values and a
1355 ServicerContext object and returns an iterator of response values.
1356 Only non-None if request_streaming and response_streaming are both
1357 True.
1358 """
1361class HandlerCallDetails(abc.ABC):
1362 """Describes an RPC that has just arrived for service.
1364 Attributes:
1365 method: The method name of the RPC.
1366 invocation_metadata: The :term:`metadata` sent by the client.
1367 """
1370class GenericRpcHandler(abc.ABC):
1371 """An implementation of arbitrarily many RPC methods."""
1373 @abc.abstractmethod
1374 def service(self, handler_call_details):
1375 """Returns the handler for servicing the RPC.
1377 Args:
1378 handler_call_details: A HandlerCallDetails describing the RPC.
1380 Returns:
1381 An RpcMethodHandler with which the RPC may be serviced if the
1382 implementation chooses to service this RPC, or None otherwise.
1383 """
1384 raise NotImplementedError()
1387class ServiceRpcHandler(GenericRpcHandler, metaclass=abc.ABCMeta):
1388 """An implementation of RPC methods belonging to a service.
1390 A service handles RPC methods with structured names of the form
1391 '/Service.Name/Service.Method', where 'Service.Name' is the value
1392 returned by service_name(), and 'Service.Method' is the method
1393 name. A service can have multiple method names, but only a single
1394 service name.
1395 """
1397 @abc.abstractmethod
1398 def service_name(self):
1399 """Returns this service's name.
1401 Returns:
1402 The service name.
1403 """
1404 raise NotImplementedError()
1407#################### Service-Side Interceptor Interfaces #####################
1410class ServerInterceptor(abc.ABC):
1411 """Affords intercepting incoming RPCs on the service-side."""
1413 @abc.abstractmethod
1414 def intercept_service(self, continuation, handler_call_details):
1415 """Intercepts incoming RPCs before handing them over to a handler.
1417 State can be passed from an interceptor to downstream interceptors
1418 via contextvars. The first interceptor is called from an empty
1419 contextvars.Context, and the same Context is used for downstream
1420 interceptors and for the final handler call. Note that there are no
1421 guarantees that interceptors and handlers will be called from the
1422 same thread.
1424 Args:
1425 continuation: A function that takes a HandlerCallDetails and
1426 proceeds to invoke the next interceptor in the chain, if any,
1427 or the RPC handler lookup logic, with the call details passed
1428 as an argument, and returns an RpcMethodHandler instance if
1429 the RPC is considered serviced, or None otherwise.
1430 handler_call_details: A HandlerCallDetails describing the RPC.
1432 Returns:
1433 An RpcMethodHandler with which the RPC may be serviced if the
1434 interceptor chooses to service this RPC, or None otherwise.
1435 """
1436 raise NotImplementedError()
1439############################# Server Interface ###############################
1442class Server(abc.ABC):
1443 """Services RPCs."""
1445 @abc.abstractmethod
1446 def add_generic_rpc_handlers(self, generic_rpc_handlers):
1447 """Registers GenericRpcHandlers with this Server.
1449 This method is only safe to call before the server is started.
1451 Args:
1452 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1453 used to service RPCs.
1454 """
1455 raise NotImplementedError()
1457 def add_registered_method_handlers(self, service_name, method_handlers):
1458 """Registers GenericRpcHandlers with this Server.
1460 This method is only safe to call before the server is started.
1462 If the same method have both generic and registered handler,
1463 registered handler will take precedence.
1465 Args:
1466 service_name: The service name.
1467 method_handlers: A dictionary that maps method names to corresponding
1468 RpcMethodHandler.
1469 """
1471 @abc.abstractmethod
1472 def add_insecure_port(self, address):
1473 """Opens an insecure port for accepting RPCs.
1475 This method may only be called before starting the server.
1477 Args:
1478 address: The address for which to open a port. If the port is 0,
1479 or not specified in the address, then gRPC runtime will choose a port.
1481 Returns:
1482 An integer port on which server will accept RPC requests.
1483 """
1484 raise NotImplementedError()
1486 @abc.abstractmethod
1487 def add_secure_port(self, address, server_credentials):
1488 """Opens a secure port for accepting RPCs.
1490 This method may only be called before starting the server.
1492 Args:
1493 address: The address for which to open a port.
1494 if the port is 0, or not specified in the address, then gRPC
1495 runtime will choose a port.
1496 server_credentials: A ServerCredentials object.
1498 Returns:
1499 An integer port on which server will accept RPC requests.
1500 """
1501 raise NotImplementedError()
1503 @abc.abstractmethod
1504 def start(self):
1505 """Starts this Server.
1507 This method may only be called once. (i.e. it is not idempotent).
1508 """
1509 raise NotImplementedError()
1511 @abc.abstractmethod
1512 def stop(self, grace):
1513 """Stops this Server.
1515 This method immediately stop service of new RPCs in all cases.
1517 If a grace period is specified, this method waits until all active
1518 RPCs are finished or until the grace period is reached. RPCs that haven't
1519 been terminated within the grace period are aborted.
1520 If a grace period is not specified (by passing None for `grace`),
1521 all existing RPCs are aborted immediately and this method
1522 blocks until the last RPC handler terminates.
1524 This method is idempotent and may be called at any time.
1525 Passing a smaller grace value in a subsequent call will have
1526 the effect of stopping the Server sooner (passing None will
1527 have the effect of stopping the server immediately). Passing
1528 a larger grace value in a subsequent call *will not* have the
1529 effect of stopping the server later (i.e. the most restrictive
1530 grace value is used).
1532 Args:
1533 grace: A duration of time in seconds or None.
1535 Returns:
1536 A threading.Event that will be set when this Server has completely
1537 stopped, i.e. when running RPCs either complete or are aborted and
1538 all handlers have terminated.
1539 """
1540 raise NotImplementedError()
1542 def wait_for_termination(self, timeout=None):
1543 """Block current thread until the server stops.
1545 This is an EXPERIMENTAL API.
1547 The wait will not consume computational resources during blocking, and
1548 it will block until one of the two following conditions are met:
1550 1) The server is stopped or terminated;
1551 2) A timeout occurs if timeout is not `None`.
1553 The timeout argument works in the same way as `threading.Event.wait()`.
1554 https://docs.python.org/3/library/threading.html#threading.Event.wait
1556 Args:
1557 timeout: A floating point number specifying a timeout for the
1558 operation in seconds.
1560 Returns:
1561 A bool indicates if the operation times out.
1562 """
1563 raise NotImplementedError()
1566################################# Functions ################################
1569def unary_unary_rpc_method_handler(
1570 behavior, request_deserializer=None, response_serializer=None
1571):
1572 """Creates an RpcMethodHandler for a unary-unary RPC method.
1574 Args:
1575 behavior: The implementation of an RPC that accepts one request
1576 and returns one response.
1577 request_deserializer: An optional :term:`deserializer` for request deserialization.
1578 response_serializer: An optional :term:`serializer` for response serialization.
1580 Returns:
1581 An RpcMethodHandler object that is typically used by grpc.Server.
1582 """
1583 from grpc import _utilities # pylint: disable=cyclic-import
1585 return _utilities.RpcMethodHandler(
1586 False,
1587 False,
1588 request_deserializer,
1589 response_serializer,
1590 behavior,
1591 None,
1592 None,
1593 None,
1594 )
1597def unary_stream_rpc_method_handler(
1598 behavior, request_deserializer=None, response_serializer=None
1599):
1600 """Creates an RpcMethodHandler for a unary-stream RPC method.
1602 Args:
1603 behavior: The implementation of an RPC that accepts one request
1604 and returns an iterator of response values.
1605 request_deserializer: An optional :term:`deserializer` for request deserialization.
1606 response_serializer: An optional :term:`serializer` for response serialization.
1608 Returns:
1609 An RpcMethodHandler object that is typically used by grpc.Server.
1610 """
1611 from grpc import _utilities # pylint: disable=cyclic-import
1613 return _utilities.RpcMethodHandler(
1614 False,
1615 True,
1616 request_deserializer,
1617 response_serializer,
1618 None,
1619 behavior,
1620 None,
1621 None,
1622 )
1625def stream_unary_rpc_method_handler(
1626 behavior, request_deserializer=None, response_serializer=None
1627):
1628 """Creates an RpcMethodHandler for a stream-unary RPC method.
1630 Args:
1631 behavior: The implementation of an RPC that accepts an iterator of
1632 request values and returns a single response value.
1633 request_deserializer: An optional :term:`deserializer` for request deserialization.
1634 response_serializer: An optional :term:`serializer` for response serialization.
1636 Returns:
1637 An RpcMethodHandler object that is typically used by grpc.Server.
1638 """
1639 from grpc import _utilities # pylint: disable=cyclic-import
1641 return _utilities.RpcMethodHandler(
1642 True,
1643 False,
1644 request_deserializer,
1645 response_serializer,
1646 None,
1647 None,
1648 behavior,
1649 None,
1650 )
1653def stream_stream_rpc_method_handler(
1654 behavior, request_deserializer=None, response_serializer=None
1655):
1656 """Creates an RpcMethodHandler for a stream-stream RPC method.
1658 Args:
1659 behavior: The implementation of an RPC that accepts an iterator of
1660 request values and returns an iterator of response values.
1661 request_deserializer: An optional :term:`deserializer` for request deserialization.
1662 response_serializer: An optional :term:`serializer` for response serialization.
1664 Returns:
1665 An RpcMethodHandler object that is typically used by grpc.Server.
1666 """
1667 from grpc import _utilities # pylint: disable=cyclic-import
1669 return _utilities.RpcMethodHandler(
1670 True,
1671 True,
1672 request_deserializer,
1673 response_serializer,
1674 None,
1675 None,
1676 None,
1677 behavior,
1678 )
1681def method_handlers_generic_handler(service, method_handlers):
1682 """Creates a GenericRpcHandler from RpcMethodHandlers.
1684 Args:
1685 service: The name of the service that is implemented by the
1686 method_handlers.
1687 method_handlers: A dictionary that maps method names to corresponding
1688 RpcMethodHandler.
1690 Returns:
1691 A GenericRpcHandler. This is typically added to the grpc.Server object
1692 with add_generic_rpc_handlers() before starting the server.
1693 """
1694 from grpc import _utilities # pylint: disable=cyclic-import
1696 return _utilities.DictionaryGenericHandler(service, method_handlers)
1699def ssl_channel_credentials(
1700 root_certificates=None, private_key=None, certificate_chain=None
1701):
1702 """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1704 Args:
1705 root_certificates: The PEM-encoded root certificates as a byte string,
1706 or None to retrieve them from a default location chosen by gRPC
1707 runtime.
1708 private_key: The PEM-encoded private key as a byte string, or None if no
1709 private key should be used.
1710 certificate_chain: The PEM-encoded certificate chain as a byte string
1711 to use or None if no certificate chain should be used.
1713 Returns:
1714 A ChannelCredentials for use with an SSL-enabled Channel.
1715 """
1716 return ChannelCredentials(
1717 _cygrpc.SSLChannelCredentials(
1718 root_certificates, private_key, certificate_chain
1719 )
1720 )
1723def xds_channel_credentials(fallback_credentials=None):
1724 """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL
1725 API.
1727 Args:
1728 fallback_credentials: Credentials to use in case it is not possible to
1729 establish a secure connection via xDS. If no fallback_credentials
1730 argument is supplied, a default SSLChannelCredentials is used.
1731 """
1732 fallback_credentials = (
1733 ssl_channel_credentials()
1734 if fallback_credentials is None
1735 else fallback_credentials
1736 )
1737 return ChannelCredentials(
1738 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials)
1739 )
1742def metadata_call_credentials(metadata_plugin, name=None):
1743 """Construct CallCredentials from an AuthMetadataPlugin.
1745 Args:
1746 metadata_plugin: An AuthMetadataPlugin to use for authentication.
1747 name: An optional name for the plugin.
1749 Returns:
1750 A CallCredentials.
1751 """
1752 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1754 return _plugin_wrapping.metadata_plugin_call_credentials(
1755 metadata_plugin, name
1756 )
1759def access_token_call_credentials(access_token):
1760 """Construct CallCredentials from an access token.
1762 Args:
1763 access_token: A string to place directly in the http request
1764 authorization header, for example
1765 "authorization: Bearer <access_token>".
1767 Returns:
1768 A CallCredentials.
1769 """
1770 from grpc import _auth # pylint: disable=cyclic-import
1771 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1773 return _plugin_wrapping.metadata_plugin_call_credentials(
1774 _auth.AccessTokenAuthMetadataPlugin(access_token), None
1775 )
1778def composite_call_credentials(*call_credentials):
1779 """Compose multiple CallCredentials to make a new CallCredentials.
1781 Args:
1782 *call_credentials: At least two CallCredentials objects.
1784 Returns:
1785 A CallCredentials object composed of the given CallCredentials objects.
1786 """
1787 return CallCredentials(
1788 _cygrpc.CompositeCallCredentials(
1789 tuple(
1790 single_call_credentials._credentials
1791 for single_call_credentials in call_credentials
1792 )
1793 )
1794 )
1797def composite_channel_credentials(channel_credentials, *call_credentials):
1798 """Compose a ChannelCredentials and one or more CallCredentials objects.
1800 Args:
1801 channel_credentials: A ChannelCredentials object.
1802 *call_credentials: One or more CallCredentials objects.
1804 Returns:
1805 A ChannelCredentials composed of the given ChannelCredentials and
1806 CallCredentials objects.
1807 """
1808 return ChannelCredentials(
1809 _cygrpc.CompositeChannelCredentials(
1810 tuple(
1811 single_call_credentials._credentials
1812 for single_call_credentials in call_credentials
1813 ),
1814 channel_credentials._credentials,
1815 )
1816 )
1819def ssl_server_credentials(
1820 private_key_certificate_chain_pairs,
1821 root_certificates=None,
1822 require_client_auth=False,
1823):
1824 """Creates a ServerCredentials for use with an SSL-enabled Server.
1826 Args:
1827 private_key_certificate_chain_pairs: A list of pairs of the form
1828 [PEM-encoded private key, PEM-encoded certificate chain].
1829 root_certificates: An optional byte string of PEM-encoded client root
1830 certificates that the server will use to verify client authentication.
1831 If omitted, require_client_auth must also be False.
1832 require_client_auth: A boolean indicating whether or not to require
1833 clients to be authenticated. May only be True if root_certificates
1834 is not None.
1836 Returns:
1837 A ServerCredentials for use with an SSL-enabled Server. Typically, this
1838 object is an argument to add_secure_port() method during server setup.
1839 """
1840 if not private_key_certificate_chain_pairs:
1841 raise ValueError(
1842 "At least one private key-certificate chain pair is required!"
1843 )
1844 elif require_client_auth and root_certificates is None:
1845 raise ValueError(
1846 "Illegal to require client auth without providing root"
1847 " certificates!"
1848 )
1849 else:
1850 return ServerCredentials(
1851 _cygrpc.server_credentials_ssl(
1852 root_certificates,
1853 [
1854 _cygrpc.SslPemKeyCertPair(key, pem)
1855 for key, pem in private_key_certificate_chain_pairs
1856 ],
1857 require_client_auth,
1858 )
1859 )
1862def xds_server_credentials(fallback_credentials):
1863 """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL
1864 API.
1866 Args:
1867 fallback_credentials: Credentials to use in case it is not possible to
1868 establish a secure connection via xDS. No default value is provided.
1869 """
1870 return ServerCredentials(
1871 _cygrpc.xds_server_credentials(fallback_credentials._credentials)
1872 )
1875def insecure_server_credentials():
1876 """Creates a credentials object directing the server to use no credentials.
1877 This is an EXPERIMENTAL API.
1879 This object cannot be used directly in a call to `add_secure_port`.
1880 Instead, it should be used to construct other credentials objects, e.g.
1881 with xds_server_credentials.
1882 """
1883 return ServerCredentials(_cygrpc.insecure_server_credentials())
1886def ssl_server_certificate_configuration(
1887 private_key_certificate_chain_pairs, root_certificates=None
1888):
1889 """Creates a ServerCertificateConfiguration for use with a Server.
1891 Args:
1892 private_key_certificate_chain_pairs: A collection of pairs of
1893 the form [PEM-encoded private key, PEM-encoded certificate
1894 chain].
1895 root_certificates: An optional byte string of PEM-encoded client root
1896 certificates that the server will use to verify client authentication.
1898 Returns:
1899 A ServerCertificateConfiguration that can be returned in the certificate
1900 configuration fetching callback.
1901 """
1902 if private_key_certificate_chain_pairs:
1903 return ServerCertificateConfiguration(
1904 _cygrpc.server_certificate_config_ssl(
1905 root_certificates,
1906 [
1907 _cygrpc.SslPemKeyCertPair(key, pem)
1908 for key, pem in private_key_certificate_chain_pairs
1909 ],
1910 )
1911 )
1912 else:
1913 raise ValueError(
1914 "At least one private key-certificate chain pair is required!"
1915 )
1918def dynamic_ssl_server_credentials(
1919 initial_certificate_configuration,
1920 certificate_configuration_fetcher,
1921 require_client_authentication=False,
1922):
1923 """Creates a ServerCredentials for use with an SSL-enabled Server.
1925 Args:
1926 initial_certificate_configuration (ServerCertificateConfiguration): The
1927 certificate configuration with which the server will be initialized.
1928 certificate_configuration_fetcher (callable): A callable that takes no
1929 arguments and should return a ServerCertificateConfiguration to
1930 replace the server's current certificate, or None for no change
1931 (i.e., the server will continue its current certificate
1932 config). The library will call this callback on *every* new
1933 client connection before starting the TLS handshake with the
1934 client, thus allowing the user application to optionally
1935 return a new ServerCertificateConfiguration that the server will then
1936 use for the handshake.
1937 require_client_authentication: A boolean indicating whether or not to
1938 require clients to be authenticated.
1940 Returns:
1941 A ServerCredentials.
1942 """
1943 return ServerCredentials(
1944 _cygrpc.server_credentials_ssl_dynamic_cert_config(
1945 initial_certificate_configuration,
1946 certificate_configuration_fetcher,
1947 require_client_authentication,
1948 )
1949 )
1952@enum.unique
1953class LocalConnectionType(enum.Enum):
1954 """Types of local connection for local credential creation.
1956 Attributes:
1957 UDS: Unix domain socket connections
1958 LOCAL_TCP: Local TCP connections.
1959 """
1961 UDS = _cygrpc.LocalConnectionType.uds
1962 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
1965def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1966 """Creates a local ChannelCredentials used for local connections.
1968 This is an EXPERIMENTAL API.
1970 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1971 also UDS connections.
1973 The connections created by local channel credentials are not
1974 encrypted, but will be checked if they are local or not.
1975 The UDS connections are considered secure by providing peer authentication
1976 and data confidentiality while TCP connections are considered insecure.
1978 It is allowed to transmit call credentials over connections created by
1979 local channel credentials.
1981 Local channel credentials are useful for 1) eliminating insecure_channel usage;
1982 2) enable unit testing for call credentials without setting up secrets.
1984 Args:
1985 local_connect_type: Local connection type (either
1986 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1988 Returns:
1989 A ChannelCredentials for use with a local Channel
1990 """
1991 return ChannelCredentials(
1992 _cygrpc.channel_credentials_local(local_connect_type.value)
1993 )
1996def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1997 """Creates a local ServerCredentials used for local connections.
1999 This is an EXPERIMENTAL API.
2001 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
2002 also UDS connections.
2004 The connections created by local server credentials are not
2005 encrypted, but will be checked if they are local or not.
2006 The UDS connections are considered secure by providing peer authentication
2007 and data confidentiality while TCP connections are considered insecure.
2009 It is allowed to transmit call credentials over connections created by local
2010 server credentials.
2012 Local server credentials are useful for 1) eliminating insecure_channel usage;
2013 2) enable unit testing for call credentials without setting up secrets.
2015 Args:
2016 local_connect_type: Local connection type (either
2017 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
2019 Returns:
2020 A ServerCredentials for use with a local Server
2021 """
2022 return ServerCredentials(
2023 _cygrpc.server_credentials_local(local_connect_type.value)
2024 )
2027def alts_channel_credentials(service_accounts=None):
2028 """Creates a ChannelCredentials for use with an ALTS-enabled Channel.
2030 This is an EXPERIMENTAL API.
2031 ALTS credentials API can only be used in GCP environment as it relies on
2032 handshaker service being available. For more info about ALTS see
2033 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2035 Args:
2036 service_accounts: A list of server identities accepted by the client.
2037 If target service accounts are provided and none of them matches the
2038 peer identity of the server, handshake will fail. The arg can be empty
2039 if the client does not have any information about trusted server
2040 identity.
2041 Returns:
2042 A ChannelCredentials for use with an ALTS-enabled Channel
2043 """
2044 return ChannelCredentials(
2045 _cygrpc.channel_credentials_alts(service_accounts or [])
2046 )
2049def alts_server_credentials():
2050 """Creates a ServerCredentials for use with an ALTS-enabled connection.
2052 This is an EXPERIMENTAL API.
2053 ALTS credentials API can only be used in GCP environment as it relies on
2054 handshaker service being available. For more info about ALTS see
2055 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2057 Returns:
2058 A ServerCredentials for use with an ALTS-enabled Server
2059 """
2060 return ServerCredentials(_cygrpc.server_credentials_alts())
2063def compute_engine_channel_credentials(call_credentials):
2064 """Creates a compute engine channel credential.
2066 This credential can only be used in a GCP environment as it relies on
2067 a handshaker service. For more info about ALTS, see
2068 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2070 This channel credential is expected to be used as part of a composite
2071 credential in conjunction with a call credentials that authenticates the
2072 VM's default service account. If used with any other sort of call
2073 credential, the connection may suddenly and unexpectedly begin failing RPCs.
2074 """
2075 return ChannelCredentials(
2076 _cygrpc.channel_credentials_compute_engine(
2077 call_credentials._credentials
2078 )
2079 )
2082def channel_ready_future(channel):
2083 """Creates a Future that tracks when a Channel is ready.
2085 Cancelling the Future does not affect the channel's state machine.
2086 It merely decouples the Future from channel state machine.
2088 Args:
2089 channel: A Channel object.
2091 Returns:
2092 A Future object that matures when the channel connectivity is
2093 ChannelConnectivity.READY.
2094 """
2095 from grpc import _utilities # pylint: disable=cyclic-import
2097 return _utilities.channel_ready_future(channel)
2100def insecure_channel(target, options=None, compression=None):
2101 """Creates an insecure Channel to a server.
2103 The returned Channel is thread-safe.
2105 Args:
2106 target: The server address
2107 options: An optional list of key-value pairs (:term:`channel_arguments`
2108 in gRPC Core runtime) to configure the channel.
2109 compression: An optional value indicating the compression method to be
2110 used over the lifetime of the channel.
2112 Returns:
2113 A Channel.
2114 """
2115 from grpc import _channel # pylint: disable=cyclic-import
2117 return _channel.Channel(
2118 target, () if options is None else options, None, compression
2119 )
2122def secure_channel(target, credentials, options=None, compression=None):
2123 """Creates a secure Channel to a server.
2125 The returned Channel is thread-safe.
2127 Args:
2128 target: The server address.
2129 credentials: A ChannelCredentials instance.
2130 options: An optional list of key-value pairs (:term:`channel_arguments`
2131 in gRPC Core runtime) to configure the channel.
2132 compression: An optional value indicating the compression method to be
2133 used over the lifetime of the channel.
2135 Returns:
2136 A Channel.
2137 """
2138 from grpc import _channel # pylint: disable=cyclic-import
2139 from grpc.experimental import _insecure_channel_credentials
2141 if credentials._credentials is _insecure_channel_credentials:
2142 raise ValueError(
2143 "secure_channel cannot be called with insecure credentials."
2144 + " Call insecure_channel instead."
2145 )
2146 return _channel.Channel(
2147 target,
2148 () if options is None else options,
2149 credentials._credentials,
2150 compression,
2151 )
2154def intercept_channel(channel, *interceptors):
2155 """Intercepts a channel through a set of interceptors.
2157 Args:
2158 channel: A Channel.
2159 interceptors: Zero or more objects of type
2160 UnaryUnaryClientInterceptor,
2161 UnaryStreamClientInterceptor,
2162 StreamUnaryClientInterceptor, or
2163 StreamStreamClientInterceptor.
2164 Interceptors are given control in the order they are listed.
2166 Returns:
2167 A Channel that intercepts each invocation via the provided interceptors.
2169 Raises:
2170 TypeError: If interceptor does not derive from any of
2171 UnaryUnaryClientInterceptor,
2172 UnaryStreamClientInterceptor,
2173 StreamUnaryClientInterceptor, or
2174 StreamStreamClientInterceptor.
2175 """
2176 from grpc import _interceptor # pylint: disable=cyclic-import
2178 return _interceptor.intercept_channel(channel, *interceptors)
2181def server(
2182 thread_pool,
2183 handlers=None,
2184 interceptors=None,
2185 options=None,
2186 maximum_concurrent_rpcs=None,
2187 compression=None,
2188 xds=False,
2189):
2190 """Creates a Server with which RPCs can be serviced.
2192 Args:
2193 thread_pool: A futures.ThreadPoolExecutor to be used by the Server
2194 to execute RPC handlers.
2195 handlers: An optional list of GenericRpcHandlers used for executing RPCs.
2196 More handlers may be added by calling add_generic_rpc_handlers any time
2197 before the server is started.
2198 interceptors: An optional list of ServerInterceptor objects that observe
2199 and optionally manipulate the incoming RPCs before handing them over to
2200 handlers. The interceptors are given control in the order they are
2201 specified. This is an EXPERIMENTAL API.
2202 options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
2203 to configure the channel.
2204 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
2205 will service before returning RESOURCE_EXHAUSTED status, or None to
2206 indicate no limit.
2207 compression: An element of grpc.compression, e.g.
2208 grpc.compression.Gzip. This compression algorithm will be used for the
2209 lifetime of the server unless overridden.
2210 xds: If set to true, retrieves server configuration via xDS. This is an
2211 EXPERIMENTAL option.
2213 Returns:
2214 A Server object.
2215 """
2216 from grpc import _server # pylint: disable=cyclic-import
2218 return _server.create_server(
2219 thread_pool,
2220 () if handlers is None else handlers,
2221 () if interceptors is None else interceptors,
2222 () if options is None else options,
2223 maximum_concurrent_rpcs,
2224 compression,
2225 xds,
2226 )
2229@contextlib.contextmanager
2230def _create_servicer_context(rpc_event, state, request_deserializer):
2231 from grpc import _server # pylint: disable=cyclic-import
2233 context = _server._Context(rpc_event, state, request_deserializer)
2234 yield context
2235 context._finalize_state() # pylint: disable=protected-access
2238@enum.unique
2239class Compression(enum.IntEnum):
2240 """Indicates the compression method to be used for an RPC.
2242 Attributes:
2243 NoCompression: Do not use compression algorithm.
2244 Deflate: Use "Deflate" compression algorithm.
2245 Gzip: Use "Gzip" compression algorithm.
2246 """
2248 NoCompression = _compression.NoCompression
2249 Deflate = _compression.Deflate
2250 Gzip = _compression.Gzip
2253################################### __all__ #################################
2255__all__ = (
2256 "FutureTimeoutError",
2257 "FutureCancelledError",
2258 "Future",
2259 "ChannelConnectivity",
2260 "StatusCode",
2261 "Status",
2262 "RpcError",
2263 "RpcContext",
2264 "Call",
2265 "ChannelCredentials",
2266 "CallCredentials",
2267 "AuthMetadataContext",
2268 "AuthMetadataPluginCallback",
2269 "AuthMetadataPlugin",
2270 "Compression",
2271 "ClientCallDetails",
2272 "ServerCertificateConfiguration",
2273 "ServerCredentials",
2274 "LocalConnectionType",
2275 "UnaryUnaryMultiCallable",
2276 "UnaryStreamMultiCallable",
2277 "StreamUnaryMultiCallable",
2278 "StreamStreamMultiCallable",
2279 "UnaryUnaryClientInterceptor",
2280 "UnaryStreamClientInterceptor",
2281 "StreamUnaryClientInterceptor",
2282 "StreamStreamClientInterceptor",
2283 "Channel",
2284 "ServicerContext",
2285 "RpcMethodHandler",
2286 "HandlerCallDetails",
2287 "GenericRpcHandler",
2288 "ServiceRpcHandler",
2289 "Server",
2290 "ServerInterceptor",
2291 "unary_unary_rpc_method_handler",
2292 "unary_stream_rpc_method_handler",
2293 "stream_unary_rpc_method_handler",
2294 "stream_stream_rpc_method_handler",
2295 "method_handlers_generic_handler",
2296 "ssl_channel_credentials",
2297 "metadata_call_credentials",
2298 "access_token_call_credentials",
2299 "composite_call_credentials",
2300 "composite_channel_credentials",
2301 "compute_engine_channel_credentials",
2302 "local_channel_credentials",
2303 "local_server_credentials",
2304 "alts_channel_credentials",
2305 "alts_server_credentials",
2306 "ssl_server_credentials",
2307 "ssl_server_certificate_configuration",
2308 "dynamic_ssl_server_credentials",
2309 "channel_ready_future",
2310 "insecure_channel",
2311 "secure_channel",
2312 "intercept_channel",
2313 "server",
2314 "protos",
2315 "services",
2316 "protos_and_services",
2317 "xds_channel_credentials",
2318 "xds_server_credentials",
2319 "insecure_server_credentials",
2320)
2322############################### Extension Shims ################################
2324# Here to maintain backwards compatibility; avoid using these in new code!
2325try:
2326 import grpc_tools
2328 sys.modules.update({"grpc.tools": grpc_tools})
2329except ImportError:
2330 pass
2331try:
2332 import grpc_health
2334 sys.modules.update({"grpc.health": grpc_health})
2335except ImportError:
2336 pass
2337try:
2338 import grpc_reflection
2340 sys.modules.update({"grpc.reflection": grpc_reflection})
2341except ImportError:
2342 pass
2344# Prevents import order issue in the case of renamed path.
2345if sys.version_info >= (3, 6) and __name__ == "grpc":
2346 from grpc import aio # pylint: disable=ungrouped-imports
2348 sys.modules.update({"grpc.aio": aio})