Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/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
21import typing
22from typing import Any, Protocol
24from grpc import _compression
25from grpc._cython import cygrpc as _cygrpc
26from grpc._runtime_protos import protos
27from grpc._runtime_protos import protos_and_services
28from grpc._runtime_protos import services
30logging.getLogger(__name__).addHandler(logging.NullHandler())
32try:
33 # pylint: disable=ungrouped-imports
34 from grpc._grpcio_metadata import __version__
35except ImportError:
36 __version__ = "dev0"
38############################## Future Interface ###############################
41class FutureTimeoutError(Exception):
42 """Indicates that a method call on a Future timed out."""
45class FutureCancelledError(Exception):
46 """Indicates that the computation underlying a Future was cancelled."""
49class Future(abc.ABC):
50 """A representation of a computation in another control flow.
52 Computations represented by a Future may be yet to be begun,
53 may be ongoing, or may have already completed.
54 """
56 @abc.abstractmethod
57 def cancel(self):
58 """Attempts to cancel the computation.
60 This method does not block.
62 Returns:
63 bool:
64 Returns True if the computation was canceled.
66 Returns False under all other circumstances, for example:
68 1. computation has begun and could not be canceled.
69 2. computation has finished
70 3. computation is scheduled for execution and it is impossible
71 to determine its state without blocking.
72 """
73 raise NotImplementedError()
75 @abc.abstractmethod
76 def cancelled(self):
77 """Describes whether the computation was cancelled.
79 This method does not block.
81 Returns:
82 bool:
83 Returns True if the computation was cancelled before its result became
84 available.
86 Returns False under all other circumstances, for example:
88 1. computation was not cancelled.
89 2. computation's result is available.
90 """
91 raise NotImplementedError()
93 @abc.abstractmethod
94 def running(self):
95 """Describes whether the computation is taking place.
97 This method does not block.
99 Returns:
100 Returns True if the computation is scheduled for execution or
101 currently executing.
103 Returns False if the computation already executed or was cancelled.
104 """
105 raise NotImplementedError()
107 @abc.abstractmethod
108 def done(self):
109 """Describes whether the computation has taken place.
111 This method does not block.
113 Returns:
114 bool:
115 Returns True if the computation already executed or was cancelled.
116 Returns False if the computation is scheduled for execution or
117 currently executing.
118 This is exactly opposite of the running() method's result.
119 """
120 raise NotImplementedError()
122 @abc.abstractmethod
123 def result(self, timeout=None):
124 """Returns the result of the computation or raises its exception.
126 This method may return immediately or may block.
128 Args:
129 timeout: The length of time in seconds to wait for the computation to
130 finish or be cancelled. If None, the call will block until the
131 computations's termination.
133 Returns:
134 The return value of the computation.
136 Raises:
137 FutureTimeoutError: If a timeout value is passed and the computation
138 does not terminate within the allotted time.
139 FutureCancelledError: If the computation was cancelled.
140 Exception: If the computation raised an exception, this call will
141 raise the same exception.
142 """
143 raise NotImplementedError()
145 @abc.abstractmethod
146 def exception(self, timeout=None):
147 """Return the exception raised by the computation.
149 This method may return immediately or may block.
151 Args:
152 timeout: The length of time in seconds to wait for the computation to
153 terminate or be cancelled. If None, the call will block until the
154 computations's termination.
156 Returns:
157 The exception raised by the computation, or None if the computation
158 did not raise an exception.
160 Raises:
161 FutureTimeoutError: If a timeout value is passed and the computation
162 does not terminate within the allotted time.
163 FutureCancelledError: If the computation was cancelled.
164 """
165 raise NotImplementedError()
167 @abc.abstractmethod
168 def traceback(self, timeout=None):
169 """Access the traceback of the exception raised by the computation.
171 This method may return immediately or may block.
173 Args:
174 timeout: The length of time in seconds to wait for the computation
175 to terminate or be cancelled. If None, the call will block until
176 the computation's termination.
178 Returns:
179 The traceback of the exception raised by the computation, or None
180 if the computation did not raise an exception.
182 Raises:
183 FutureTimeoutError: If a timeout value is passed and the computation
184 does not terminate within the allotted time.
185 FutureCancelledError: If the computation was cancelled.
186 """
187 raise NotImplementedError()
189 @abc.abstractmethod
190 def add_done_callback(self, fn):
191 """Adds a function to be called at completion of the computation.
193 The callback will be passed this Future object describing the outcome
194 of the computation. Callbacks will be invoked after the future is
195 terminated, whether successfully or not.
197 If the computation has already completed, the callback will be called
198 immediately.
200 Exceptions raised in the callback will be logged at ERROR level, but
201 will not terminate any threads of execution.
203 Args:
204 fn: A callable taking this Future object as its single parameter.
205 """
206 raise NotImplementedError()
209################################ gRPC Enums ##################################
212@enum.unique
213class ChannelConnectivity(enum.Enum):
214 """Mirrors grpc_connectivity_state in the gRPC Core.
216 Attributes:
217 IDLE: The channel is idle.
218 CONNECTING: The channel is connecting.
219 READY: The channel is ready to conduct RPCs.
220 TRANSIENT_FAILURE: The channel has seen a failure from which it expects
221 to recover.
222 SHUTDOWN: The channel has seen a failure from which it cannot recover.
223 """
225 IDLE = (_cygrpc.ConnectivityState.idle, "idle")
226 CONNECTING = (_cygrpc.ConnectivityState.connecting, "connecting")
227 READY = (_cygrpc.ConnectivityState.ready, "ready")
228 TRANSIENT_FAILURE = (
229 _cygrpc.ConnectivityState.transient_failure,
230 "transient failure",
231 )
232 SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, "shutdown")
235@enum.unique
236class StatusCode(enum.Enum):
237 """Mirrors grpc_status_code in the gRPC Core.
239 Attributes:
240 OK: Not an error; returned on success
241 CANCELLED: The operation was cancelled (typically by the caller).
242 UNKNOWN: Unknown error.
243 INVALID_ARGUMENT: Client specified an invalid argument.
244 DEADLINE_EXCEEDED: Deadline expired before operation could complete.
245 NOT_FOUND: Some requested entity (e.g., file or directory) was not found.
246 ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory)
247 already exists.
248 PERMISSION_DENIED: The caller does not have permission to execute the specified
249 operation.
250 UNAUTHENTICATED: The request does not have valid authentication credentials for the
251 operation.
252 RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or
253 perhaps the entire file system is out of space.
254 FAILED_PRECONDITION: Operation was rejected because the system is not in a state
255 required for the operation's execution.
256 ABORTED: The operation was aborted, typically due to a concurrency issue
257 like sequencer check failures, transaction aborts, etc.
258 UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service.
259 INTERNAL: Internal errors. Means some invariants expected by underlying
260 system has been broken.
261 UNAVAILABLE: The service is currently unavailable.
262 DATA_LOSS: Unrecoverable data loss or corruption.
263 """
265 OK = (int(_cygrpc.StatusCode.ok), "ok")
266 CANCELLED = (int(_cygrpc.StatusCode.cancelled), "cancelled")
267 UNKNOWN = (int(_cygrpc.StatusCode.unknown), "unknown")
268 INVALID_ARGUMENT = (
269 int(_cygrpc.StatusCode.invalid_argument),
270 "invalid argument",
271 )
272 DEADLINE_EXCEEDED = (
273 int(_cygrpc.StatusCode.deadline_exceeded),
274 "deadline exceeded",
275 )
276 NOT_FOUND = (int(_cygrpc.StatusCode.not_found), "not found")
277 ALREADY_EXISTS = (int(_cygrpc.StatusCode.already_exists), "already exists")
278 PERMISSION_DENIED = (
279 int(_cygrpc.StatusCode.permission_denied),
280 "permission denied",
281 )
282 RESOURCE_EXHAUSTED = (
283 int(_cygrpc.StatusCode.resource_exhausted),
284 "resource exhausted",
285 )
286 FAILED_PRECONDITION = (
287 int(_cygrpc.StatusCode.failed_precondition),
288 "failed precondition",
289 )
290 ABORTED = (int(_cygrpc.StatusCode.aborted), "aborted")
291 OUT_OF_RANGE = (int(_cygrpc.StatusCode.out_of_range), "out of range")
292 UNIMPLEMENTED = (int(_cygrpc.StatusCode.unimplemented), "unimplemented")
293 INTERNAL = (int(_cygrpc.StatusCode.internal), "internal")
294 UNAVAILABLE = (int(_cygrpc.StatusCode.unavailable), "unavailable")
295 DATA_LOSS = (int(_cygrpc.StatusCode.data_loss), "data loss")
296 UNAUTHENTICATED = (
297 int(_cygrpc.StatusCode.unauthenticated),
298 "unauthenticated",
299 )
302############################# gRPC Status ################################
305class Status(abc.ABC):
306 """Describes the status of an RPC.
308 This is an EXPERIMENTAL API.
310 Attributes:
311 code: A StatusCode object to be sent to the client.
312 details: A UTF-8-encodable string to be sent to the client upon
313 termination of the RPC.
314 trailing_metadata: The trailing :term:`metadata` in the RPC.
315 """
318############################# gRPC Exceptions ################################
321class RpcError(Exception):
322 """Raised by the gRPC library to indicate non-OK-status RPC termination."""
325############################## Shared Context ################################
328class RpcContext(abc.ABC):
329 """Provides RPC-related information and action."""
331 @abc.abstractmethod
332 def is_active(self):
333 """Describes whether the RPC is active or has terminated.
335 Returns:
336 bool:
337 True if RPC is active, False otherwise.
338 """
339 raise NotImplementedError()
341 @abc.abstractmethod
342 def time_remaining(self):
343 """Describes the length of allowed time remaining for the RPC.
345 Returns:
346 A nonnegative float indicating the length of allowed time in seconds
347 remaining for the RPC to complete before it is considered to have
348 timed out, or None if no deadline was specified for the RPC.
349 """
350 raise NotImplementedError()
352 @abc.abstractmethod
353 def cancel(self):
354 """Cancels the RPC.
356 Idempotent and has no effect if the RPC has already terminated.
357 """
358 raise NotImplementedError()
360 @abc.abstractmethod
361 def add_callback(self, callback):
362 """Registers a callback to be called on RPC termination.
364 Args:
365 callback: A no-parameter callable to be called on RPC termination.
367 Returns:
368 True if the callback was added and will be called later; False if
369 the callback was not added and will not be called (because the RPC
370 already terminated or some other reason).
371 """
372 raise NotImplementedError()
375######################### Invocation-Side Context ############################
378class Call(RpcContext, metaclass=abc.ABCMeta):
379 """Invocation-side utility object for an RPC."""
381 @abc.abstractmethod
382 def initial_metadata(self):
383 """Accesses the initial metadata sent by the server.
385 This method blocks until the value is available.
387 Returns:
388 The initial :term:`metadata`.
389 """
390 raise NotImplementedError()
392 @abc.abstractmethod
393 def trailing_metadata(self):
394 """Accesses the trailing metadata sent by the server.
396 This method blocks until the value is available.
398 Returns:
399 The trailing :term:`metadata`.
400 """
401 raise NotImplementedError()
403 @abc.abstractmethod
404 def code(self):
405 """Accesses the status code sent by the server.
407 This method blocks until the value is available.
409 Returns:
410 The StatusCode value for the RPC.
411 """
412 raise NotImplementedError()
414 @abc.abstractmethod
415 def details(self):
416 """Accesses the details sent by the server.
418 This method blocks until the value is available.
420 Returns:
421 The details string of the RPC.
422 """
423 raise NotImplementedError()
426############## Invocation-Side Interceptor Interfaces & Classes ##############
429class ClientCallDetails(abc.ABC):
430 """Describes an RPC to be invoked.
432 Attributes:
433 method: The method name of the RPC.
434 timeout: An optional duration of time in seconds to allow for the RPC.
435 metadata: Optional :term:`metadata` to be transmitted to
436 the service-side of the RPC.
437 credentials: An optional CallCredentials for the RPC.
438 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
439 compression: An element of grpc.Compression, e.g.
440 grpc.Compression.Gzip.
441 """
444class UnaryUnaryClientInterceptor(abc.ABC):
445 """Affords intercepting unary-unary invocations."""
447 @abc.abstractmethod
448 def intercept_unary_unary(self, continuation, client_call_details, request):
449 """Intercepts a unary-unary invocation asynchronously.
451 Args:
452 continuation: A function that proceeds with the invocation by
453 executing the next interceptor in chain or invoking the
454 actual RPC on the underlying Channel. It is the interceptor's
455 responsibility to call it if it decides to move the RPC forward.
456 The interceptor can use
457 `response_future = continuation(client_call_details, request)`
458 to continue with the RPC. `continuation` returns an object that is
459 both a Call for the RPC and a Future. In the event of RPC
460 completion, the return Call-Future's result value will be
461 the response message of the RPC. Should the event terminate
462 with non-OK status, the returned Call-Future's exception value
463 will be an RpcError.
464 client_call_details: A ClientCallDetails object describing the
465 outgoing RPC.
466 request: The request value for the RPC.
468 Returns:
469 An object that is both a Call for the RPC and a Future.
470 In the event of RPC completion, the return Call-Future's
471 result value will be the response message of the RPC.
472 Should the event terminate with non-OK status, the returned
473 Call-Future's exception value will be an RpcError.
474 """
475 raise NotImplementedError()
478class UnaryStreamClientInterceptor(abc.ABC):
479 """Affords intercepting unary-stream invocations."""
481 @abc.abstractmethod
482 def intercept_unary_stream(
483 self, continuation, client_call_details, request
484 ):
485 """Intercepts a unary-stream invocation.
487 Args:
488 continuation: A function that proceeds with the invocation by
489 executing the next interceptor in chain or invoking the
490 actual RPC on the underlying Channel. It is the interceptor's
491 responsibility to call it if it decides to move the RPC forward.
492 The interceptor can use
493 `response_iterator = continuation(client_call_details, request)`
494 to continue with the RPC. `continuation` returns an object that is
495 both a Call for the RPC and an iterator for response values.
496 Drawing response values from the returned Call-iterator may
497 raise RpcError indicating termination of the RPC with non-OK
498 status.
499 client_call_details: A ClientCallDetails object describing the
500 outgoing RPC.
501 request: The request value for the RPC.
503 Returns:
504 An object that is both a Call for the RPC and an iterator of
505 response values. Drawing response values from the returned
506 Call-iterator may raise RpcError indicating termination of
507 the RPC with non-OK status. This object *should* also fulfill the
508 Future interface, though it may not.
509 """
510 raise NotImplementedError()
513class StreamUnaryClientInterceptor(abc.ABC):
514 """Affords intercepting stream-unary invocations."""
516 @abc.abstractmethod
517 def intercept_stream_unary(
518 self, continuation, client_call_details, request_iterator
519 ):
520 """Intercepts a stream-unary invocation asynchronously.
522 Args:
523 continuation: A function that proceeds with the invocation by
524 executing the next interceptor in chain or invoking the
525 actual RPC on the underlying Channel. It is the interceptor's
526 responsibility to call it if it decides to move the RPC forward.
527 The interceptor can use
528 `response_future = continuation(client_call_details, request_iterator)`
529 to continue with the RPC. `continuation` returns an object that is
530 both a Call for the RPC and a Future. In the event of RPC completion,
531 the return Call-Future's result value will be the response message
532 of the RPC. Should the event terminate with non-OK status, the
533 returned Call-Future's exception value will be an RpcError.
534 client_call_details: A ClientCallDetails object describing the
535 outgoing RPC.
536 request_iterator: An iterator that yields request values for the RPC.
538 Returns:
539 An object that is both a Call for the RPC and a Future.
540 In the event of RPC completion, the return Call-Future's
541 result value will be the response message of the RPC.
542 Should the event terminate with non-OK status, the returned
543 Call-Future's exception value will be an RpcError.
544 """
545 raise NotImplementedError()
548class StreamStreamClientInterceptor(abc.ABC):
549 """Affords intercepting stream-stream invocations."""
551 @abc.abstractmethod
552 def intercept_stream_stream(
553 self, continuation, client_call_details, request_iterator
554 ):
555 """Intercepts a stream-stream invocation.
557 Args:
558 continuation: A function that proceeds with the invocation by
559 executing the next interceptor in chain or invoking the
560 actual RPC on the underlying Channel. It is the interceptor's
561 responsibility to call it if it decides to move the RPC forward.
562 The interceptor can use
563 `response_iterator = continuation(client_call_details, request_iterator)`
564 to continue with the RPC. `continuation` returns an object that is
565 both a Call for the RPC and an iterator for response values.
566 Drawing response values from the returned Call-iterator may
567 raise RpcError indicating termination of the RPC with non-OK
568 status.
569 client_call_details: A ClientCallDetails object describing the
570 outgoing RPC.
571 request_iterator: An iterator that yields request values for the RPC.
573 Returns:
574 An object that is both a Call for the RPC and an iterator of
575 response values. Drawing response values from the returned
576 Call-iterator may raise RpcError indicating termination of
577 the RPC with non-OK status. This object *should* also fulfill the
578 Future interface, though it may not.
579 """
580 raise NotImplementedError()
583############ Authentication & Authorization Interfaces & Classes #############
586class ChannelCredentials:
587 """An encapsulation of the data required to create a secure Channel.
589 This class has no supported interface - it exists to define the type of its
590 instances and its instances exist to be passed to other functions. For
591 example, ssl_channel_credentials returns an instance of this class and
592 secure_channel requires an instance of this class.
593 """
595 _credentials: _cygrpc.ChannelCredentials
597 def __init__(self, credentials):
598 self._credentials = credentials
601class CallCredentials:
602 """An encapsulation of the data required to assert an identity over a call.
604 A CallCredentials has to be used with secure Channel, otherwise the
605 metadata will not be transmitted to the server.
607 A CallCredentials may be composed with ChannelCredentials to always assert
608 identity for every call over that Channel.
610 This class has no supported interface - it exists to define the type of its
611 instances and its instances exist to be passed to other functions.
612 """
614 def __init__(self, credentials):
615 self._credentials = credentials
618class AuthMetadataContext(abc.ABC):
619 """Provides information to call credentials metadata plugins.
621 Attributes:
622 service_url: A string URL of the service being called into.
623 method_name: A string of the fully qualified method name being called.
624 """
627class AuthMetadataPluginCallback(abc.ABC):
628 """Callback object received by a metadata plugin."""
630 def __call__(self, metadata, error):
631 """Passes to the gRPC runtime authentication metadata for an RPC.
633 Args:
634 metadata: The :term:`metadata` used to construct the CallCredentials.
635 error: An Exception to indicate error or None to indicate success.
636 """
637 raise NotImplementedError()
640class AuthMetadataPlugin(abc.ABC):
641 """A specification for custom authentication."""
643 def __call__(self, context, callback):
644 """Implements authentication by passing metadata to a callback.
646 This method will be invoked asynchronously in a separate thread.
648 Args:
649 context: An AuthMetadataContext providing information on the RPC that
650 the plugin is being called to authenticate.
651 callback: An AuthMetadataPluginCallback to be invoked either
652 synchronously or asynchronously.
653 """
654 raise NotImplementedError()
657class ServerCredentials:
658 """An encapsulation of the data required to open a secure port on a Server.
660 This class has no supported interface - it exists to define the type of its
661 instances and its instances exist to be passed to other functions.
662 """
664 def __init__(self, credentials):
665 self._credentials = credentials
668class ServerCertificateConfiguration:
669 """A certificate configuration for use with an SSL-enabled Server.
671 Instances of this class can be returned in the certificate configuration
672 fetching callback.
674 This class has no supported interface -- it exists to define the
675 type of its instances and its instances exist to be passed to
676 other functions.
677 """
679 def __init__(self, certificate_configuration):
680 self._certificate_configuration = certificate_configuration
683######################## Multi-Callable Interfaces ###########################
686class UnaryUnaryMultiCallable(abc.ABC):
687 """Affords invoking a unary-unary RPC from client-side."""
689 @abc.abstractmethod
690 def __call__(
691 self,
692 request,
693 timeout=None,
694 metadata=None,
695 credentials=None,
696 wait_for_ready=None,
697 compression=None,
698 ):
699 """Synchronously invokes the underlying RPC.
701 Args:
702 request: The request value for the RPC.
703 timeout: An optional duration of time in seconds to allow
704 for the RPC.
705 metadata: Optional :term:`metadata` to be transmitted to the
706 service-side of the RPC.
707 credentials: An optional CallCredentials for the RPC. Only valid for
708 secure Channel.
709 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
710 compression: An element of grpc.Compression, e.g.
711 grpc.Compression.Gzip.
713 Returns:
714 The response value for the RPC.
716 Raises:
717 RpcError: Indicating that the RPC terminated with non-OK status. The
718 raised RpcError will also be a Call for the RPC affording the RPC's
719 metadata, status code, and details.
720 """
721 raise NotImplementedError()
723 @abc.abstractmethod
724 def with_call(
725 self,
726 request,
727 timeout=None,
728 metadata=None,
729 credentials=None,
730 wait_for_ready=None,
731 compression=None,
732 ):
733 """Synchronously invokes the underlying RPC.
735 Args:
736 request: The request value for the RPC.
737 timeout: An optional durating of time in seconds to allow for
738 the RPC.
739 metadata: Optional :term:`metadata` to be transmitted to the
740 service-side of the RPC.
741 credentials: An optional CallCredentials for the RPC. Only valid for
742 secure Channel.
743 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
744 compression: An element of grpc.Compression, e.g.
745 grpc.Compression.Gzip.
747 Returns:
748 The response value for the RPC and a Call value for the RPC.
750 Raises:
751 RpcError: Indicating that the RPC terminated with non-OK status. The
752 raised RpcError will also be a Call for the RPC affording the RPC's
753 metadata, status code, and details.
754 """
755 raise NotImplementedError()
757 @abc.abstractmethod
758 def future(
759 self,
760 request,
761 timeout=None,
762 metadata=None,
763 credentials=None,
764 wait_for_ready=None,
765 compression=None,
766 ):
767 """Asynchronously invokes the underlying RPC.
769 Args:
770 request: The request value for the RPC.
771 timeout: An optional duration of time in seconds to allow for
772 the RPC.
773 metadata: Optional :term:`metadata` to be transmitted to the
774 service-side of the RPC.
775 credentials: An optional CallCredentials for the RPC. Only valid for
776 secure Channel.
777 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
778 compression: An element of grpc.Compression, e.g.
779 grpc.Compression.Gzip.
781 Returns:
782 An object that is both a Call for the RPC and a Future.
783 In the event of RPC completion, the return Call-Future's result
784 value will be the response message of the RPC.
785 Should the event terminate with non-OK status,
786 the returned Call-Future's exception value will be an RpcError.
787 """
788 raise NotImplementedError()
791class UnaryStreamMultiCallable(abc.ABC):
792 """Affords invoking a unary-stream RPC from client-side."""
794 @abc.abstractmethod
795 def __call__(
796 self,
797 request,
798 timeout=None,
799 metadata=None,
800 credentials=None,
801 wait_for_ready=None,
802 compression=None,
803 ):
804 """Invokes the underlying RPC.
806 Args:
807 request: The request value for the RPC.
808 timeout: An optional duration of time in seconds to allow for
809 the RPC. If None, the timeout is considered infinite.
810 metadata: An optional :term:`metadata` to be transmitted to the
811 service-side of the RPC.
812 credentials: An optional CallCredentials for the RPC. Only valid for
813 secure Channel.
814 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
815 compression: An element of grpc.Compression, e.g.
816 grpc.Compression.Gzip.
818 Returns:
819 An object that is a Call for the RPC, an iterator of response
820 values, and a Future for the RPC. Drawing response values from the
821 returned Call-iterator may raise RpcError indicating termination of
822 the RPC with non-OK status.
823 """
824 raise NotImplementedError()
827class StreamUnaryMultiCallable(abc.ABC):
828 """Affords invoking a stream-unary RPC from client-side."""
830 @abc.abstractmethod
831 def __call__(
832 self,
833 request_iterator,
834 timeout=None,
835 metadata=None,
836 credentials=None,
837 wait_for_ready=None,
838 compression=None,
839 ):
840 """Synchronously invokes the underlying RPC.
842 Args:
843 request_iterator: An iterator that yields request values for
844 the RPC.
845 timeout: An optional duration of time in seconds to allow for
846 the RPC. If None, the timeout is considered infinite.
847 metadata: Optional :term:`metadata` to be transmitted to the
848 service-side of the RPC.
849 credentials: An optional CallCredentials for the RPC. Only valid for
850 secure Channel.
851 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
852 compression: An element of grpc.Compression, e.g.
853 grpc.Compression.Gzip.
855 Returns:
856 The response value for the RPC.
858 Raises:
859 RpcError: Indicating that the RPC terminated with non-OK status. The
860 raised RpcError will also implement grpc.Call, affording methods
861 such as metadata, code, and details.
862 """
863 raise NotImplementedError()
865 @abc.abstractmethod
866 def with_call(
867 self,
868 request_iterator,
869 timeout=None,
870 metadata=None,
871 credentials=None,
872 wait_for_ready=None,
873 compression=None,
874 ):
875 """Synchronously invokes the underlying RPC on the client.
877 Args:
878 request_iterator: An iterator that yields request values for
879 the RPC.
880 timeout: An optional duration of time in seconds to allow for
881 the RPC. If None, the timeout is considered infinite.
882 metadata: Optional :term:`metadata` to be transmitted to the
883 service-side of the RPC.
884 credentials: An optional CallCredentials for the RPC. Only valid for
885 secure Channel.
886 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
887 compression: An element of grpc.Compression, e.g.
888 grpc.Compression.Gzip.
890 Returns:
891 The response value for the RPC and a Call object for the RPC.
893 Raises:
894 RpcError: Indicating that the RPC terminated with non-OK status. The
895 raised RpcError will also be a Call for the RPC affording the RPC's
896 metadata, status code, and details.
897 """
898 raise NotImplementedError()
900 @abc.abstractmethod
901 def future(
902 self,
903 request_iterator,
904 timeout=None,
905 metadata=None,
906 credentials=None,
907 wait_for_ready=None,
908 compression=None,
909 ):
910 """Asynchronously invokes the underlying RPC on the client.
912 Args:
913 request_iterator: An iterator that yields request values for the RPC.
914 timeout: An optional duration of time in seconds to allow for
915 the RPC. If None, the timeout is considered infinite.
916 metadata: Optional :term:`metadata` to be transmitted to the
917 service-side of the RPC.
918 credentials: An optional CallCredentials for the RPC. Only valid for
919 secure Channel.
920 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
921 compression: An element of grpc.Compression, e.g.
922 grpc.Compression.Gzip.
924 Returns:
925 An object that is both a Call for the RPC and a Future.
926 In the event of RPC completion, the return Call-Future's result value
927 will be the response message of the RPC. Should the event terminate
928 with non-OK status, the returned Call-Future's exception value will
929 be an RpcError.
930 """
931 raise NotImplementedError()
934class StreamStreamMultiCallable(abc.ABC):
935 """Affords invoking a stream-stream RPC on client-side."""
937 @abc.abstractmethod
938 def __call__(
939 self,
940 request_iterator,
941 timeout=None,
942 metadata=None,
943 credentials=None,
944 wait_for_ready=None,
945 compression=None,
946 ):
947 """Invokes the underlying RPC on the client.
949 Args:
950 request_iterator: An iterator that yields request values for the RPC.
951 timeout: An optional duration of time in seconds to allow for
952 the RPC. If not specified, the timeout is considered infinite.
953 metadata: Optional :term:`metadata` to be transmitted to the
954 service-side of the RPC.
955 credentials: An optional CallCredentials for the RPC. Only valid for
956 secure Channel.
957 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
958 compression: An element of grpc.Compression, e.g.
959 grpc.Compression.Gzip.
961 Returns:
962 An object that is a Call for the RPC, an iterator of response
963 values, and a Future for the RPC. Drawing response values from the
964 returned Call-iterator may raise RpcError indicating termination of
965 the RPC with non-OK status.
966 """
967 raise NotImplementedError()
970############################# Channel Interface ##############################
973class Channel(abc.ABC):
974 """Affords RPC invocation via generic methods on client-side.
976 Channel objects implement the Context Manager type, although they need not
977 support being entered and exited multiple times.
978 """
980 @abc.abstractmethod
981 def subscribe(self, callback, try_to_connect=False):
982 """Subscribe to this Channel's connectivity state machine.
984 A Channel may be in any of the states described by ChannelConnectivity.
985 This method allows application to monitor the state transitions.
986 The typical use case is to debug or gain better visibility into gRPC
987 runtime's state.
989 Args:
990 callback: A callable to be invoked with ChannelConnectivity argument.
991 ChannelConnectivity describes current state of the channel.
992 The callable will be invoked immediately upon subscription
993 and again for every change to ChannelConnectivity until it
994 is unsubscribed or this Channel object goes out of scope.
995 try_to_connect: A boolean indicating whether or not this Channel
996 should attempt to connect immediately. If set to False, gRPC
997 runtime decides when to connect.
998 """
999 raise NotImplementedError()
1001 @abc.abstractmethod
1002 def unsubscribe(self, callback):
1003 """Unsubscribes a subscribed callback from this Channel's connectivity.
1005 Args:
1006 callback: A callable previously registered with this Channel from
1007 having been passed to its "subscribe" method.
1008 """
1009 raise NotImplementedError()
1011 @abc.abstractmethod
1012 def unary_unary(
1013 self,
1014 method,
1015 request_serializer=None,
1016 response_deserializer=None,
1017 _registered_method=False,
1018 ):
1019 """Creates a UnaryUnaryMultiCallable for a unary-unary method.
1021 Args:
1022 method: The name of the RPC method.
1023 request_serializer: Optional :term:`serializer` for serializing the request
1024 message. Request goes unserialized in case None is passed.
1025 response_deserializer: Optional :term:`deserializer` for deserializing the
1026 response message. Response goes undeserialized in case None
1027 is passed.
1028 _registered_method: Implementation Private. A bool representing whether the method
1029 is registered.
1031 Returns:
1032 A UnaryUnaryMultiCallable value for the named unary-unary method.
1033 """
1034 raise NotImplementedError()
1036 @abc.abstractmethod
1037 def unary_stream(
1038 self,
1039 method,
1040 request_serializer=None,
1041 response_deserializer=None,
1042 _registered_method=False,
1043 ):
1044 """Creates a UnaryStreamMultiCallable for a unary-stream method.
1046 Args:
1047 method: The name of the RPC method.
1048 request_serializer: Optional :term:`serializer` for serializing the request
1049 message. Request goes unserialized in case None is passed.
1050 response_deserializer: Optional :term:`deserializer` for deserializing the
1051 response message. Response goes undeserialized in case None is
1052 passed.
1053 _registered_method: Implementation Private. A bool representing whether the method
1054 is registered.
1056 Returns:
1057 A UnaryStreamMultiCallable value for the name unary-stream method.
1058 """
1059 raise NotImplementedError()
1061 @abc.abstractmethod
1062 def stream_unary(
1063 self,
1064 method,
1065 request_serializer=None,
1066 response_deserializer=None,
1067 _registered_method=False,
1068 ):
1069 """Creates a StreamUnaryMultiCallable for a stream-unary method.
1071 Args:
1072 method: The name of the RPC method.
1073 request_serializer: Optional :term:`serializer` for serializing the request
1074 message. Request goes unserialized in case None is passed.
1075 response_deserializer: Optional :term:`deserializer` for deserializing the
1076 response message. Response goes undeserialized in case None is
1077 passed.
1078 _registered_method: Implementation Private. A bool representing whether the method
1079 is registered.
1081 Returns:
1082 A StreamUnaryMultiCallable value for the named stream-unary method.
1083 """
1084 raise NotImplementedError()
1086 @abc.abstractmethod
1087 def stream_stream(
1088 self,
1089 method,
1090 request_serializer=None,
1091 response_deserializer=None,
1092 _registered_method=False,
1093 ):
1094 """Creates a StreamStreamMultiCallable for a stream-stream method.
1096 Args:
1097 method: The name of the RPC method.
1098 request_serializer: Optional :term:`serializer` for serializing the request
1099 message. Request goes unserialized in case None is passed.
1100 response_deserializer: Optional :term:`deserializer` for deserializing the
1101 response message. Response goes undeserialized in case None
1102 is passed.
1103 _registered_method: Implementation Private. A bool representing whether the method
1104 is registered.
1106 Returns:
1107 A StreamStreamMultiCallable value for the named stream-stream method.
1108 """
1109 raise NotImplementedError()
1111 @abc.abstractmethod
1112 def close(self):
1113 """Closes this Channel and releases all resources held by it.
1115 Closing the Channel will immediately terminate all RPCs active with the
1116 Channel and it is not valid to invoke new RPCs with the Channel.
1118 This method is idempotent.
1119 """
1120 raise NotImplementedError()
1122 def __enter__(self):
1123 """Enters the runtime context related to the channel object."""
1124 raise NotImplementedError()
1126 def __exit__(self, exc_type, exc_val, exc_tb):
1127 """Exits the runtime context related to the channel object."""
1128 raise NotImplementedError()
1131########################## Service-Side Context ##############################
1134class ServicerContext(RpcContext, metaclass=abc.ABCMeta):
1135 """A context object passed to method implementations."""
1137 @abc.abstractmethod
1138 def invocation_metadata(self):
1139 """Accesses the metadata sent by the client.
1141 Returns:
1142 The invocation :term:`metadata`.
1143 """
1144 raise NotImplementedError()
1146 @abc.abstractmethod
1147 def peer(self):
1148 """Identifies the peer that invoked the RPC being serviced.
1150 Returns:
1151 A string identifying the peer that invoked the RPC being serviced.
1152 The string format is determined by gRPC runtime.
1153 """
1154 raise NotImplementedError()
1156 @abc.abstractmethod
1157 def peer_identities(self):
1158 """Gets one or more peer identity(s).
1160 Equivalent to
1161 servicer_context.auth_context().get(servicer_context.peer_identity_key())
1163 Returns:
1164 An iterable of the identities, or None if the call is not
1165 authenticated. Each identity is returned as a raw bytes type.
1166 """
1167 raise NotImplementedError()
1169 @abc.abstractmethod
1170 def peer_identity_key(self):
1171 """The auth property used to identify the peer.
1173 For example, "x509_common_name" or "x509_subject_alternative_name" are
1174 used to identify an SSL peer.
1176 Returns:
1177 The auth property (string) that indicates the
1178 peer identity, or None if the call is not authenticated.
1179 """
1180 raise NotImplementedError()
1182 @abc.abstractmethod
1183 def auth_context(self):
1184 """Gets the auth context for the call.
1186 Returns:
1187 A map of strings to an iterable of bytes for each auth property.
1188 """
1189 raise NotImplementedError()
1191 def set_compression(self, compression):
1192 """Set the compression algorithm to be used for the entire call.
1194 Args:
1195 compression: An element of grpc.Compression, e.g.
1196 grpc.Compression.Gzip.
1197 """
1198 raise NotImplementedError()
1200 @abc.abstractmethod
1201 def send_initial_metadata(self, initial_metadata):
1202 """Sends the initial metadata value to the client.
1204 This method need not be called by implementations if they have no
1205 metadata to add to what the gRPC runtime will transmit.
1207 Args:
1208 initial_metadata: The initial :term:`metadata`.
1209 """
1210 raise NotImplementedError()
1212 @abc.abstractmethod
1213 def set_trailing_metadata(self, trailing_metadata):
1214 """Sets the trailing metadata for the RPC.
1216 Sets the trailing metadata to be sent upon completion of the RPC.
1218 If this method is invoked multiple times throughout the lifetime of an
1219 RPC, the value supplied in the final invocation will be the value sent
1220 over the wire.
1222 This method need not be called by implementations if they have no
1223 metadata to add to what the gRPC runtime will transmit.
1225 Args:
1226 trailing_metadata: The trailing :term:`metadata`.
1227 """
1228 raise NotImplementedError()
1230 def trailing_metadata(self):
1231 """Access value to be used as trailing metadata upon RPC completion.
1233 This is an EXPERIMENTAL API.
1235 Returns:
1236 The trailing :term:`metadata` for the RPC.
1237 """
1238 raise NotImplementedError()
1240 @abc.abstractmethod
1241 def abort(self, code, details):
1242 """Raises an exception to terminate the RPC with a non-OK status.
1244 The code and details passed as arguments will supersede any existing
1245 ones.
1247 Args:
1248 code: A StatusCode object to be sent to the client.
1249 It must not be StatusCode.OK.
1250 details: A UTF-8-encodable string to be sent to the client upon
1251 termination of the RPC.
1253 Raises:
1254 Exception: An exception is always raised to signal the abortion the
1255 RPC to the gRPC runtime.
1256 """
1257 raise NotImplementedError()
1259 @abc.abstractmethod
1260 def abort_with_status(self, status):
1261 """Raises an exception to terminate the RPC with a non-OK status.
1263 The status passed as argument will supersede any existing status code,
1264 status message and trailing metadata.
1266 This is an EXPERIMENTAL API.
1268 Args:
1269 status: A grpc.Status object. The status code in it must not be
1270 StatusCode.OK.
1272 Raises:
1273 Exception: An exception is always raised to signal the abortion the
1274 RPC to the gRPC runtime.
1275 """
1276 raise NotImplementedError()
1278 @abc.abstractmethod
1279 def set_code(self, code):
1280 """Sets the value to be used as status code upon RPC completion.
1282 This method need not be called by method implementations if they wish
1283 the gRPC runtime to determine the status code of the RPC.
1285 Args:
1286 code: A StatusCode object to be sent to the client.
1287 """
1288 raise NotImplementedError()
1290 @abc.abstractmethod
1291 def set_details(self, details):
1292 """Sets the value to be used as detail string upon RPC completion.
1294 This method need not be called by method implementations if they have
1295 no details to transmit.
1297 Args:
1298 details: A UTF-8-encodable string to be sent to the client upon
1299 termination of the RPC.
1300 """
1301 raise NotImplementedError()
1303 def code(self):
1304 """Accesses the value to be used as status code upon RPC completion.
1306 This is an EXPERIMENTAL API.
1308 Returns:
1309 The StatusCode value for the RPC.
1310 """
1311 raise NotImplementedError()
1313 def details(self):
1314 """Accesses the value to be used as detail string upon RPC completion.
1316 This is an EXPERIMENTAL API.
1318 Returns:
1319 The details string of the RPC.
1320 """
1321 raise NotImplementedError()
1323 def disable_next_message_compression(self):
1324 """Disables compression for the next response message.
1326 This method will override any compression configuration set during
1327 server creation or set on the call.
1328 """
1329 raise NotImplementedError()
1332##################### Service-Side Handler Interfaces ########################
1335class RpcMethodHandler(abc.ABC):
1336 """An implementation of a single RPC method.
1338 Attributes:
1339 request_streaming: Whether the RPC supports exactly one request message
1340 or any arbitrary number of request messages.
1341 response_streaming: Whether the RPC supports exactly one response message
1342 or any arbitrary number of response messages.
1343 request_deserializer: A callable :term:`deserializer` that accepts a byte string and
1344 returns an object suitable to be passed to this object's business
1345 logic, or None to indicate that this object's business logic should be
1346 passed the raw request bytes.
1347 response_serializer: A callable :term:`serializer` that accepts an object produced
1348 by this object's business logic and returns a byte string, or None to
1349 indicate that the byte strings produced by this object's business logic
1350 should be transmitted on the wire as they are.
1351 unary_unary: This object's application-specific business logic as a
1352 callable value that takes a request value and a ServicerContext object
1353 and returns a response value. Only non-None if both request_streaming
1354 and response_streaming are False.
1355 unary_stream: This object's application-specific business logic as a
1356 callable value that takes a request value and a ServicerContext object
1357 and returns an iterator of response values. Only non-None if
1358 request_streaming is False and response_streaming is True.
1359 stream_unary: This object's application-specific business logic as a
1360 callable value that takes an iterator of request values and a
1361 ServicerContext object and returns a response value. Only non-None if
1362 request_streaming is True and response_streaming is False.
1363 stream_stream: This object's application-specific business logic as a
1364 callable value that takes an iterator of request values and a
1365 ServicerContext object and returns an iterator of response values.
1366 Only non-None if request_streaming and response_streaming are both
1367 True.
1368 """
1371@typing.runtime_checkable
1372class HandlerCallDetails(Protocol):
1373 """Describes an RPC that has just arrived for service.
1375 Attributes:
1376 method: The method name of the RPC.
1377 invocation_metadata: The :term:`metadata` sent by the client.
1378 """
1380 method: str
1381 invocation_metadata: Any
1384class GenericRpcHandler(abc.ABC):
1385 """An implementation of arbitrarily many RPC methods."""
1387 @abc.abstractmethod
1388 def service(self, handler_call_details):
1389 """Returns the handler for servicing the RPC.
1391 Args:
1392 handler_call_details: A HandlerCallDetails describing the RPC.
1394 Returns:
1395 An RpcMethodHandler with which the RPC may be serviced if the
1396 implementation chooses to service this RPC, or None otherwise.
1397 """
1398 raise NotImplementedError()
1401class ServiceRpcHandler(GenericRpcHandler, metaclass=abc.ABCMeta):
1402 """An implementation of RPC methods belonging to a service.
1404 A service handles RPC methods with structured names of the form
1405 '/Service.Name/Service.Method', where 'Service.Name' is the value
1406 returned by service_name(), and 'Service.Method' is the method
1407 name. A service can have multiple method names, but only a single
1408 service name.
1409 """
1411 @abc.abstractmethod
1412 def service_name(self):
1413 """Returns this service's name.
1415 Returns:
1416 The service name.
1417 """
1418 raise NotImplementedError()
1421#################### Service-Side Interceptor Interfaces #####################
1424class ServerInterceptor(abc.ABC):
1425 """Affords intercepting incoming RPCs on the service-side."""
1427 @abc.abstractmethod
1428 def intercept_service(self, continuation, handler_call_details):
1429 """Intercepts incoming RPCs before handing them over to a handler.
1431 State can be passed from an interceptor to downstream interceptors
1432 via contextvars. The first interceptor is called from an empty
1433 contextvars.Context, and the same Context is used for downstream
1434 interceptors and for the final handler call. Note that there are no
1435 guarantees that interceptors and handlers will be called from the
1436 same thread.
1438 Args:
1439 continuation: A function that takes a HandlerCallDetails and
1440 proceeds to invoke the next interceptor in the chain, if any,
1441 or the RPC handler lookup logic, with the call details passed
1442 as an argument, and returns an RpcMethodHandler instance if
1443 the RPC is considered serviced, or None otherwise.
1444 handler_call_details: A HandlerCallDetails describing the RPC.
1446 Returns:
1447 An RpcMethodHandler with which the RPC may be serviced if the
1448 interceptor chooses to service this RPC, or None otherwise.
1449 """
1450 raise NotImplementedError()
1453############################# Server Interface ###############################
1456class Server(abc.ABC):
1457 """Services RPCs."""
1459 @abc.abstractmethod
1460 def add_generic_rpc_handlers(self, generic_rpc_handlers):
1461 """Registers GenericRpcHandlers with this Server.
1463 This method is only safe to call before the server is started.
1465 Args:
1466 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1467 used to service RPCs.
1468 """
1469 raise NotImplementedError()
1471 def add_registered_method_handlers( # noqa: B027
1472 self, service_name, method_handlers
1473 ):
1474 """Registers GenericRpcHandlers with this Server.
1476 This method is only safe to call before the server is started.
1478 If the same method have both generic and registered handler,
1479 registered handler will take precedence.
1481 Args:
1482 service_name: The service name.
1483 method_handlers: A dictionary that maps method names to corresponding
1484 RpcMethodHandler.
1485 """
1487 @abc.abstractmethod
1488 def add_insecure_port(self, address):
1489 """Opens an insecure port for accepting RPCs.
1491 This method may only be called before starting the server.
1493 Args:
1494 address: The address for which to open a port. If the port is 0,
1495 or not specified in the address, then gRPC runtime will choose a port.
1497 Returns:
1498 An integer port on which server will accept RPC requests.
1499 """
1500 raise NotImplementedError()
1502 @abc.abstractmethod
1503 def add_secure_port(self, address, server_credentials):
1504 """Opens a secure port for accepting RPCs.
1506 This method may only be called before starting the server.
1508 Args:
1509 address: The address for which to open a port.
1510 if the port is 0, or not specified in the address, then gRPC
1511 runtime will choose a port.
1512 server_credentials: A ServerCredentials object.
1514 Returns:
1515 An integer port on which server will accept RPC requests.
1516 """
1517 raise NotImplementedError()
1519 @abc.abstractmethod
1520 def start(self):
1521 """Starts this Server.
1523 This method may only be called once. (i.e. it is not idempotent).
1524 """
1525 raise NotImplementedError()
1527 @abc.abstractmethod
1528 def stop(self, grace):
1529 """Stops this Server.
1531 This method immediately stop service of new RPCs in all cases.
1533 If a grace period is specified, this method waits until all active
1534 RPCs are finished or until the grace period is reached. RPCs that haven't
1535 been terminated within the grace period are aborted.
1536 If a grace period is not specified (by passing None for `grace`),
1537 all existing RPCs are aborted immediately and this method
1538 blocks until the last RPC handler terminates.
1540 This method is idempotent and may be called at any time.
1541 Passing a smaller grace value in a subsequent call will have
1542 the effect of stopping the Server sooner (passing None will
1543 have the effect of stopping the server immediately). Passing
1544 a larger grace value in a subsequent call *will not* have the
1545 effect of stopping the server later (i.e. the most restrictive
1546 grace value is used).
1548 Args:
1549 grace: A duration of time in seconds or None.
1551 Returns:
1552 A threading.Event that will be set when this Server has completely
1553 stopped, i.e. when running RPCs either complete or are aborted and
1554 all handlers have terminated.
1555 """
1556 raise NotImplementedError()
1558 def wait_for_termination(self, timeout=None):
1559 """Block current thread until the server stops.
1561 This is an EXPERIMENTAL API.
1563 The wait will not consume computational resources during blocking, and
1564 it will block until one of the two following conditions are met:
1566 1) The server is stopped or terminated;
1567 2) A timeout occurs if timeout is not `None`.
1569 The timeout argument works in the same way as `threading.Event.wait()`.
1570 https://docs.python.org/3/library/threading.html#threading.Event.wait
1572 Args:
1573 timeout: A floating point number specifying a timeout for the
1574 operation in seconds.
1576 Returns:
1577 A bool indicates if the operation times out.
1578 """
1579 raise NotImplementedError()
1582################################# Functions ################################
1585def unary_unary_rpc_method_handler(
1586 behavior, request_deserializer=None, response_serializer=None
1587):
1588 """Creates an RpcMethodHandler for a unary-unary RPC method.
1590 Args:
1591 behavior: The implementation of an RPC that accepts one request
1592 and returns one response.
1593 request_deserializer: An optional :term:`deserializer` for request deserialization.
1594 response_serializer: An optional :term:`serializer` for response serialization.
1596 Returns:
1597 An RpcMethodHandler object that is typically used by grpc.Server.
1598 """
1599 from grpc import _utilities # pylint: disable=cyclic-import
1601 return _utilities.RpcMethodHandler(
1602 False,
1603 False,
1604 request_deserializer,
1605 response_serializer,
1606 behavior,
1607 None,
1608 None,
1609 None,
1610 )
1613def unary_stream_rpc_method_handler(
1614 behavior, request_deserializer=None, response_serializer=None
1615):
1616 """Creates an RpcMethodHandler for a unary-stream RPC method.
1618 Args:
1619 behavior: The implementation of an RPC that accepts one request
1620 and returns an iterator of response values.
1621 request_deserializer: An optional :term:`deserializer` for request deserialization.
1622 response_serializer: An optional :term:`serializer` for response serialization.
1624 Returns:
1625 An RpcMethodHandler object that is typically used by grpc.Server.
1626 """
1627 from grpc import _utilities # pylint: disable=cyclic-import
1629 return _utilities.RpcMethodHandler(
1630 False,
1631 True,
1632 request_deserializer,
1633 response_serializer,
1634 None,
1635 behavior,
1636 None,
1637 None,
1638 )
1641def stream_unary_rpc_method_handler(
1642 behavior, request_deserializer=None, response_serializer=None
1643):
1644 """Creates an RpcMethodHandler for a stream-unary RPC method.
1646 Args:
1647 behavior: The implementation of an RPC that accepts an iterator of
1648 request values and returns a single response value.
1649 request_deserializer: An optional :term:`deserializer` for request deserialization.
1650 response_serializer: An optional :term:`serializer` for response serialization.
1652 Returns:
1653 An RpcMethodHandler object that is typically used by grpc.Server.
1654 """
1655 from grpc import _utilities # pylint: disable=cyclic-import
1657 return _utilities.RpcMethodHandler(
1658 True,
1659 False,
1660 request_deserializer,
1661 response_serializer,
1662 None,
1663 None,
1664 behavior,
1665 None,
1666 )
1669def stream_stream_rpc_method_handler(
1670 behavior, request_deserializer=None, response_serializer=None
1671):
1672 """Creates an RpcMethodHandler for a stream-stream RPC method.
1674 Args:
1675 behavior: The implementation of an RPC that accepts an iterator of
1676 request values and returns an iterator of response values.
1677 request_deserializer: An optional :term:`deserializer` for request deserialization.
1678 response_serializer: An optional :term:`serializer` for response serialization.
1680 Returns:
1681 An RpcMethodHandler object that is typically used by grpc.Server.
1682 """
1683 from grpc import _utilities # pylint: disable=cyclic-import
1685 return _utilities.RpcMethodHandler(
1686 True,
1687 True,
1688 request_deserializer,
1689 response_serializer,
1690 None,
1691 None,
1692 None,
1693 behavior,
1694 )
1697def method_handlers_generic_handler(service, method_handlers):
1698 """Creates a GenericRpcHandler from RpcMethodHandlers.
1700 Args:
1701 service: The name of the service that is implemented by the
1702 method_handlers.
1703 method_handlers: A dictionary that maps method names to corresponding
1704 RpcMethodHandler.
1706 Returns:
1707 A GenericRpcHandler. This is typically added to the grpc.Server object
1708 with add_generic_rpc_handlers() before starting the server.
1709 """
1710 from grpc import _utilities # pylint: disable=cyclic-import
1712 return _utilities.DictionaryGenericHandler(service, method_handlers)
1715def ssl_channel_credentials(
1716 root_certificates=None, private_key=None, certificate_chain=None
1717):
1718 """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1720 Args:
1721 root_certificates: The PEM-encoded root certificates as a byte string,
1722 or None to retrieve them from a default location chosen by gRPC
1723 runtime.
1724 private_key: The PEM-encoded private key as a byte string, or None if no
1725 private key should be used.
1726 certificate_chain: The PEM-encoded certificate chain as a byte string
1727 to use or None if no certificate chain should be used.
1729 Returns:
1730 A ChannelCredentials for use with an SSL-enabled Channel.
1731 """
1732 return ChannelCredentials(
1733 _cygrpc.SSLChannelCredentials(
1734 root_certificates, private_key, certificate_chain
1735 )
1736 )
1739def xds_channel_credentials(fallback_credentials=None):
1740 """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL
1741 API.
1743 Args:
1744 fallback_credentials: Credentials to use in case it is not possible to
1745 establish a secure connection via xDS. If no fallback_credentials
1746 argument is supplied, a default SSLChannelCredentials is used.
1747 """
1748 fallback_credentials = (
1749 ssl_channel_credentials()
1750 if fallback_credentials is None
1751 else fallback_credentials
1752 )
1753 return ChannelCredentials(
1754 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials)
1755 )
1758def metadata_call_credentials(metadata_plugin, name=None):
1759 """Construct CallCredentials from an AuthMetadataPlugin.
1761 Args:
1762 metadata_plugin: An AuthMetadataPlugin to use for authentication.
1763 name: An optional name for the plugin.
1765 Returns:
1766 A CallCredentials.
1767 """
1768 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1770 return _plugin_wrapping.metadata_plugin_call_credentials(
1771 metadata_plugin, name
1772 )
1775def access_token_call_credentials(access_token):
1776 """Construct CallCredentials from an access token.
1778 Args:
1779 access_token: A string to place directly in the http request
1780 authorization header, for example
1781 "authorization: Bearer <access_token>".
1783 Returns:
1784 A CallCredentials.
1785 """
1786 from grpc import _auth # pylint: disable=cyclic-import
1787 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1789 return _plugin_wrapping.metadata_plugin_call_credentials(
1790 _auth.AccessTokenAuthMetadataPlugin(access_token), None
1791 )
1794def composite_call_credentials(*call_credentials):
1795 """Compose multiple CallCredentials to make a new CallCredentials.
1797 Args:
1798 *call_credentials: At least two CallCredentials objects.
1800 Returns:
1801 A CallCredentials object composed of the given CallCredentials objects.
1802 """
1803 return CallCredentials(
1804 _cygrpc.CompositeCallCredentials(
1805 tuple(
1806 single_call_credentials._credentials
1807 for single_call_credentials in call_credentials
1808 )
1809 )
1810 )
1813def composite_channel_credentials(channel_credentials, *call_credentials):
1814 """Compose a ChannelCredentials and one or more CallCredentials objects.
1816 Args:
1817 channel_credentials: A ChannelCredentials object.
1818 *call_credentials: One or more CallCredentials objects.
1820 Returns:
1821 A ChannelCredentials composed of the given ChannelCredentials and
1822 CallCredentials objects.
1823 """
1824 return ChannelCredentials(
1825 _cygrpc.CompositeChannelCredentials(
1826 tuple(
1827 single_call_credentials._credentials
1828 for single_call_credentials in call_credentials
1829 ),
1830 channel_credentials._credentials,
1831 )
1832 )
1835def ssl_server_credentials(
1836 private_key_certificate_chain_pairs,
1837 root_certificates=None,
1838 require_client_auth=False,
1839):
1840 """Creates a ServerCredentials for use with an SSL-enabled Server.
1842 Args:
1843 private_key_certificate_chain_pairs: A list of pairs of the form
1844 [PEM-encoded private key, PEM-encoded certificate chain].
1845 root_certificates: An optional byte string of PEM-encoded client root
1846 certificates that the server will use to verify client authentication.
1847 If omitted, require_client_auth must also be False.
1848 require_client_auth: A boolean indicating whether or not to require
1849 clients to be authenticated. May only be True if root_certificates
1850 is not None.
1852 Returns:
1853 A ServerCredentials for use with an SSL-enabled Server. Typically, this
1854 object is an argument to add_secure_port() method during server setup.
1855 """
1856 if not private_key_certificate_chain_pairs:
1857 error_msg = (
1858 "At least one private key-certificate chain pair is required!"
1859 )
1860 raise ValueError(error_msg)
1861 if require_client_auth and root_certificates is None:
1862 error_msg = "Illegal to require client auth without providing root certificates!"
1863 raise ValueError(error_msg)
1864 return ServerCredentials(
1865 _cygrpc.server_credentials_ssl(
1866 root_certificates,
1867 [
1868 _cygrpc.SslPemKeyCertPair(key, pem)
1869 for key, pem in private_key_certificate_chain_pairs
1870 ],
1871 require_client_auth,
1872 )
1873 )
1876def xds_server_credentials(fallback_credentials):
1877 """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL
1878 API.
1880 Args:
1881 fallback_credentials: Credentials to use in case it is not possible to
1882 establish a secure connection via xDS. No default value is provided.
1883 """
1884 return ServerCredentials(
1885 _cygrpc.xds_server_credentials(fallback_credentials._credentials)
1886 )
1889def insecure_server_credentials():
1890 """Creates a credentials object directing the server to use no credentials.
1891 This is an EXPERIMENTAL API.
1893 This object cannot be used directly in a call to `add_secure_port`.
1894 Instead, it should be used to construct other credentials objects, e.g.
1895 with xds_server_credentials.
1896 """
1897 return ServerCredentials(_cygrpc.insecure_server_credentials())
1900def ssl_server_certificate_configuration(
1901 private_key_certificate_chain_pairs, root_certificates=None
1902):
1903 """Creates a ServerCertificateConfiguration for use with a Server.
1905 Args:
1906 private_key_certificate_chain_pairs: A collection of pairs of
1907 the form [PEM-encoded private key, PEM-encoded certificate
1908 chain].
1909 root_certificates: An optional byte string of PEM-encoded client root
1910 certificates that the server will use to verify client authentication.
1912 Returns:
1913 A ServerCertificateConfiguration that can be returned in the certificate
1914 configuration fetching callback.
1915 """
1916 if private_key_certificate_chain_pairs:
1917 return ServerCertificateConfiguration(
1918 _cygrpc.server_certificate_config_ssl(
1919 root_certificates,
1920 [
1921 _cygrpc.SslPemKeyCertPair(key, pem)
1922 for key, pem in private_key_certificate_chain_pairs
1923 ],
1924 )
1925 )
1926 error_msg = "At least one private key-certificate chain pair is required!"
1927 raise ValueError(error_msg)
1930def dynamic_ssl_server_credentials(
1931 initial_certificate_configuration,
1932 certificate_configuration_fetcher,
1933 require_client_authentication=False,
1934):
1935 """Creates a ServerCredentials for use with an SSL-enabled Server.
1937 Args:
1938 initial_certificate_configuration (ServerCertificateConfiguration): The
1939 certificate configuration with which the server will be initialized.
1940 certificate_configuration_fetcher (callable): A callable that takes no
1941 arguments and should return a ServerCertificateConfiguration to
1942 replace the server's current certificate, or None for no change
1943 (i.e., the server will continue its current certificate
1944 config). The library will call this callback on *every* new
1945 client connection before starting the TLS handshake with the
1946 client, thus allowing the user application to optionally
1947 return a new ServerCertificateConfiguration that the server will then
1948 use for the handshake.
1949 require_client_authentication: A boolean indicating whether or not to
1950 require clients to be authenticated.
1952 Returns:
1953 A ServerCredentials.
1954 """
1955 return ServerCredentials(
1956 _cygrpc.server_credentials_ssl_dynamic_cert_config(
1957 initial_certificate_configuration,
1958 certificate_configuration_fetcher,
1959 require_client_authentication,
1960 )
1961 )
1964@enum.unique
1965class LocalConnectionType(enum.Enum):
1966 """Types of local connection for local credential creation.
1968 Attributes:
1969 UDS: Unix domain socket connections
1970 LOCAL_TCP: Local TCP connections.
1971 """
1973 UDS = _cygrpc.LocalConnectionType.uds
1974 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
1977def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1978 """Creates a local ChannelCredentials used for local connections.
1980 This is an EXPERIMENTAL API.
1982 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1983 also UDS connections.
1985 The connections created by local channel credentials are not
1986 encrypted, but will be checked if they are local or not.
1987 The UDS connections are considered secure by providing peer authentication
1988 and data confidentiality while TCP connections are considered insecure.
1990 It is allowed to transmit call credentials over connections created by
1991 local channel credentials.
1993 Local channel credentials are useful for 1) eliminating insecure_channel usage;
1994 2) enable unit testing for call credentials without setting up secrets.
1996 Args:
1997 local_connect_type: Local connection type (either
1998 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
2000 Returns:
2001 A ChannelCredentials for use with a local Channel
2002 """
2003 return ChannelCredentials(
2004 _cygrpc.channel_credentials_local(local_connect_type.value)
2005 )
2008def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
2009 """Creates a local ServerCredentials used for local connections.
2011 This is an EXPERIMENTAL API.
2013 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
2014 also UDS connections.
2016 The connections created by local server credentials are not
2017 encrypted, but will be checked if they are local or not.
2018 The UDS connections are considered secure by providing peer authentication
2019 and data confidentiality while TCP connections are considered insecure.
2021 It is allowed to transmit call credentials over connections created by local
2022 server credentials.
2024 Local server credentials are useful for 1) eliminating insecure_channel usage;
2025 2) enable unit testing for call credentials without setting up secrets.
2027 Args:
2028 local_connect_type: Local connection type (either
2029 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
2031 Returns:
2032 A ServerCredentials for use with a local Server
2033 """
2034 return ServerCredentials(
2035 _cygrpc.server_credentials_local(local_connect_type.value)
2036 )
2039def alts_channel_credentials(service_accounts=None):
2040 """Creates a ChannelCredentials for use with an ALTS-enabled Channel.
2042 This is an EXPERIMENTAL API.
2043 ALTS credentials API can only be used in GCP environment as it relies on
2044 handshaker service being available. For more info about ALTS see
2045 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2047 Args:
2048 service_accounts: A list of server identities accepted by the client.
2049 If target service accounts are provided and none of them matches the
2050 peer identity of the server, handshake will fail. The arg can be empty
2051 if the client does not have any information about trusted server
2052 identity.
2054 Returns:
2055 A ChannelCredentials for use with an ALTS-enabled Channel
2056 """
2057 return ChannelCredentials(
2058 _cygrpc.channel_credentials_alts(service_accounts or [])
2059 )
2062def alts_server_credentials():
2063 """Creates a ServerCredentials for use with an ALTS-enabled connection.
2065 This is an EXPERIMENTAL API.
2066 ALTS credentials API can only be used in GCP environment as it relies on
2067 handshaker service being available. For more info about ALTS see
2068 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2070 Returns:
2071 A ServerCredentials for use with an ALTS-enabled Server
2072 """
2073 return ServerCredentials(_cygrpc.server_credentials_alts())
2076def compute_engine_channel_credentials(call_credentials):
2077 """Creates a compute engine channel credential.
2079 This credential can only be used in a GCP environment as it relies on
2080 a handshaker service. For more info about ALTS, see
2081 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2083 This channel credential is expected to be used as part of a composite
2084 credential in conjunction with a call credentials that authenticates the
2085 VM's default service account. If used with any other sort of call
2086 credential, the connection may suddenly and unexpectedly begin failing RPCs.
2087 """
2088 return ChannelCredentials(
2089 _cygrpc.channel_credentials_compute_engine(
2090 call_credentials._credentials
2091 )
2092 )
2095def channel_ready_future(channel):
2096 """Creates a Future that tracks when a Channel is ready.
2098 Cancelling the Future does not affect the channel's state machine.
2099 It merely decouples the Future from channel state machine.
2101 Args:
2102 channel: A Channel object.
2104 Returns:
2105 A Future object that matures when the channel connectivity is
2106 ChannelConnectivity.READY.
2107 """
2108 from grpc import _utilities # pylint: disable=cyclic-import
2110 return _utilities.channel_ready_future(channel)
2113def insecure_channel(target, options=None, compression=None):
2114 """Creates an insecure Channel to a server.
2116 The returned Channel is thread-safe.
2118 Args:
2119 target: The server address
2120 options: An optional list of key-value pairs (:term:`channel_arguments`
2121 in gRPC Core runtime) to configure the channel.
2122 compression: An optional value indicating the compression method to be
2123 used over the lifetime of the channel.
2125 Returns:
2126 A Channel.
2127 """
2128 from grpc import _channel # pylint: disable=cyclic-import
2130 return _channel.Channel(
2131 target, () if options is None else options, None, compression
2132 )
2135def secure_channel(target, credentials, options=None, compression=None):
2136 """Creates a secure Channel to a server.
2138 The returned Channel is thread-safe.
2140 Args:
2141 target: The server address.
2142 credentials: A ChannelCredentials instance.
2143 options: An optional list of key-value pairs (:term:`channel_arguments`
2144 in gRPC Core runtime) to configure the channel.
2145 compression: An optional value indicating the compression method to be
2146 used over the lifetime of the channel.
2148 Returns:
2149 A Channel.
2150 """
2151 from grpc import _channel # pylint: disable=cyclic-import
2152 from grpc.experimental import _insecure_channel_credentials
2154 if credentials._credentials is _insecure_channel_credentials:
2155 raise ValueError(
2156 "secure_channel cannot be called with insecure credentials."
2157 + " Call insecure_channel instead."
2158 )
2159 return _channel.Channel(
2160 target,
2161 () if options is None else options,
2162 credentials._credentials,
2163 compression,
2164 )
2167def intercept_channel(channel, *interceptors):
2168 """Intercepts a channel through a set of interceptors.
2170 Args:
2171 channel: A Channel.
2172 interceptors: Zero or more objects of type
2173 UnaryUnaryClientInterceptor,
2174 UnaryStreamClientInterceptor,
2175 StreamUnaryClientInterceptor, or
2176 StreamStreamClientInterceptor.
2177 Interceptors are given control in the order they are listed.
2179 Returns:
2180 A Channel that intercepts each invocation via the provided interceptors.
2182 Raises:
2183 TypeError: If interceptor does not derive from any of
2184 UnaryUnaryClientInterceptor,
2185 UnaryStreamClientInterceptor,
2186 StreamUnaryClientInterceptor, or
2187 StreamStreamClientInterceptor.
2188 """
2189 from grpc import _interceptor # pylint: disable=cyclic-import
2191 return _interceptor.intercept_channel(channel, *interceptors)
2194def server(
2195 thread_pool,
2196 handlers=None,
2197 interceptors=None,
2198 options=None,
2199 maximum_concurrent_rpcs=None,
2200 compression=None,
2201 xds=False,
2202):
2203 """Creates a Server with which RPCs can be serviced.
2205 Args:
2206 thread_pool: A futures.ThreadPoolExecutor to be used by the Server
2207 to execute RPC handlers.
2208 handlers: An optional list of GenericRpcHandlers used for executing RPCs.
2209 More handlers may be added by calling add_generic_rpc_handlers any time
2210 before the server is started.
2211 interceptors: An optional list of ServerInterceptor objects that observe
2212 and optionally manipulate the incoming RPCs before handing them over to
2213 handlers. The interceptors are given control in the order they are
2214 specified. This is an EXPERIMENTAL API.
2215 options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
2216 to configure the channel.
2217 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
2218 will service before returning RESOURCE_EXHAUSTED status, or None to
2219 indicate no limit.
2220 compression: An element of grpc.Compression, e.g.
2221 grpc.Compression.Gzip. This compression algorithm will be used for the
2222 lifetime of the server unless overridden.
2223 xds: If set to true, retrieves server configuration via xDS. This is an
2224 EXPERIMENTAL option.
2226 Returns:
2227 A Server object.
2228 """
2229 from grpc import _server # pylint: disable=cyclic-import
2231 return _server.create_server(
2232 thread_pool,
2233 () if handlers is None else handlers,
2234 () if interceptors is None else interceptors,
2235 () if options is None else options,
2236 maximum_concurrent_rpcs,
2237 compression,
2238 xds,
2239 )
2242@contextlib.contextmanager
2243def _create_servicer_context(rpc_event, state, request_deserializer):
2244 from grpc import _server # pylint: disable=cyclic-import
2246 context = _server._Context(rpc_event, state, request_deserializer)
2247 yield context
2248 context._finalize_state() # pylint: disable=protected-access
2251@enum.unique
2252class Compression(enum.IntEnum):
2253 """Indicates the compression method to be used for an RPC.
2255 Attributes:
2256 NoCompression: Do not use compression algorithm.
2257 Deflate: Use "Deflate" compression algorithm.
2258 Gzip: Use "Gzip" compression algorithm.
2259 """
2261 NoCompression = _compression.NoCompression
2262 Deflate = _compression.Deflate
2263 Gzip = _compression.Gzip
2266################################### __all__ #################################
2268__all__ = (
2269 "AuthMetadataContext",
2270 "AuthMetadataPlugin",
2271 "AuthMetadataPluginCallback",
2272 "Call",
2273 "CallCredentials",
2274 "Channel",
2275 "ChannelConnectivity",
2276 "ChannelCredentials",
2277 "ClientCallDetails",
2278 "Compression",
2279 "Future",
2280 "FutureCancelledError",
2281 "FutureTimeoutError",
2282 "GenericRpcHandler",
2283 "HandlerCallDetails",
2284 "LocalConnectionType",
2285 "RpcContext",
2286 "RpcError",
2287 "RpcMethodHandler",
2288 "Server",
2289 "ServerCertificateConfiguration",
2290 "ServerCredentials",
2291 "ServerInterceptor",
2292 "ServiceRpcHandler",
2293 "ServicerContext",
2294 "Status",
2295 "StatusCode",
2296 "StreamStreamClientInterceptor",
2297 "StreamStreamMultiCallable",
2298 "StreamUnaryClientInterceptor",
2299 "StreamUnaryMultiCallable",
2300 "UnaryStreamClientInterceptor",
2301 "UnaryStreamMultiCallable",
2302 "UnaryUnaryClientInterceptor",
2303 "UnaryUnaryMultiCallable",
2304 "access_token_call_credentials",
2305 "alts_channel_credentials",
2306 "alts_server_credentials",
2307 "channel_ready_future",
2308 "composite_call_credentials",
2309 "composite_channel_credentials",
2310 "compute_engine_channel_credentials",
2311 "dynamic_ssl_server_credentials",
2312 "insecure_channel",
2313 "insecure_server_credentials",
2314 "intercept_channel",
2315 "local_channel_credentials",
2316 "local_server_credentials",
2317 "metadata_call_credentials",
2318 "method_handlers_generic_handler",
2319 "protos",
2320 "protos_and_services",
2321 "secure_channel",
2322 "server",
2323 "services",
2324 "ssl_channel_credentials",
2325 "ssl_server_certificate_configuration",
2326 "ssl_server_credentials",
2327 "stream_stream_rpc_method_handler",
2328 "stream_unary_rpc_method_handler",
2329 "unary_stream_rpc_method_handler",
2330 "unary_unary_rpc_method_handler",
2331 "xds_channel_credentials",
2332 "xds_server_credentials",
2333)
2335############################### Extension Shims ################################
2337# Here to maintain backwards compatibility; avoid using these in new code!
2338try:
2339 import grpc_tools
2341 sys.modules.update({"grpc.tools": grpc_tools})
2342except ImportError:
2343 pass
2344try:
2345 import grpc_health
2347 sys.modules.update({"grpc.health": grpc_health})
2348except ImportError:
2349 pass
2350try:
2351 import grpc_reflection
2353 sys.modules.update({"grpc.reflection": grpc_reflection})
2354except ImportError:
2355 pass
2357# Prevents import order issue in the case of renamed path.
2358if sys.version_info >= (3, 6) and __name__ == "grpc":
2359 from grpc import aio # pylint: disable=ungrouped-imports
2361 sys.modules.update({"grpc.aio": aio})