Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/grpc/__init__.py: 69%
372 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:37 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:37 +0000
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, method, request_serializer=None, response_deserializer=None
1004 ):
1005 """Creates a UnaryUnaryMultiCallable for a unary-unary method.
1007 Args:
1008 method: The name of the RPC method.
1009 request_serializer: Optional :term:`serializer` for serializing the request
1010 message. Request goes unserialized in case None is passed.
1011 response_deserializer: Optional :term:`deserializer` for deserializing the
1012 response message. Response goes undeserialized in case None
1013 is passed.
1015 Returns:
1016 A UnaryUnaryMultiCallable value for the named unary-unary method.
1017 """
1018 raise NotImplementedError()
1020 @abc.abstractmethod
1021 def unary_stream(
1022 self, method, request_serializer=None, response_deserializer=None
1023 ):
1024 """Creates a UnaryStreamMultiCallable for a unary-stream method.
1026 Args:
1027 method: The name of the RPC method.
1028 request_serializer: Optional :term:`serializer` for serializing the request
1029 message. Request goes unserialized in case None is passed.
1030 response_deserializer: Optional :term:`deserializer` for deserializing the
1031 response message. Response goes undeserialized in case None is
1032 passed.
1034 Returns:
1035 A UnaryStreamMultiCallable value for the name unary-stream method.
1036 """
1037 raise NotImplementedError()
1039 @abc.abstractmethod
1040 def stream_unary(
1041 self, method, request_serializer=None, response_deserializer=None
1042 ):
1043 """Creates a StreamUnaryMultiCallable for a stream-unary method.
1045 Args:
1046 method: The name of the RPC method.
1047 request_serializer: Optional :term:`serializer` for serializing the request
1048 message. Request goes unserialized in case None is passed.
1049 response_deserializer: Optional :term:`deserializer` for deserializing the
1050 response message. Response goes undeserialized in case None is
1051 passed.
1053 Returns:
1054 A StreamUnaryMultiCallable value for the named stream-unary method.
1055 """
1056 raise NotImplementedError()
1058 @abc.abstractmethod
1059 def stream_stream(
1060 self, method, request_serializer=None, response_deserializer=None
1061 ):
1062 """Creates a StreamStreamMultiCallable for a stream-stream method.
1064 Args:
1065 method: The name of the RPC method.
1066 request_serializer: Optional :term:`serializer` for serializing the request
1067 message. Request goes unserialized in case None is passed.
1068 response_deserializer: Optional :term:`deserializer` for deserializing the
1069 response message. Response goes undeserialized in case None
1070 is passed.
1072 Returns:
1073 A StreamStreamMultiCallable value for the named stream-stream method.
1074 """
1075 raise NotImplementedError()
1077 @abc.abstractmethod
1078 def close(self):
1079 """Closes this Channel and releases all resources held by it.
1081 Closing the Channel will immediately terminate all RPCs active with the
1082 Channel and it is not valid to invoke new RPCs with the Channel.
1084 This method is idempotent.
1085 """
1086 raise NotImplementedError()
1088 def __enter__(self):
1089 """Enters the runtime context related to the channel object."""
1090 raise NotImplementedError()
1092 def __exit__(self, exc_type, exc_val, exc_tb):
1093 """Exits the runtime context related to the channel object."""
1094 raise NotImplementedError()
1097########################## Service-Side Context ##############################
1100class ServicerContext(RpcContext, metaclass=abc.ABCMeta):
1101 """A context object passed to method implementations."""
1103 @abc.abstractmethod
1104 def invocation_metadata(self):
1105 """Accesses the metadata sent by the client.
1107 Returns:
1108 The invocation :term:`metadata`.
1109 """
1110 raise NotImplementedError()
1112 @abc.abstractmethod
1113 def peer(self):
1114 """Identifies the peer that invoked the RPC being serviced.
1116 Returns:
1117 A string identifying the peer that invoked the RPC being serviced.
1118 The string format is determined by gRPC runtime.
1119 """
1120 raise NotImplementedError()
1122 @abc.abstractmethod
1123 def peer_identities(self):
1124 """Gets one or more peer identity(s).
1126 Equivalent to
1127 servicer_context.auth_context().get(servicer_context.peer_identity_key())
1129 Returns:
1130 An iterable of the identities, or None if the call is not
1131 authenticated. Each identity is returned as a raw bytes type.
1132 """
1133 raise NotImplementedError()
1135 @abc.abstractmethod
1136 def peer_identity_key(self):
1137 """The auth property used to identify the peer.
1139 For example, "x509_common_name" or "x509_subject_alternative_name" are
1140 used to identify an SSL peer.
1142 Returns:
1143 The auth property (string) that indicates the
1144 peer identity, or None if the call is not authenticated.
1145 """
1146 raise NotImplementedError()
1148 @abc.abstractmethod
1149 def auth_context(self):
1150 """Gets the auth context for the call.
1152 Returns:
1153 A map of strings to an iterable of bytes for each auth property.
1154 """
1155 raise NotImplementedError()
1157 def set_compression(self, compression):
1158 """Set the compression algorithm to be used for the entire call.
1160 Args:
1161 compression: An element of grpc.compression, e.g.
1162 grpc.compression.Gzip.
1163 """
1164 raise NotImplementedError()
1166 @abc.abstractmethod
1167 def send_initial_metadata(self, initial_metadata):
1168 """Sends the initial metadata value to the client.
1170 This method need not be called by implementations if they have no
1171 metadata to add to what the gRPC runtime will transmit.
1173 Args:
1174 initial_metadata: The initial :term:`metadata`.
1175 """
1176 raise NotImplementedError()
1178 @abc.abstractmethod
1179 def set_trailing_metadata(self, trailing_metadata):
1180 """Sets the trailing metadata for the RPC.
1182 Sets the trailing metadata to be sent upon completion of the RPC.
1184 If this method is invoked multiple times throughout the lifetime of an
1185 RPC, the value supplied in the final invocation will be the value sent
1186 over the wire.
1188 This method need not be called by implementations if they have no
1189 metadata to add to what the gRPC runtime will transmit.
1191 Args:
1192 trailing_metadata: The trailing :term:`metadata`.
1193 """
1194 raise NotImplementedError()
1196 def trailing_metadata(self):
1197 """Access value to be used as trailing metadata upon RPC completion.
1199 This is an EXPERIMENTAL API.
1201 Returns:
1202 The trailing :term:`metadata` for the RPC.
1203 """
1204 raise NotImplementedError()
1206 @abc.abstractmethod
1207 def abort(self, code, details):
1208 """Raises an exception to terminate the RPC with a non-OK status.
1210 The code and details passed as arguments will supercede any existing
1211 ones.
1213 Args:
1214 code: A StatusCode object to be sent to the client.
1215 It must not be StatusCode.OK.
1216 details: A UTF-8-encodable string to be sent to the client upon
1217 termination of the RPC.
1219 Raises:
1220 Exception: An exception is always raised to signal the abortion the
1221 RPC to the gRPC runtime.
1222 """
1223 raise NotImplementedError()
1225 @abc.abstractmethod
1226 def abort_with_status(self, status):
1227 """Raises an exception to terminate the RPC with a non-OK status.
1229 The status passed as argument will supercede any existing status code,
1230 status message and trailing metadata.
1232 This is an EXPERIMENTAL API.
1234 Args:
1235 status: A grpc.Status object. The status code in it must not be
1236 StatusCode.OK.
1238 Raises:
1239 Exception: An exception is always raised to signal the abortion the
1240 RPC to the gRPC runtime.
1241 """
1242 raise NotImplementedError()
1244 @abc.abstractmethod
1245 def set_code(self, code):
1246 """Sets the value to be used as status code upon RPC completion.
1248 This method need not be called by method implementations if they wish
1249 the gRPC runtime to determine the status code of the RPC.
1251 Args:
1252 code: A StatusCode object to be sent to the client.
1253 """
1254 raise NotImplementedError()
1256 @abc.abstractmethod
1257 def set_details(self, details):
1258 """Sets the value to be used as detail string upon RPC completion.
1260 This method need not be called by method implementations if they have
1261 no details to transmit.
1263 Args:
1264 details: A UTF-8-encodable string to be sent to the client upon
1265 termination of the RPC.
1266 """
1267 raise NotImplementedError()
1269 def code(self):
1270 """Accesses the value to be used as status code upon RPC completion.
1272 This is an EXPERIMENTAL API.
1274 Returns:
1275 The StatusCode value for the RPC.
1276 """
1277 raise NotImplementedError()
1279 def details(self):
1280 """Accesses the value to be used as detail string upon RPC completion.
1282 This is an EXPERIMENTAL API.
1284 Returns:
1285 The details string of the RPC.
1286 """
1287 raise NotImplementedError()
1289 def disable_next_message_compression(self):
1290 """Disables compression for the next response message.
1292 This method will override any compression configuration set during
1293 server creation or set on the call.
1294 """
1295 raise NotImplementedError()
1298##################### Service-Side Handler Interfaces ########################
1301class RpcMethodHandler(abc.ABC):
1302 """An implementation of a single RPC method.
1304 Attributes:
1305 request_streaming: Whether the RPC supports exactly one request message
1306 or any arbitrary number of request messages.
1307 response_streaming: Whether the RPC supports exactly one response message
1308 or any arbitrary number of response messages.
1309 request_deserializer: A callable :term:`deserializer` that accepts a byte string and
1310 returns an object suitable to be passed to this object's business
1311 logic, or None to indicate that this object's business logic should be
1312 passed the raw request bytes.
1313 response_serializer: A callable :term:`serializer` that accepts an object produced
1314 by this object's business logic and returns a byte string, or None to
1315 indicate that the byte strings produced by this object's business logic
1316 should be transmitted on the wire as they are.
1317 unary_unary: This object's application-specific business logic as a
1318 callable value that takes a request value and a ServicerContext object
1319 and returns a response value. Only non-None if both request_streaming
1320 and response_streaming are False.
1321 unary_stream: This object's application-specific business logic as a
1322 callable value that takes a request value and a ServicerContext object
1323 and returns an iterator of response values. Only non-None if
1324 request_streaming is False and response_streaming is True.
1325 stream_unary: This object's application-specific business logic as a
1326 callable value that takes an iterator of request values and a
1327 ServicerContext object and returns a response value. Only non-None if
1328 request_streaming is True and response_streaming is False.
1329 stream_stream: This object's application-specific business logic as a
1330 callable value that takes an iterator of request values and a
1331 ServicerContext object and returns an iterator of response values.
1332 Only non-None if request_streaming and response_streaming are both
1333 True.
1334 """
1337class HandlerCallDetails(abc.ABC):
1338 """Describes an RPC that has just arrived for service.
1340 Attributes:
1341 method: The method name of the RPC.
1342 invocation_metadata: The :term:`metadata` sent by the client.
1343 """
1346class GenericRpcHandler(abc.ABC):
1347 """An implementation of arbitrarily many RPC methods."""
1349 @abc.abstractmethod
1350 def service(self, handler_call_details):
1351 """Returns the handler for servicing the RPC.
1353 Args:
1354 handler_call_details: A HandlerCallDetails describing the RPC.
1356 Returns:
1357 An RpcMethodHandler with which the RPC may be serviced if the
1358 implementation chooses to service this RPC, or None otherwise.
1359 """
1360 raise NotImplementedError()
1363class ServiceRpcHandler(GenericRpcHandler, metaclass=abc.ABCMeta):
1364 """An implementation of RPC methods belonging to a service.
1366 A service handles RPC methods with structured names of the form
1367 '/Service.Name/Service.Method', where 'Service.Name' is the value
1368 returned by service_name(), and 'Service.Method' is the method
1369 name. A service can have multiple method names, but only a single
1370 service name.
1371 """
1373 @abc.abstractmethod
1374 def service_name(self):
1375 """Returns this service's name.
1377 Returns:
1378 The service name.
1379 """
1380 raise NotImplementedError()
1383#################### Service-Side Interceptor Interfaces #####################
1386class ServerInterceptor(abc.ABC):
1387 """Affords intercepting incoming RPCs on the service-side."""
1389 @abc.abstractmethod
1390 def intercept_service(self, continuation, handler_call_details):
1391 """Intercepts incoming RPCs before handing them over to a handler.
1393 Args:
1394 continuation: A function that takes a HandlerCallDetails and
1395 proceeds to invoke the next interceptor in the chain, if any,
1396 or the RPC handler lookup logic, with the call details passed
1397 as an argument, and returns an RpcMethodHandler instance if
1398 the RPC is considered serviced, or None otherwise.
1399 handler_call_details: A HandlerCallDetails describing the RPC.
1401 Returns:
1402 An RpcMethodHandler with which the RPC may be serviced if the
1403 interceptor chooses to service this RPC, or None otherwise.
1404 """
1405 raise NotImplementedError()
1408############################# Server Interface ###############################
1411class Server(abc.ABC):
1412 """Services RPCs."""
1414 @abc.abstractmethod
1415 def add_generic_rpc_handlers(self, generic_rpc_handlers):
1416 """Registers GenericRpcHandlers with this Server.
1418 This method is only safe to call before the server is started.
1420 Args:
1421 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1422 used to service RPCs.
1423 """
1424 raise NotImplementedError()
1426 @abc.abstractmethod
1427 def add_insecure_port(self, address):
1428 """Opens an insecure port for accepting RPCs.
1430 This method may only be called before starting the server.
1432 Args:
1433 address: The address for which to open a port. If the port is 0,
1434 or not specified in the address, then gRPC runtime will choose a port.
1436 Returns:
1437 An integer port on which server will accept RPC requests.
1438 """
1439 raise NotImplementedError()
1441 @abc.abstractmethod
1442 def add_secure_port(self, address, server_credentials):
1443 """Opens a secure port for accepting RPCs.
1445 This method may only be called before starting the server.
1447 Args:
1448 address: The address for which to open a port.
1449 if the port is 0, or not specified in the address, then gRPC
1450 runtime will choose a port.
1451 server_credentials: A ServerCredentials object.
1453 Returns:
1454 An integer port on which server will accept RPC requests.
1455 """
1456 raise NotImplementedError()
1458 @abc.abstractmethod
1459 def start(self):
1460 """Starts this Server.
1462 This method may only be called once. (i.e. it is not idempotent).
1463 """
1464 raise NotImplementedError()
1466 @abc.abstractmethod
1467 def stop(self, grace):
1468 """Stops this Server.
1470 This method immediately stop service of new RPCs in all cases.
1472 If a grace period is specified, this method returns immediately
1473 and all RPCs active at the end of the grace period are aborted.
1474 If a grace period is not specified (by passing None for `grace`),
1475 all existing RPCs are aborted immediately and this method
1476 blocks until the last RPC handler terminates.
1478 This method is idempotent and may be called at any time.
1479 Passing a smaller grace value in a subsequent call will have
1480 the effect of stopping the Server sooner (passing None will
1481 have the effect of stopping the server immediately). Passing
1482 a larger grace value in a subsequent call *will not* have the
1483 effect of stopping the server later (i.e. the most restrictive
1484 grace value is used).
1486 Args:
1487 grace: A duration of time in seconds or None.
1489 Returns:
1490 A threading.Event that will be set when this Server has completely
1491 stopped, i.e. when running RPCs either complete or are aborted and
1492 all handlers have terminated.
1493 """
1494 raise NotImplementedError()
1496 def wait_for_termination(self, timeout=None):
1497 """Block current thread until the server stops.
1499 This is an EXPERIMENTAL API.
1501 The wait will not consume computational resources during blocking, and
1502 it will block until one of the two following conditions are met:
1504 1) The server is stopped or terminated;
1505 2) A timeout occurs if timeout is not `None`.
1507 The timeout argument works in the same way as `threading.Event.wait()`.
1508 https://docs.python.org/3/library/threading.html#threading.Event.wait
1510 Args:
1511 timeout: A floating point number specifying a timeout for the
1512 operation in seconds.
1514 Returns:
1515 A bool indicates if the operation times out.
1516 """
1517 raise NotImplementedError()
1520################################# Functions ################################
1523def unary_unary_rpc_method_handler(
1524 behavior, request_deserializer=None, response_serializer=None
1525):
1526 """Creates an RpcMethodHandler for a unary-unary RPC method.
1528 Args:
1529 behavior: The implementation of an RPC that accepts one request
1530 and returns one response.
1531 request_deserializer: An optional :term:`deserializer` for request deserialization.
1532 response_serializer: An optional :term:`serializer` for response serialization.
1534 Returns:
1535 An RpcMethodHandler object that is typically used by grpc.Server.
1536 """
1537 from grpc import _utilities # pylint: disable=cyclic-import
1539 return _utilities.RpcMethodHandler(
1540 False,
1541 False,
1542 request_deserializer,
1543 response_serializer,
1544 behavior,
1545 None,
1546 None,
1547 None,
1548 )
1551def unary_stream_rpc_method_handler(
1552 behavior, request_deserializer=None, response_serializer=None
1553):
1554 """Creates an RpcMethodHandler for a unary-stream RPC method.
1556 Args:
1557 behavior: The implementation of an RPC that accepts one request
1558 and returns an iterator of response values.
1559 request_deserializer: An optional :term:`deserializer` for request deserialization.
1560 response_serializer: An optional :term:`serializer` for response serialization.
1562 Returns:
1563 An RpcMethodHandler object that is typically used by grpc.Server.
1564 """
1565 from grpc import _utilities # pylint: disable=cyclic-import
1567 return _utilities.RpcMethodHandler(
1568 False,
1569 True,
1570 request_deserializer,
1571 response_serializer,
1572 None,
1573 behavior,
1574 None,
1575 None,
1576 )
1579def stream_unary_rpc_method_handler(
1580 behavior, request_deserializer=None, response_serializer=None
1581):
1582 """Creates an RpcMethodHandler for a stream-unary RPC method.
1584 Args:
1585 behavior: The implementation of an RPC that accepts an iterator of
1586 request values and returns a single response value.
1587 request_deserializer: An optional :term:`deserializer` for request deserialization.
1588 response_serializer: An optional :term:`serializer` for response serialization.
1590 Returns:
1591 An RpcMethodHandler object that is typically used by grpc.Server.
1592 """
1593 from grpc import _utilities # pylint: disable=cyclic-import
1595 return _utilities.RpcMethodHandler(
1596 True,
1597 False,
1598 request_deserializer,
1599 response_serializer,
1600 None,
1601 None,
1602 behavior,
1603 None,
1604 )
1607def stream_stream_rpc_method_handler(
1608 behavior, request_deserializer=None, response_serializer=None
1609):
1610 """Creates an RpcMethodHandler for a stream-stream RPC method.
1612 Args:
1613 behavior: The implementation of an RPC that accepts an iterator of
1614 request values and returns an iterator of response values.
1615 request_deserializer: An optional :term:`deserializer` for request deserialization.
1616 response_serializer: An optional :term:`serializer` for response serialization.
1618 Returns:
1619 An RpcMethodHandler object that is typically used by grpc.Server.
1620 """
1621 from grpc import _utilities # pylint: disable=cyclic-import
1623 return _utilities.RpcMethodHandler(
1624 True,
1625 True,
1626 request_deserializer,
1627 response_serializer,
1628 None,
1629 None,
1630 None,
1631 behavior,
1632 )
1635def method_handlers_generic_handler(service, method_handlers):
1636 """Creates a GenericRpcHandler from RpcMethodHandlers.
1638 Args:
1639 service: The name of the service that is implemented by the
1640 method_handlers.
1641 method_handlers: A dictionary that maps method names to corresponding
1642 RpcMethodHandler.
1644 Returns:
1645 A GenericRpcHandler. This is typically added to the grpc.Server object
1646 with add_generic_rpc_handlers() before starting the server.
1647 """
1648 from grpc import _utilities # pylint: disable=cyclic-import
1650 return _utilities.DictionaryGenericHandler(service, method_handlers)
1653def ssl_channel_credentials(
1654 root_certificates=None, private_key=None, certificate_chain=None
1655):
1656 """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1658 Args:
1659 root_certificates: The PEM-encoded root certificates as a byte string,
1660 or None to retrieve them from a default location chosen by gRPC
1661 runtime.
1662 private_key: The PEM-encoded private key as a byte string, or None if no
1663 private key should be used.
1664 certificate_chain: The PEM-encoded certificate chain as a byte string
1665 to use or None if no certificate chain should be used.
1667 Returns:
1668 A ChannelCredentials for use with an SSL-enabled Channel.
1669 """
1670 return ChannelCredentials(
1671 _cygrpc.SSLChannelCredentials(
1672 root_certificates, private_key, certificate_chain
1673 )
1674 )
1677def xds_channel_credentials(fallback_credentials=None):
1678 """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL
1679 API.
1681 Args:
1682 fallback_credentials: Credentials to use in case it is not possible to
1683 establish a secure connection via xDS. If no fallback_credentials
1684 argument is supplied, a default SSLChannelCredentials is used.
1685 """
1686 fallback_credentials = (
1687 ssl_channel_credentials()
1688 if fallback_credentials is None
1689 else fallback_credentials
1690 )
1691 return ChannelCredentials(
1692 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials)
1693 )
1696def metadata_call_credentials(metadata_plugin, name=None):
1697 """Construct CallCredentials from an AuthMetadataPlugin.
1699 Args:
1700 metadata_plugin: An AuthMetadataPlugin to use for authentication.
1701 name: An optional name for the plugin.
1703 Returns:
1704 A CallCredentials.
1705 """
1706 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1708 return _plugin_wrapping.metadata_plugin_call_credentials(
1709 metadata_plugin, name
1710 )
1713def access_token_call_credentials(access_token):
1714 """Construct CallCredentials from an access token.
1716 Args:
1717 access_token: A string to place directly in the http request
1718 authorization header, for example
1719 "authorization: Bearer <access_token>".
1721 Returns:
1722 A CallCredentials.
1723 """
1724 from grpc import _auth # pylint: disable=cyclic-import
1725 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1727 return _plugin_wrapping.metadata_plugin_call_credentials(
1728 _auth.AccessTokenAuthMetadataPlugin(access_token), None
1729 )
1732def composite_call_credentials(*call_credentials):
1733 """Compose multiple CallCredentials to make a new CallCredentials.
1735 Args:
1736 *call_credentials: At least two CallCredentials objects.
1738 Returns:
1739 A CallCredentials object composed of the given CallCredentials objects.
1740 """
1741 return CallCredentials(
1742 _cygrpc.CompositeCallCredentials(
1743 tuple(
1744 single_call_credentials._credentials
1745 for single_call_credentials in call_credentials
1746 )
1747 )
1748 )
1751def composite_channel_credentials(channel_credentials, *call_credentials):
1752 """Compose a ChannelCredentials and one or more CallCredentials objects.
1754 Args:
1755 channel_credentials: A ChannelCredentials object.
1756 *call_credentials: One or more CallCredentials objects.
1758 Returns:
1759 A ChannelCredentials composed of the given ChannelCredentials and
1760 CallCredentials objects.
1761 """
1762 return ChannelCredentials(
1763 _cygrpc.CompositeChannelCredentials(
1764 tuple(
1765 single_call_credentials._credentials
1766 for single_call_credentials in call_credentials
1767 ),
1768 channel_credentials._credentials,
1769 )
1770 )
1773def ssl_server_credentials(
1774 private_key_certificate_chain_pairs,
1775 root_certificates=None,
1776 require_client_auth=False,
1777):
1778 """Creates a ServerCredentials for use with an SSL-enabled Server.
1780 Args:
1781 private_key_certificate_chain_pairs: A list of pairs of the form
1782 [PEM-encoded private key, PEM-encoded certificate chain].
1783 root_certificates: An optional byte string of PEM-encoded client root
1784 certificates that the server will use to verify client authentication.
1785 If omitted, require_client_auth must also be False.
1786 require_client_auth: A boolean indicating whether or not to require
1787 clients to be authenticated. May only be True if root_certificates
1788 is not None.
1790 Returns:
1791 A ServerCredentials for use with an SSL-enabled Server. Typically, this
1792 object is an argument to add_secure_port() method during server setup.
1793 """
1794 if not private_key_certificate_chain_pairs:
1795 raise ValueError(
1796 "At least one private key-certificate chain pair is required!"
1797 )
1798 elif require_client_auth and root_certificates is None:
1799 raise ValueError(
1800 "Illegal to require client auth without providing root"
1801 " certificates!"
1802 )
1803 else:
1804 return ServerCredentials(
1805 _cygrpc.server_credentials_ssl(
1806 root_certificates,
1807 [
1808 _cygrpc.SslPemKeyCertPair(key, pem)
1809 for key, pem in private_key_certificate_chain_pairs
1810 ],
1811 require_client_auth,
1812 )
1813 )
1816def xds_server_credentials(fallback_credentials):
1817 """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL
1818 API.
1820 Args:
1821 fallback_credentials: Credentials to use in case it is not possible to
1822 establish a secure connection via xDS. No default value is provided.
1823 """
1824 return ServerCredentials(
1825 _cygrpc.xds_server_credentials(fallback_credentials._credentials)
1826 )
1829def insecure_server_credentials():
1830 """Creates a credentials object directing the server to use no credentials.
1831 This is an EXPERIMENTAL API.
1833 This object cannot be used directly in a call to `add_secure_port`.
1834 Instead, it should be used to construct other credentials objects, e.g.
1835 with xds_server_credentials.
1836 """
1837 return ServerCredentials(_cygrpc.insecure_server_credentials())
1840def ssl_server_certificate_configuration(
1841 private_key_certificate_chain_pairs, root_certificates=None
1842):
1843 """Creates a ServerCertificateConfiguration for use with a Server.
1845 Args:
1846 private_key_certificate_chain_pairs: A collection of pairs of
1847 the form [PEM-encoded private key, PEM-encoded certificate
1848 chain].
1849 root_certificates: An optional byte string of PEM-encoded client root
1850 certificates that the server will use to verify client authentication.
1852 Returns:
1853 A ServerCertificateConfiguration that can be returned in the certificate
1854 configuration fetching callback.
1855 """
1856 if private_key_certificate_chain_pairs:
1857 return ServerCertificateConfiguration(
1858 _cygrpc.server_certificate_config_ssl(
1859 root_certificates,
1860 [
1861 _cygrpc.SslPemKeyCertPair(key, pem)
1862 for key, pem in private_key_certificate_chain_pairs
1863 ],
1864 )
1865 )
1866 else:
1867 raise ValueError(
1868 "At least one private key-certificate chain pair is required!"
1869 )
1872def dynamic_ssl_server_credentials(
1873 initial_certificate_configuration,
1874 certificate_configuration_fetcher,
1875 require_client_authentication=False,
1876):
1877 """Creates a ServerCredentials for use with an SSL-enabled Server.
1879 Args:
1880 initial_certificate_configuration (ServerCertificateConfiguration): The
1881 certificate configuration with which the server will be initialized.
1882 certificate_configuration_fetcher (callable): A callable that takes no
1883 arguments and should return a ServerCertificateConfiguration to
1884 replace the server's current certificate, or None for no change
1885 (i.e., the server will continue its current certificate
1886 config). The library will call this callback on *every* new
1887 client connection before starting the TLS handshake with the
1888 client, thus allowing the user application to optionally
1889 return a new ServerCertificateConfiguration that the server will then
1890 use for the handshake.
1891 require_client_authentication: A boolean indicating whether or not to
1892 require clients to be authenticated.
1894 Returns:
1895 A ServerCredentials.
1896 """
1897 return ServerCredentials(
1898 _cygrpc.server_credentials_ssl_dynamic_cert_config(
1899 initial_certificate_configuration,
1900 certificate_configuration_fetcher,
1901 require_client_authentication,
1902 )
1903 )
1906@enum.unique
1907class LocalConnectionType(enum.Enum):
1908 """Types of local connection for local credential creation.
1910 Attributes:
1911 UDS: Unix domain socket connections
1912 LOCAL_TCP: Local TCP connections.
1913 """
1915 UDS = _cygrpc.LocalConnectionType.uds
1916 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
1919def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1920 """Creates a local ChannelCredentials used for local connections.
1922 This is an EXPERIMENTAL API.
1924 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1925 also UDS connections.
1927 The connections created by local channel credentials are not
1928 encrypted, but will be checked if they are local or not.
1929 The UDS connections are considered secure by providing peer authentication
1930 and data confidentiality while TCP connections are considered insecure.
1932 It is allowed to transmit call credentials over connections created by
1933 local channel credentials.
1935 Local channel credentials are useful for 1) eliminating insecure_channel usage;
1936 2) enable unit testing for call credentials without setting up secrets.
1938 Args:
1939 local_connect_type: Local connection type (either
1940 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1942 Returns:
1943 A ChannelCredentials for use with a local Channel
1944 """
1945 return ChannelCredentials(
1946 _cygrpc.channel_credentials_local(local_connect_type.value)
1947 )
1950def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1951 """Creates a local ServerCredentials used for local connections.
1953 This is an EXPERIMENTAL API.
1955 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1956 also UDS connections.
1958 The connections created by local server credentials are not
1959 encrypted, but will be checked if they are local or not.
1960 The UDS connections are considered secure by providing peer authentication
1961 and data confidentiality while TCP connections are considered insecure.
1963 It is allowed to transmit call credentials over connections created by local
1964 server credentials.
1966 Local server credentials are useful for 1) eliminating insecure_channel usage;
1967 2) enable unit testing for call credentials without setting up secrets.
1969 Args:
1970 local_connect_type: Local connection type (either
1971 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1973 Returns:
1974 A ServerCredentials for use with a local Server
1975 """
1976 return ServerCredentials(
1977 _cygrpc.server_credentials_local(local_connect_type.value)
1978 )
1981def alts_channel_credentials(service_accounts=None):
1982 """Creates a ChannelCredentials for use with an ALTS-enabled Channel.
1984 This is an EXPERIMENTAL API.
1985 ALTS credentials API can only be used in GCP environment as it relies on
1986 handshaker service being available. For more info about ALTS see
1987 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1989 Args:
1990 service_accounts: A list of server identities accepted by the client.
1991 If target service accounts are provided and none of them matches the
1992 peer identity of the server, handshake will fail. The arg can be empty
1993 if the client does not have any information about trusted server
1994 identity.
1995 Returns:
1996 A ChannelCredentials for use with an ALTS-enabled Channel
1997 """
1998 return ChannelCredentials(
1999 _cygrpc.channel_credentials_alts(service_accounts or [])
2000 )
2003def alts_server_credentials():
2004 """Creates a ServerCredentials for use with an ALTS-enabled connection.
2006 This is an EXPERIMENTAL API.
2007 ALTS credentials API can only be used in GCP environment as it relies on
2008 handshaker service being available. For more info about ALTS see
2009 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2011 Returns:
2012 A ServerCredentials for use with an ALTS-enabled Server
2013 """
2014 return ServerCredentials(_cygrpc.server_credentials_alts())
2017def compute_engine_channel_credentials(call_credentials):
2018 """Creates a compute engine channel credential.
2020 This credential can only be used in a GCP environment as it relies on
2021 a handshaker service. For more info about ALTS, see
2022 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2024 This channel credential is expected to be used as part of a composite
2025 credential in conjunction with a call credentials that authenticates the
2026 VM's default service account. If used with any other sort of call
2027 credential, the connection may suddenly and unexpectedly begin failing RPCs.
2028 """
2029 return ChannelCredentials(
2030 _cygrpc.channel_credentials_compute_engine(
2031 call_credentials._credentials
2032 )
2033 )
2036def channel_ready_future(channel):
2037 """Creates a Future that tracks when a Channel is ready.
2039 Cancelling the Future does not affect the channel's state machine.
2040 It merely decouples the Future from channel state machine.
2042 Args:
2043 channel: A Channel object.
2045 Returns:
2046 A Future object that matures when the channel connectivity is
2047 ChannelConnectivity.READY.
2048 """
2049 from grpc import _utilities # pylint: disable=cyclic-import
2051 return _utilities.channel_ready_future(channel)
2054def insecure_channel(target, options=None, compression=None):
2055 """Creates an insecure Channel to a server.
2057 The returned Channel is thread-safe.
2059 Args:
2060 target: The server address
2061 options: An optional list of key-value pairs (:term:`channel_arguments`
2062 in gRPC Core runtime) to configure the channel.
2063 compression: An optional value indicating the compression method to be
2064 used over the lifetime of the channel.
2066 Returns:
2067 A Channel.
2068 """
2069 from grpc import _channel # pylint: disable=cyclic-import
2071 return _channel.Channel(
2072 target, () if options is None else options, None, compression
2073 )
2076def secure_channel(target, credentials, options=None, compression=None):
2077 """Creates a secure Channel to a server.
2079 The returned Channel is thread-safe.
2081 Args:
2082 target: The server address.
2083 credentials: A ChannelCredentials instance.
2084 options: An optional list of key-value pairs (:term:`channel_arguments`
2085 in gRPC Core runtime) to configure the channel.
2086 compression: An optional value indicating the compression method to be
2087 used over the lifetime of the channel.
2089 Returns:
2090 A Channel.
2091 """
2092 from grpc import _channel # pylint: disable=cyclic-import
2093 from grpc.experimental import _insecure_channel_credentials
2095 if credentials._credentials is _insecure_channel_credentials:
2096 raise ValueError(
2097 "secure_channel cannot be called with insecure credentials."
2098 + " Call insecure_channel instead."
2099 )
2100 return _channel.Channel(
2101 target,
2102 () if options is None else options,
2103 credentials._credentials,
2104 compression,
2105 )
2108def intercept_channel(channel, *interceptors):
2109 """Intercepts a channel through a set of interceptors.
2111 Args:
2112 channel: A Channel.
2113 interceptors: Zero or more objects of type
2114 UnaryUnaryClientInterceptor,
2115 UnaryStreamClientInterceptor,
2116 StreamUnaryClientInterceptor, or
2117 StreamStreamClientInterceptor.
2118 Interceptors are given control in the order they are listed.
2120 Returns:
2121 A Channel that intercepts each invocation via the provided interceptors.
2123 Raises:
2124 TypeError: If interceptor does not derive from any of
2125 UnaryUnaryClientInterceptor,
2126 UnaryStreamClientInterceptor,
2127 StreamUnaryClientInterceptor, or
2128 StreamStreamClientInterceptor.
2129 """
2130 from grpc import _interceptor # pylint: disable=cyclic-import
2132 return _interceptor.intercept_channel(channel, *interceptors)
2135def server(
2136 thread_pool,
2137 handlers=None,
2138 interceptors=None,
2139 options=None,
2140 maximum_concurrent_rpcs=None,
2141 compression=None,
2142 xds=False,
2143):
2144 """Creates a Server with which RPCs can be serviced.
2146 Args:
2147 thread_pool: A futures.ThreadPoolExecutor to be used by the Server
2148 to execute RPC handlers.
2149 handlers: An optional list of GenericRpcHandlers used for executing RPCs.
2150 More handlers may be added by calling add_generic_rpc_handlers any time
2151 before the server is started.
2152 interceptors: An optional list of ServerInterceptor objects that observe
2153 and optionally manipulate the incoming RPCs before handing them over to
2154 handlers. The interceptors are given control in the order they are
2155 specified. This is an EXPERIMENTAL API.
2156 options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
2157 to configure the channel.
2158 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
2159 will service before returning RESOURCE_EXHAUSTED status, or None to
2160 indicate no limit.
2161 compression: An element of grpc.compression, e.g.
2162 grpc.compression.Gzip. This compression algorithm will be used for the
2163 lifetime of the server unless overridden.
2164 xds: If set to true, retrieves server configuration via xDS. This is an
2165 EXPERIMENTAL option.
2167 Returns:
2168 A Server object.
2169 """
2170 from grpc import _server # pylint: disable=cyclic-import
2172 return _server.create_server(
2173 thread_pool,
2174 () if handlers is None else handlers,
2175 () if interceptors is None else interceptors,
2176 () if options is None else options,
2177 maximum_concurrent_rpcs,
2178 compression,
2179 xds,
2180 )
2183@contextlib.contextmanager
2184def _create_servicer_context(rpc_event, state, request_deserializer):
2185 from grpc import _server # pylint: disable=cyclic-import
2187 context = _server._Context(rpc_event, state, request_deserializer)
2188 yield context
2189 context._finalize_state() # pylint: disable=protected-access
2192@enum.unique
2193class Compression(enum.IntEnum):
2194 """Indicates the compression method to be used for an RPC.
2196 Attributes:
2197 NoCompression: Do not use compression algorithm.
2198 Deflate: Use "Deflate" compression algorithm.
2199 Gzip: Use "Gzip" compression algorithm.
2200 """
2202 NoCompression = _compression.NoCompression
2203 Deflate = _compression.Deflate
2204 Gzip = _compression.Gzip
2207################################### __all__ #################################
2209__all__ = (
2210 "FutureTimeoutError",
2211 "FutureCancelledError",
2212 "Future",
2213 "ChannelConnectivity",
2214 "StatusCode",
2215 "Status",
2216 "RpcError",
2217 "RpcContext",
2218 "Call",
2219 "ChannelCredentials",
2220 "CallCredentials",
2221 "AuthMetadataContext",
2222 "AuthMetadataPluginCallback",
2223 "AuthMetadataPlugin",
2224 "Compression",
2225 "ClientCallDetails",
2226 "ServerCertificateConfiguration",
2227 "ServerCredentials",
2228 "LocalConnectionType",
2229 "UnaryUnaryMultiCallable",
2230 "UnaryStreamMultiCallable",
2231 "StreamUnaryMultiCallable",
2232 "StreamStreamMultiCallable",
2233 "UnaryUnaryClientInterceptor",
2234 "UnaryStreamClientInterceptor",
2235 "StreamUnaryClientInterceptor",
2236 "StreamStreamClientInterceptor",
2237 "Channel",
2238 "ServicerContext",
2239 "RpcMethodHandler",
2240 "HandlerCallDetails",
2241 "GenericRpcHandler",
2242 "ServiceRpcHandler",
2243 "Server",
2244 "ServerInterceptor",
2245 "unary_unary_rpc_method_handler",
2246 "unary_stream_rpc_method_handler",
2247 "stream_unary_rpc_method_handler",
2248 "stream_stream_rpc_method_handler",
2249 "method_handlers_generic_handler",
2250 "ssl_channel_credentials",
2251 "metadata_call_credentials",
2252 "access_token_call_credentials",
2253 "composite_call_credentials",
2254 "composite_channel_credentials",
2255 "compute_engine_channel_credentials",
2256 "local_channel_credentials",
2257 "local_server_credentials",
2258 "alts_channel_credentials",
2259 "alts_server_credentials",
2260 "ssl_server_credentials",
2261 "ssl_server_certificate_configuration",
2262 "dynamic_ssl_server_credentials",
2263 "channel_ready_future",
2264 "insecure_channel",
2265 "secure_channel",
2266 "intercept_channel",
2267 "server",
2268 "protos",
2269 "services",
2270 "protos_and_services",
2271 "xds_channel_credentials",
2272 "xds_server_credentials",
2273 "insecure_server_credentials",
2274)
2276############################### Extension Shims ################################
2278# Here to maintain backwards compatibility; avoid using these in new code!
2279try:
2280 import grpc_tools
2282 sys.modules.update({"grpc.tools": grpc_tools})
2283except ImportError:
2284 pass
2285try:
2286 import grpc_health
2288 sys.modules.update({"grpc.health": grpc_health})
2289except ImportError:
2290 pass
2291try:
2292 import grpc_reflection
2294 sys.modules.update({"grpc.reflection": grpc_reflection})
2295except ImportError:
2296 pass
2298# Prevents import order issue in the case of renamed path.
2299if sys.version_info >= (3, 6) and __name__ == "grpc":
2300 from grpc import aio # pylint: disable=ungrouped-imports
2302 sys.modules.update({"grpc.aio": aio})