Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/grpc/__init__.py: 66%
372 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:45 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:45 +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 State can be passed from an interceptor to downstream interceptors
1394 via contextvars. The first interceptor is called from an empty
1395 contextvars.Context, and the same Context is used for downstream
1396 interceptors and for the final handler call. Note that there are no
1397 guarantees that interceptors and handlers will be called from the
1398 same thread.
1400 Args:
1401 continuation: A function that takes a HandlerCallDetails and
1402 proceeds to invoke the next interceptor in the chain, if any,
1403 or the RPC handler lookup logic, with the call details passed
1404 as an argument, and returns an RpcMethodHandler instance if
1405 the RPC is considered serviced, or None otherwise.
1406 handler_call_details: A HandlerCallDetails describing the RPC.
1408 Returns:
1409 An RpcMethodHandler with which the RPC may be serviced if the
1410 interceptor chooses to service this RPC, or None otherwise.
1411 """
1412 raise NotImplementedError()
1415############################# Server Interface ###############################
1418class Server(abc.ABC):
1419 """Services RPCs."""
1421 @abc.abstractmethod
1422 def add_generic_rpc_handlers(self, generic_rpc_handlers):
1423 """Registers GenericRpcHandlers with this Server.
1425 This method is only safe to call before the server is started.
1427 Args:
1428 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1429 used to service RPCs.
1430 """
1431 raise NotImplementedError()
1433 @abc.abstractmethod
1434 def add_insecure_port(self, address):
1435 """Opens an insecure port for accepting RPCs.
1437 This method may only be called before starting the server.
1439 Args:
1440 address: The address for which to open a port. If the port is 0,
1441 or not specified in the address, then gRPC runtime will choose a port.
1443 Returns:
1444 An integer port on which server will accept RPC requests.
1445 """
1446 raise NotImplementedError()
1448 @abc.abstractmethod
1449 def add_secure_port(self, address, server_credentials):
1450 """Opens a secure port for accepting RPCs.
1452 This method may only be called before starting the server.
1454 Args:
1455 address: The address for which to open a port.
1456 if the port is 0, or not specified in the address, then gRPC
1457 runtime will choose a port.
1458 server_credentials: A ServerCredentials object.
1460 Returns:
1461 An integer port on which server will accept RPC requests.
1462 """
1463 raise NotImplementedError()
1465 @abc.abstractmethod
1466 def start(self):
1467 """Starts this Server.
1469 This method may only be called once. (i.e. it is not idempotent).
1470 """
1471 raise NotImplementedError()
1473 @abc.abstractmethod
1474 def stop(self, grace):
1475 """Stops this Server.
1477 This method immediately stop service of new RPCs in all cases.
1479 If a grace period is specified, this method returns immediately
1480 and all RPCs active at the end of the grace period are aborted.
1481 If a grace period is not specified (by passing None for `grace`),
1482 all existing RPCs are aborted immediately and this method
1483 blocks until the last RPC handler terminates.
1485 This method is idempotent and may be called at any time.
1486 Passing a smaller grace value in a subsequent call will have
1487 the effect of stopping the Server sooner (passing None will
1488 have the effect of stopping the server immediately). Passing
1489 a larger grace value in a subsequent call *will not* have the
1490 effect of stopping the server later (i.e. the most restrictive
1491 grace value is used).
1493 Args:
1494 grace: A duration of time in seconds or None.
1496 Returns:
1497 A threading.Event that will be set when this Server has completely
1498 stopped, i.e. when running RPCs either complete or are aborted and
1499 all handlers have terminated.
1500 """
1501 raise NotImplementedError()
1503 def wait_for_termination(self, timeout=None):
1504 """Block current thread until the server stops.
1506 This is an EXPERIMENTAL API.
1508 The wait will not consume computational resources during blocking, and
1509 it will block until one of the two following conditions are met:
1511 1) The server is stopped or terminated;
1512 2) A timeout occurs if timeout is not `None`.
1514 The timeout argument works in the same way as `threading.Event.wait()`.
1515 https://docs.python.org/3/library/threading.html#threading.Event.wait
1517 Args:
1518 timeout: A floating point number specifying a timeout for the
1519 operation in seconds.
1521 Returns:
1522 A bool indicates if the operation times out.
1523 """
1524 raise NotImplementedError()
1527################################# Functions ################################
1530def unary_unary_rpc_method_handler(
1531 behavior, request_deserializer=None, response_serializer=None
1532):
1533 """Creates an RpcMethodHandler for a unary-unary RPC method.
1535 Args:
1536 behavior: The implementation of an RPC that accepts one request
1537 and returns one response.
1538 request_deserializer: An optional :term:`deserializer` for request deserialization.
1539 response_serializer: An optional :term:`serializer` for response serialization.
1541 Returns:
1542 An RpcMethodHandler object that is typically used by grpc.Server.
1543 """
1544 from grpc import _utilities # pylint: disable=cyclic-import
1546 return _utilities.RpcMethodHandler(
1547 False,
1548 False,
1549 request_deserializer,
1550 response_serializer,
1551 behavior,
1552 None,
1553 None,
1554 None,
1555 )
1558def unary_stream_rpc_method_handler(
1559 behavior, request_deserializer=None, response_serializer=None
1560):
1561 """Creates an RpcMethodHandler for a unary-stream RPC method.
1563 Args:
1564 behavior: The implementation of an RPC that accepts one request
1565 and returns an iterator of response values.
1566 request_deserializer: An optional :term:`deserializer` for request deserialization.
1567 response_serializer: An optional :term:`serializer` for response serialization.
1569 Returns:
1570 An RpcMethodHandler object that is typically used by grpc.Server.
1571 """
1572 from grpc import _utilities # pylint: disable=cyclic-import
1574 return _utilities.RpcMethodHandler(
1575 False,
1576 True,
1577 request_deserializer,
1578 response_serializer,
1579 None,
1580 behavior,
1581 None,
1582 None,
1583 )
1586def stream_unary_rpc_method_handler(
1587 behavior, request_deserializer=None, response_serializer=None
1588):
1589 """Creates an RpcMethodHandler for a stream-unary RPC method.
1591 Args:
1592 behavior: The implementation of an RPC that accepts an iterator of
1593 request values and returns a single response value.
1594 request_deserializer: An optional :term:`deserializer` for request deserialization.
1595 response_serializer: An optional :term:`serializer` for response serialization.
1597 Returns:
1598 An RpcMethodHandler object that is typically used by grpc.Server.
1599 """
1600 from grpc import _utilities # pylint: disable=cyclic-import
1602 return _utilities.RpcMethodHandler(
1603 True,
1604 False,
1605 request_deserializer,
1606 response_serializer,
1607 None,
1608 None,
1609 behavior,
1610 None,
1611 )
1614def stream_stream_rpc_method_handler(
1615 behavior, request_deserializer=None, response_serializer=None
1616):
1617 """Creates an RpcMethodHandler for a stream-stream RPC method.
1619 Args:
1620 behavior: The implementation of an RPC that accepts an iterator of
1621 request values and returns an iterator of response values.
1622 request_deserializer: An optional :term:`deserializer` for request deserialization.
1623 response_serializer: An optional :term:`serializer` for response serialization.
1625 Returns:
1626 An RpcMethodHandler object that is typically used by grpc.Server.
1627 """
1628 from grpc import _utilities # pylint: disable=cyclic-import
1630 return _utilities.RpcMethodHandler(
1631 True,
1632 True,
1633 request_deserializer,
1634 response_serializer,
1635 None,
1636 None,
1637 None,
1638 behavior,
1639 )
1642def method_handlers_generic_handler(service, method_handlers):
1643 """Creates a GenericRpcHandler from RpcMethodHandlers.
1645 Args:
1646 service: The name of the service that is implemented by the
1647 method_handlers.
1648 method_handlers: A dictionary that maps method names to corresponding
1649 RpcMethodHandler.
1651 Returns:
1652 A GenericRpcHandler. This is typically added to the grpc.Server object
1653 with add_generic_rpc_handlers() before starting the server.
1654 """
1655 from grpc import _utilities # pylint: disable=cyclic-import
1657 return _utilities.DictionaryGenericHandler(service, method_handlers)
1660def ssl_channel_credentials(
1661 root_certificates=None, private_key=None, certificate_chain=None
1662):
1663 """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1665 Args:
1666 root_certificates: The PEM-encoded root certificates as a byte string,
1667 or None to retrieve them from a default location chosen by gRPC
1668 runtime.
1669 private_key: The PEM-encoded private key as a byte string, or None if no
1670 private key should be used.
1671 certificate_chain: The PEM-encoded certificate chain as a byte string
1672 to use or None if no certificate chain should be used.
1674 Returns:
1675 A ChannelCredentials for use with an SSL-enabled Channel.
1676 """
1677 return ChannelCredentials(
1678 _cygrpc.SSLChannelCredentials(
1679 root_certificates, private_key, certificate_chain
1680 )
1681 )
1684def xds_channel_credentials(fallback_credentials=None):
1685 """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL
1686 API.
1688 Args:
1689 fallback_credentials: Credentials to use in case it is not possible to
1690 establish a secure connection via xDS. If no fallback_credentials
1691 argument is supplied, a default SSLChannelCredentials is used.
1692 """
1693 fallback_credentials = (
1694 ssl_channel_credentials()
1695 if fallback_credentials is None
1696 else fallback_credentials
1697 )
1698 return ChannelCredentials(
1699 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials)
1700 )
1703def metadata_call_credentials(metadata_plugin, name=None):
1704 """Construct CallCredentials from an AuthMetadataPlugin.
1706 Args:
1707 metadata_plugin: An AuthMetadataPlugin to use for authentication.
1708 name: An optional name for the plugin.
1710 Returns:
1711 A CallCredentials.
1712 """
1713 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1715 return _plugin_wrapping.metadata_plugin_call_credentials(
1716 metadata_plugin, name
1717 )
1720def access_token_call_credentials(access_token):
1721 """Construct CallCredentials from an access token.
1723 Args:
1724 access_token: A string to place directly in the http request
1725 authorization header, for example
1726 "authorization: Bearer <access_token>".
1728 Returns:
1729 A CallCredentials.
1730 """
1731 from grpc import _auth # pylint: disable=cyclic-import
1732 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1734 return _plugin_wrapping.metadata_plugin_call_credentials(
1735 _auth.AccessTokenAuthMetadataPlugin(access_token), None
1736 )
1739def composite_call_credentials(*call_credentials):
1740 """Compose multiple CallCredentials to make a new CallCredentials.
1742 Args:
1743 *call_credentials: At least two CallCredentials objects.
1745 Returns:
1746 A CallCredentials object composed of the given CallCredentials objects.
1747 """
1748 return CallCredentials(
1749 _cygrpc.CompositeCallCredentials(
1750 tuple(
1751 single_call_credentials._credentials
1752 for single_call_credentials in call_credentials
1753 )
1754 )
1755 )
1758def composite_channel_credentials(channel_credentials, *call_credentials):
1759 """Compose a ChannelCredentials and one or more CallCredentials objects.
1761 Args:
1762 channel_credentials: A ChannelCredentials object.
1763 *call_credentials: One or more CallCredentials objects.
1765 Returns:
1766 A ChannelCredentials composed of the given ChannelCredentials and
1767 CallCredentials objects.
1768 """
1769 return ChannelCredentials(
1770 _cygrpc.CompositeChannelCredentials(
1771 tuple(
1772 single_call_credentials._credentials
1773 for single_call_credentials in call_credentials
1774 ),
1775 channel_credentials._credentials,
1776 )
1777 )
1780def ssl_server_credentials(
1781 private_key_certificate_chain_pairs,
1782 root_certificates=None,
1783 require_client_auth=False,
1784):
1785 """Creates a ServerCredentials for use with an SSL-enabled Server.
1787 Args:
1788 private_key_certificate_chain_pairs: A list of pairs of the form
1789 [PEM-encoded private key, PEM-encoded certificate chain].
1790 root_certificates: An optional byte string of PEM-encoded client root
1791 certificates that the server will use to verify client authentication.
1792 If omitted, require_client_auth must also be False.
1793 require_client_auth: A boolean indicating whether or not to require
1794 clients to be authenticated. May only be True if root_certificates
1795 is not None.
1797 Returns:
1798 A ServerCredentials for use with an SSL-enabled Server. Typically, this
1799 object is an argument to add_secure_port() method during server setup.
1800 """
1801 if not private_key_certificate_chain_pairs:
1802 raise ValueError(
1803 "At least one private key-certificate chain pair is required!"
1804 )
1805 elif require_client_auth and root_certificates is None:
1806 raise ValueError(
1807 "Illegal to require client auth without providing root"
1808 " certificates!"
1809 )
1810 else:
1811 return ServerCredentials(
1812 _cygrpc.server_credentials_ssl(
1813 root_certificates,
1814 [
1815 _cygrpc.SslPemKeyCertPair(key, pem)
1816 for key, pem in private_key_certificate_chain_pairs
1817 ],
1818 require_client_auth,
1819 )
1820 )
1823def xds_server_credentials(fallback_credentials):
1824 """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL
1825 API.
1827 Args:
1828 fallback_credentials: Credentials to use in case it is not possible to
1829 establish a secure connection via xDS. No default value is provided.
1830 """
1831 return ServerCredentials(
1832 _cygrpc.xds_server_credentials(fallback_credentials._credentials)
1833 )
1836def insecure_server_credentials():
1837 """Creates a credentials object directing the server to use no credentials.
1838 This is an EXPERIMENTAL API.
1840 This object cannot be used directly in a call to `add_secure_port`.
1841 Instead, it should be used to construct other credentials objects, e.g.
1842 with xds_server_credentials.
1843 """
1844 return ServerCredentials(_cygrpc.insecure_server_credentials())
1847def ssl_server_certificate_configuration(
1848 private_key_certificate_chain_pairs, root_certificates=None
1849):
1850 """Creates a ServerCertificateConfiguration for use with a Server.
1852 Args:
1853 private_key_certificate_chain_pairs: A collection of pairs of
1854 the form [PEM-encoded private key, PEM-encoded certificate
1855 chain].
1856 root_certificates: An optional byte string of PEM-encoded client root
1857 certificates that the server will use to verify client authentication.
1859 Returns:
1860 A ServerCertificateConfiguration that can be returned in the certificate
1861 configuration fetching callback.
1862 """
1863 if private_key_certificate_chain_pairs:
1864 return ServerCertificateConfiguration(
1865 _cygrpc.server_certificate_config_ssl(
1866 root_certificates,
1867 [
1868 _cygrpc.SslPemKeyCertPair(key, pem)
1869 for key, pem in private_key_certificate_chain_pairs
1870 ],
1871 )
1872 )
1873 else:
1874 raise ValueError(
1875 "At least one private key-certificate chain pair is required!"
1876 )
1879def dynamic_ssl_server_credentials(
1880 initial_certificate_configuration,
1881 certificate_configuration_fetcher,
1882 require_client_authentication=False,
1883):
1884 """Creates a ServerCredentials for use with an SSL-enabled Server.
1886 Args:
1887 initial_certificate_configuration (ServerCertificateConfiguration): The
1888 certificate configuration with which the server will be initialized.
1889 certificate_configuration_fetcher (callable): A callable that takes no
1890 arguments and should return a ServerCertificateConfiguration to
1891 replace the server's current certificate, or None for no change
1892 (i.e., the server will continue its current certificate
1893 config). The library will call this callback on *every* new
1894 client connection before starting the TLS handshake with the
1895 client, thus allowing the user application to optionally
1896 return a new ServerCertificateConfiguration that the server will then
1897 use for the handshake.
1898 require_client_authentication: A boolean indicating whether or not to
1899 require clients to be authenticated.
1901 Returns:
1902 A ServerCredentials.
1903 """
1904 return ServerCredentials(
1905 _cygrpc.server_credentials_ssl_dynamic_cert_config(
1906 initial_certificate_configuration,
1907 certificate_configuration_fetcher,
1908 require_client_authentication,
1909 )
1910 )
1913@enum.unique
1914class LocalConnectionType(enum.Enum):
1915 """Types of local connection for local credential creation.
1917 Attributes:
1918 UDS: Unix domain socket connections
1919 LOCAL_TCP: Local TCP connections.
1920 """
1922 UDS = _cygrpc.LocalConnectionType.uds
1923 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
1926def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1927 """Creates a local ChannelCredentials used for local connections.
1929 This is an EXPERIMENTAL API.
1931 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1932 also UDS connections.
1934 The connections created by local channel credentials are not
1935 encrypted, but will be checked if they are local or not.
1936 The UDS connections are considered secure by providing peer authentication
1937 and data confidentiality while TCP connections are considered insecure.
1939 It is allowed to transmit call credentials over connections created by
1940 local channel credentials.
1942 Local channel credentials are useful for 1) eliminating insecure_channel usage;
1943 2) enable unit testing for call credentials without setting up secrets.
1945 Args:
1946 local_connect_type: Local connection type (either
1947 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1949 Returns:
1950 A ChannelCredentials for use with a local Channel
1951 """
1952 return ChannelCredentials(
1953 _cygrpc.channel_credentials_local(local_connect_type.value)
1954 )
1957def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1958 """Creates a local ServerCredentials used for local connections.
1960 This is an EXPERIMENTAL API.
1962 Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1963 also UDS connections.
1965 The connections created by local server credentials are not
1966 encrypted, but will be checked if they are local or not.
1967 The UDS connections are considered secure by providing peer authentication
1968 and data confidentiality while TCP connections are considered insecure.
1970 It is allowed to transmit call credentials over connections created by local
1971 server credentials.
1973 Local server credentials are useful for 1) eliminating insecure_channel usage;
1974 2) enable unit testing for call credentials without setting up secrets.
1976 Args:
1977 local_connect_type: Local connection type (either
1978 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1980 Returns:
1981 A ServerCredentials for use with a local Server
1982 """
1983 return ServerCredentials(
1984 _cygrpc.server_credentials_local(local_connect_type.value)
1985 )
1988def alts_channel_credentials(service_accounts=None):
1989 """Creates a ChannelCredentials for use with an ALTS-enabled Channel.
1991 This is an EXPERIMENTAL API.
1992 ALTS credentials API can only be used in GCP environment as it relies on
1993 handshaker service being available. For more info about ALTS see
1994 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1996 Args:
1997 service_accounts: A list of server identities accepted by the client.
1998 If target service accounts are provided and none of them matches the
1999 peer identity of the server, handshake will fail. The arg can be empty
2000 if the client does not have any information about trusted server
2001 identity.
2002 Returns:
2003 A ChannelCredentials for use with an ALTS-enabled Channel
2004 """
2005 return ChannelCredentials(
2006 _cygrpc.channel_credentials_alts(service_accounts or [])
2007 )
2010def alts_server_credentials():
2011 """Creates a ServerCredentials for use with an ALTS-enabled connection.
2013 This is an EXPERIMENTAL API.
2014 ALTS credentials API can only be used in GCP environment as it relies on
2015 handshaker service being available. For more info about ALTS see
2016 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2018 Returns:
2019 A ServerCredentials for use with an ALTS-enabled Server
2020 """
2021 return ServerCredentials(_cygrpc.server_credentials_alts())
2024def compute_engine_channel_credentials(call_credentials):
2025 """Creates a compute engine channel credential.
2027 This credential can only be used in a GCP environment as it relies on
2028 a handshaker service. For more info about ALTS, see
2029 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2031 This channel credential is expected to be used as part of a composite
2032 credential in conjunction with a call credentials that authenticates the
2033 VM's default service account. If used with any other sort of call
2034 credential, the connection may suddenly and unexpectedly begin failing RPCs.
2035 """
2036 return ChannelCredentials(
2037 _cygrpc.channel_credentials_compute_engine(
2038 call_credentials._credentials
2039 )
2040 )
2043def channel_ready_future(channel):
2044 """Creates a Future that tracks when a Channel is ready.
2046 Cancelling the Future does not affect the channel's state machine.
2047 It merely decouples the Future from channel state machine.
2049 Args:
2050 channel: A Channel object.
2052 Returns:
2053 A Future object that matures when the channel connectivity is
2054 ChannelConnectivity.READY.
2055 """
2056 from grpc import _utilities # pylint: disable=cyclic-import
2058 return _utilities.channel_ready_future(channel)
2061def insecure_channel(target, options=None, compression=None):
2062 """Creates an insecure Channel to a server.
2064 The returned Channel is thread-safe.
2066 Args:
2067 target: The server address
2068 options: An optional list of key-value pairs (:term:`channel_arguments`
2069 in gRPC Core runtime) to configure the channel.
2070 compression: An optional value indicating the compression method to be
2071 used over the lifetime of the channel.
2073 Returns:
2074 A Channel.
2075 """
2076 from grpc import _channel # pylint: disable=cyclic-import
2078 return _channel.Channel(
2079 target, () if options is None else options, None, compression
2080 )
2083def secure_channel(target, credentials, options=None, compression=None):
2084 """Creates a secure Channel to a server.
2086 The returned Channel is thread-safe.
2088 Args:
2089 target: The server address.
2090 credentials: A ChannelCredentials instance.
2091 options: An optional list of key-value pairs (:term:`channel_arguments`
2092 in gRPC Core runtime) to configure the channel.
2093 compression: An optional value indicating the compression method to be
2094 used over the lifetime of the channel.
2096 Returns:
2097 A Channel.
2098 """
2099 from grpc import _channel # pylint: disable=cyclic-import
2100 from grpc.experimental import _insecure_channel_credentials
2102 if credentials._credentials is _insecure_channel_credentials:
2103 raise ValueError(
2104 "secure_channel cannot be called with insecure credentials."
2105 + " Call insecure_channel instead."
2106 )
2107 return _channel.Channel(
2108 target,
2109 () if options is None else options,
2110 credentials._credentials,
2111 compression,
2112 )
2115def intercept_channel(channel, *interceptors):
2116 """Intercepts a channel through a set of interceptors.
2118 Args:
2119 channel: A Channel.
2120 interceptors: Zero or more objects of type
2121 UnaryUnaryClientInterceptor,
2122 UnaryStreamClientInterceptor,
2123 StreamUnaryClientInterceptor, or
2124 StreamStreamClientInterceptor.
2125 Interceptors are given control in the order they are listed.
2127 Returns:
2128 A Channel that intercepts each invocation via the provided interceptors.
2130 Raises:
2131 TypeError: If interceptor does not derive from any of
2132 UnaryUnaryClientInterceptor,
2133 UnaryStreamClientInterceptor,
2134 StreamUnaryClientInterceptor, or
2135 StreamStreamClientInterceptor.
2136 """
2137 from grpc import _interceptor # pylint: disable=cyclic-import
2139 return _interceptor.intercept_channel(channel, *interceptors)
2142def server(
2143 thread_pool,
2144 handlers=None,
2145 interceptors=None,
2146 options=None,
2147 maximum_concurrent_rpcs=None,
2148 compression=None,
2149 xds=False,
2150):
2151 """Creates a Server with which RPCs can be serviced.
2153 Args:
2154 thread_pool: A futures.ThreadPoolExecutor to be used by the Server
2155 to execute RPC handlers.
2156 handlers: An optional list of GenericRpcHandlers used for executing RPCs.
2157 More handlers may be added by calling add_generic_rpc_handlers any time
2158 before the server is started.
2159 interceptors: An optional list of ServerInterceptor objects that observe
2160 and optionally manipulate the incoming RPCs before handing them over to
2161 handlers. The interceptors are given control in the order they are
2162 specified. This is an EXPERIMENTAL API.
2163 options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
2164 to configure the channel.
2165 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
2166 will service before returning RESOURCE_EXHAUSTED status, or None to
2167 indicate no limit.
2168 compression: An element of grpc.compression, e.g.
2169 grpc.compression.Gzip. This compression algorithm will be used for the
2170 lifetime of the server unless overridden.
2171 xds: If set to true, retrieves server configuration via xDS. This is an
2172 EXPERIMENTAL option.
2174 Returns:
2175 A Server object.
2176 """
2177 from grpc import _server # pylint: disable=cyclic-import
2179 return _server.create_server(
2180 thread_pool,
2181 () if handlers is None else handlers,
2182 () if interceptors is None else interceptors,
2183 () if options is None else options,
2184 maximum_concurrent_rpcs,
2185 compression,
2186 xds,
2187 )
2190@contextlib.contextmanager
2191def _create_servicer_context(rpc_event, state, request_deserializer):
2192 from grpc import _server # pylint: disable=cyclic-import
2194 context = _server._Context(rpc_event, state, request_deserializer)
2195 yield context
2196 context._finalize_state() # pylint: disable=protected-access
2199@enum.unique
2200class Compression(enum.IntEnum):
2201 """Indicates the compression method to be used for an RPC.
2203 Attributes:
2204 NoCompression: Do not use compression algorithm.
2205 Deflate: Use "Deflate" compression algorithm.
2206 Gzip: Use "Gzip" compression algorithm.
2207 """
2209 NoCompression = _compression.NoCompression
2210 Deflate = _compression.Deflate
2211 Gzip = _compression.Gzip
2214################################### __all__ #################################
2216__all__ = (
2217 "FutureTimeoutError",
2218 "FutureCancelledError",
2219 "Future",
2220 "ChannelConnectivity",
2221 "StatusCode",
2222 "Status",
2223 "RpcError",
2224 "RpcContext",
2225 "Call",
2226 "ChannelCredentials",
2227 "CallCredentials",
2228 "AuthMetadataContext",
2229 "AuthMetadataPluginCallback",
2230 "AuthMetadataPlugin",
2231 "Compression",
2232 "ClientCallDetails",
2233 "ServerCertificateConfiguration",
2234 "ServerCredentials",
2235 "LocalConnectionType",
2236 "UnaryUnaryMultiCallable",
2237 "UnaryStreamMultiCallable",
2238 "StreamUnaryMultiCallable",
2239 "StreamStreamMultiCallable",
2240 "UnaryUnaryClientInterceptor",
2241 "UnaryStreamClientInterceptor",
2242 "StreamUnaryClientInterceptor",
2243 "StreamStreamClientInterceptor",
2244 "Channel",
2245 "ServicerContext",
2246 "RpcMethodHandler",
2247 "HandlerCallDetails",
2248 "GenericRpcHandler",
2249 "ServiceRpcHandler",
2250 "Server",
2251 "ServerInterceptor",
2252 "unary_unary_rpc_method_handler",
2253 "unary_stream_rpc_method_handler",
2254 "stream_unary_rpc_method_handler",
2255 "stream_stream_rpc_method_handler",
2256 "method_handlers_generic_handler",
2257 "ssl_channel_credentials",
2258 "metadata_call_credentials",
2259 "access_token_call_credentials",
2260 "composite_call_credentials",
2261 "composite_channel_credentials",
2262 "compute_engine_channel_credentials",
2263 "local_channel_credentials",
2264 "local_server_credentials",
2265 "alts_channel_credentials",
2266 "alts_server_credentials",
2267 "ssl_server_credentials",
2268 "ssl_server_certificate_configuration",
2269 "dynamic_ssl_server_credentials",
2270 "channel_ready_future",
2271 "insecure_channel",
2272 "secure_channel",
2273 "intercept_channel",
2274 "server",
2275 "protos",
2276 "services",
2277 "protos_and_services",
2278 "xds_channel_credentials",
2279 "xds_server_credentials",
2280 "insecure_server_credentials",
2281)
2283############################### Extension Shims ################################
2285# Here to maintain backwards compatibility; avoid using these in new code!
2286try:
2287 import grpc_tools
2289 sys.modules.update({"grpc.tools": grpc_tools})
2290except ImportError:
2291 pass
2292try:
2293 import grpc_health
2295 sys.modules.update({"grpc.health": grpc_health})
2296except ImportError:
2297 pass
2298try:
2299 import grpc_reflection
2301 sys.modules.update({"grpc.reflection": grpc_reflection})
2302except ImportError:
2303 pass
2305# Prevents import order issue in the case of renamed path.
2306if sys.version_info >= (3, 6) and __name__ == "grpc":
2307 from grpc import aio # pylint: disable=ungrouped-imports
2309 sys.modules.update({"grpc.aio": aio})