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