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.""" 15 16import abc 17import contextlib 18import enum 19import logging 20import sys 21 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 27 28logging.getLogger(__name__).addHandler(logging.NullHandler()) 29 30try: 31 # pylint: disable=ungrouped-imports 32 from grpc._grpcio_metadata import __version__ 33except ImportError: 34 __version__ = "dev0" 35 36############################## Future Interface ############################### 37 38 39class FutureTimeoutError(Exception): 40 """Indicates that a method call on a Future timed out.""" 41 42 43class FutureCancelledError(Exception): 44 """Indicates that the computation underlying a Future was cancelled.""" 45 46 47class Future(abc.ABC): 48 """A representation of a computation in another control flow. 49 50 Computations represented by a Future may be yet to be begun, 51 may be ongoing, or may have already completed. 52 """ 53 54 @abc.abstractmethod 55 def cancel(self): 56 """Attempts to cancel the computation. 57 58 This method does not block. 59 60 Returns: 61 bool: 62 Returns True if the computation was canceled. 63 64 Returns False under all other circumstances, for example: 65 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() 72 73 @abc.abstractmethod 74 def cancelled(self): 75 """Describes whether the computation was cancelled. 76 77 This method does not block. 78 79 Returns: 80 bool: 81 Returns True if the computation was cancelled before its result became 82 available. 83 84 Returns False under all other circumstances, for example: 85 86 1. computation was not cancelled. 87 2. computation's result is available. 88 """ 89 raise NotImplementedError() 90 91 @abc.abstractmethod 92 def running(self): 93 """Describes whether the computation is taking place. 94 95 This method does not block. 96 97 Returns: 98 Returns True if the computation is scheduled for execution or 99 currently executing. 100 101 Returns False if the computation already executed or was cancelled. 102 """ 103 raise NotImplementedError() 104 105 @abc.abstractmethod 106 def done(self): 107 """Describes whether the computation has taken place. 108 109 This method does not block. 110 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() 119 120 @abc.abstractmethod 121 def result(self, timeout=None): 122 """Returns the result of the computation or raises its exception. 123 124 This method may return immediately or may block. 125 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. 130 131 Returns: 132 The return value of the computation. 133 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() 142 143 @abc.abstractmethod 144 def exception(self, timeout=None): 145 """Return the exception raised by the computation. 146 147 This method may return immediately or may block. 148 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. 153 154 Returns: 155 The exception raised by the computation, or None if the computation 156 did not raise an exception. 157 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() 164 165 @abc.abstractmethod 166 def traceback(self, timeout=None): 167 """Access the traceback of the exception raised by the computation. 168 169 This method may return immediately or may block. 170 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. 175 176 Returns: 177 The traceback of the exception raised by the computation, or None 178 if the computation did not raise an exception. 179 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() 186 187 @abc.abstractmethod 188 def add_done_callback(self, fn): 189 """Adds a function to be called at completion of the computation. 190 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. 194 195 If the computation has already completed, the callback will be called 196 immediately. 197 198 Exceptions raised in the callback will be logged at ERROR level, but 199 will not terminate any threads of execution. 200 201 Args: 202 fn: A callable taking this Future object as its single parameter. 203 """ 204 raise NotImplementedError() 205 206 207################################ gRPC Enums ################################## 208 209 210@enum.unique 211class ChannelConnectivity(enum.Enum): 212 """Mirrors grpc_connectivity_state in the gRPC Core. 213 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 """ 222 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") 231 232 233@enum.unique 234class StatusCode(enum.Enum): 235 """Mirrors grpc_status_code in the gRPC Core. 236 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 """ 262 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") 292 293 294############################# gRPC Status ################################ 295 296 297class Status(abc.ABC): 298 """Describes the status of an RPC. 299 300 This is an EXPERIMENTAL API. 301 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 """ 308 309 310############################# gRPC Exceptions ################################ 311 312 313class RpcError(Exception): 314 """Raised by the gRPC library to indicate non-OK-status RPC termination.""" 315 316 317############################## Shared Context ################################ 318 319 320class RpcContext(abc.ABC): 321 """Provides RPC-related information and action.""" 322 323 @abc.abstractmethod 324 def is_active(self): 325 """Describes whether the RPC is active or has terminated. 326 327 Returns: 328 bool: 329 True if RPC is active, False otherwise. 330 """ 331 raise NotImplementedError() 332 333 @abc.abstractmethod 334 def time_remaining(self): 335 """Describes the length of allowed time remaining for the RPC. 336 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() 343 344 @abc.abstractmethod 345 def cancel(self): 346 """Cancels the RPC. 347 348 Idempotent and has no effect if the RPC has already terminated. 349 """ 350 raise NotImplementedError() 351 352 @abc.abstractmethod 353 def add_callback(self, callback): 354 """Registers a callback to be called on RPC termination. 355 356 Args: 357 callback: A no-parameter callable to be called on RPC termination. 358 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() 365 366 367######################### Invocation-Side Context ############################ 368 369 370class Call(RpcContext, metaclass=abc.ABCMeta): 371 """Invocation-side utility object for an RPC.""" 372 373 @abc.abstractmethod 374 def initial_metadata(self): 375 """Accesses the initial metadata sent by the server. 376 377 This method blocks until the value is available. 378 379 Returns: 380 The initial :term:`metadata`. 381 """ 382 raise NotImplementedError() 383 384 @abc.abstractmethod 385 def trailing_metadata(self): 386 """Accesses the trailing metadata sent by the server. 387 388 This method blocks until the value is available. 389 390 Returns: 391 The trailing :term:`metadata`. 392 """ 393 raise NotImplementedError() 394 395 @abc.abstractmethod 396 def code(self): 397 """Accesses the status code sent by the server. 398 399 This method blocks until the value is available. 400 401 Returns: 402 The StatusCode value for the RPC. 403 """ 404 raise NotImplementedError() 405 406 @abc.abstractmethod 407 def details(self): 408 """Accesses the details sent by the server. 409 410 This method blocks until the value is available. 411 412 Returns: 413 The details string of the RPC. 414 """ 415 raise NotImplementedError() 416 417 418############## Invocation-Side Interceptor Interfaces & Classes ############## 419 420 421class ClientCallDetails(abc.ABC): 422 """Describes an RPC to be invoked. 423 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 """ 434 435 436class UnaryUnaryClientInterceptor(abc.ABC): 437 """Affords intercepting unary-unary invocations.""" 438 439 @abc.abstractmethod 440 def intercept_unary_unary(self, continuation, client_call_details, request): 441 """Intercepts a unary-unary invocation asynchronously. 442 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. 459 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() 468 469 470class UnaryStreamClientInterceptor(abc.ABC): 471 """Affords intercepting unary-stream invocations.""" 472 473 @abc.abstractmethod 474 def intercept_unary_stream( 475 self, continuation, client_call_details, request 476 ): 477 """Intercepts a unary-stream invocation. 478 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. 494 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() 503 504 505class StreamUnaryClientInterceptor(abc.ABC): 506 """Affords intercepting stream-unary invocations.""" 507 508 @abc.abstractmethod 509 def intercept_stream_unary( 510 self, continuation, client_call_details, request_iterator 511 ): 512 """Intercepts a stream-unary invocation asynchronously. 513 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. 529 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() 538 539 540class StreamStreamClientInterceptor(abc.ABC): 541 """Affords intercepting stream-stream invocations.""" 542 543 @abc.abstractmethod 544 def intercept_stream_stream( 545 self, continuation, client_call_details, request_iterator 546 ): 547 """Intercepts a stream-stream invocation. 548 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. 564 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() 573 574 575############ Authentication & Authorization Interfaces & Classes ############# 576 577 578class ChannelCredentials(object): 579 """An encapsulation of the data required to create a secure Channel. 580 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 """ 586 587 def __init__(self, credentials): 588 self._credentials = credentials 589 590 591class CallCredentials(object): 592 """An encapsulation of the data required to assert an identity over a call. 593 594 A CallCredentials has to be used with secure Channel, otherwise the 595 metadata will not be transmitted to the server. 596 597 A CallCredentials may be composed with ChannelCredentials to always assert 598 identity for every call over that Channel. 599 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 """ 603 604 def __init__(self, credentials): 605 self._credentials = credentials 606 607 608class AuthMetadataContext(abc.ABC): 609 """Provides information to call credentials metadata plugins. 610 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 """ 615 616 617class AuthMetadataPluginCallback(abc.ABC): 618 """Callback object received by a metadata plugin.""" 619 620 def __call__(self, metadata, error): 621 """Passes to the gRPC runtime authentication metadata for an RPC. 622 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() 628 629 630class AuthMetadataPlugin(abc.ABC): 631 """A specification for custom authentication.""" 632 633 def __call__(self, context, callback): 634 """Implements authentication by passing metadata to a callback. 635 636 This method will be invoked asynchronously in a separate thread. 637 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() 645 646 647class ServerCredentials(object): 648 """An encapsulation of the data required to open a secure port on a Server. 649 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 """ 653 654 def __init__(self, credentials): 655 self._credentials = credentials 656 657 658class ServerCertificateConfiguration(object): 659 """A certificate configuration for use with an SSL-enabled Server. 660 661 Instances of this class can be returned in the certificate configuration 662 fetching callback. 663 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 """ 668 669 def __init__(self, certificate_configuration): 670 self._certificate_configuration = certificate_configuration 671 672 673######################## Multi-Callable Interfaces ########################### 674 675 676class UnaryUnaryMultiCallable(abc.ABC): 677 """Affords invoking a unary-unary RPC from client-side.""" 678 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. 690 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. 702 703 Returns: 704 The response value for the RPC. 705 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() 712 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. 724 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. 736 737 Returns: 738 The response value for the RPC and a Call value for the RPC. 739 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() 746 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. 758 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. 770 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() 779 780 781class UnaryStreamMultiCallable(abc.ABC): 782 """Affords invoking a unary-stream RPC from client-side.""" 783 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. 795 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. 807 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() 815 816 817class StreamUnaryMultiCallable(abc.ABC): 818 """Affords invoking a stream-unary RPC from client-side.""" 819 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. 831 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. 844 845 Returns: 846 The response value for the RPC. 847 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() 854 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. 866 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. 879 880 Returns: 881 The response value for the RPC and a Call object for the RPC. 882 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() 889 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. 901 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. 913 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() 922 923 924class StreamStreamMultiCallable(abc.ABC): 925 """Affords invoking a stream-stream RPC on client-side.""" 926 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. 938 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. 950 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() 958 959 960############################# Channel Interface ############################## 961 962 963class Channel(abc.ABC): 964 """Affords RPC invocation via generic methods on client-side. 965 966 Channel objects implement the Context Manager type, although they need not 967 support being entered and exited multiple times. 968 """ 969 970 @abc.abstractmethod 971 def subscribe(self, callback, try_to_connect=False): 972 """Subscribe to this Channel's connectivity state machine. 973 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. 978 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() 990 991 @abc.abstractmethod 992 def unsubscribe(self, callback): 993 """Unsubscribes a subscribed callback from this Channel's connectivity. 994 995 Args: 996 callback: A callable previously registered with this Channel from 997 having been passed to its "subscribe" method. 998 """ 999 raise NotImplementedError() 1000 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. 1010 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. 1020 1021 Returns: 1022 A UnaryUnaryMultiCallable value for the named unary-unary method. 1023 """ 1024 raise NotImplementedError() 1025 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. 1035 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. 1045 1046 Returns: 1047 A UnaryStreamMultiCallable value for the name unary-stream method. 1048 """ 1049 raise NotImplementedError() 1050 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. 1060 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. 1070 1071 Returns: 1072 A StreamUnaryMultiCallable value for the named stream-unary method. 1073 """ 1074 raise NotImplementedError() 1075 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. 1085 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. 1095 1096 Returns: 1097 A StreamStreamMultiCallable value for the named stream-stream method. 1098 """ 1099 raise NotImplementedError() 1100 1101 @abc.abstractmethod 1102 def close(self): 1103 """Closes this Channel and releases all resources held by it. 1104 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. 1107 1108 This method is idempotent. 1109 """ 1110 raise NotImplementedError() 1111 1112 def __enter__(self): 1113 """Enters the runtime context related to the channel object.""" 1114 raise NotImplementedError() 1115 1116 def __exit__(self, exc_type, exc_val, exc_tb): 1117 """Exits the runtime context related to the channel object.""" 1118 raise NotImplementedError() 1119 1120 1121########################## Service-Side Context ############################## 1122 1123 1124class ServicerContext(RpcContext, metaclass=abc.ABCMeta): 1125 """A context object passed to method implementations.""" 1126 1127 @abc.abstractmethod 1128 def invocation_metadata(self): 1129 """Accesses the metadata sent by the client. 1130 1131 Returns: 1132 The invocation :term:`metadata`. 1133 """ 1134 raise NotImplementedError() 1135 1136 @abc.abstractmethod 1137 def peer(self): 1138 """Identifies the peer that invoked the RPC being serviced. 1139 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() 1145 1146 @abc.abstractmethod 1147 def peer_identities(self): 1148 """Gets one or more peer identity(s). 1149 1150 Equivalent to 1151 servicer_context.auth_context().get(servicer_context.peer_identity_key()) 1152 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() 1158 1159 @abc.abstractmethod 1160 def peer_identity_key(self): 1161 """The auth property used to identify the peer. 1162 1163 For example, "x509_common_name" or "x509_subject_alternative_name" are 1164 used to identify an SSL peer. 1165 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() 1171 1172 @abc.abstractmethod 1173 def auth_context(self): 1174 """Gets the auth context for the call. 1175 1176 Returns: 1177 A map of strings to an iterable of bytes for each auth property. 1178 """ 1179 raise NotImplementedError() 1180 1181 def set_compression(self, compression): 1182 """Set the compression algorithm to be used for the entire call. 1183 1184 Args: 1185 compression: An element of grpc.compression, e.g. 1186 grpc.compression.Gzip. 1187 """ 1188 raise NotImplementedError() 1189 1190 @abc.abstractmethod 1191 def send_initial_metadata(self, initial_metadata): 1192 """Sends the initial metadata value to the client. 1193 1194 This method need not be called by implementations if they have no 1195 metadata to add to what the gRPC runtime will transmit. 1196 1197 Args: 1198 initial_metadata: The initial :term:`metadata`. 1199 """ 1200 raise NotImplementedError() 1201 1202 @abc.abstractmethod 1203 def set_trailing_metadata(self, trailing_metadata): 1204 """Sets the trailing metadata for the RPC. 1205 1206 Sets the trailing metadata to be sent upon completion of the RPC. 1207 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. 1211 1212 This method need not be called by implementations if they have no 1213 metadata to add to what the gRPC runtime will transmit. 1214 1215 Args: 1216 trailing_metadata: The trailing :term:`metadata`. 1217 """ 1218 raise NotImplementedError() 1219 1220 def trailing_metadata(self): 1221 """Access value to be used as trailing metadata upon RPC completion. 1222 1223 This is an EXPERIMENTAL API. 1224 1225 Returns: 1226 The trailing :term:`metadata` for the RPC. 1227 """ 1228 raise NotImplementedError() 1229 1230 @abc.abstractmethod 1231 def abort(self, code, details): 1232 """Raises an exception to terminate the RPC with a non-OK status. 1233 1234 The code and details passed as arguments will supercede any existing 1235 ones. 1236 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. 1242 1243 Raises: 1244 Exception: An exception is always raised to signal the abortion the 1245 RPC to the gRPC runtime. 1246 """ 1247 raise NotImplementedError() 1248 1249 @abc.abstractmethod 1250 def abort_with_status(self, status): 1251 """Raises an exception to terminate the RPC with a non-OK status. 1252 1253 The status passed as argument will supercede any existing status code, 1254 status message and trailing metadata. 1255 1256 This is an EXPERIMENTAL API. 1257 1258 Args: 1259 status: A grpc.Status object. The status code in it must not be 1260 StatusCode.OK. 1261 1262 Raises: 1263 Exception: An exception is always raised to signal the abortion the 1264 RPC to the gRPC runtime. 1265 """ 1266 raise NotImplementedError() 1267 1268 @abc.abstractmethod 1269 def set_code(self, code): 1270 """Sets the value to be used as status code upon RPC completion. 1271 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. 1274 1275 Args: 1276 code: A StatusCode object to be sent to the client. 1277 """ 1278 raise NotImplementedError() 1279 1280 @abc.abstractmethod 1281 def set_details(self, details): 1282 """Sets the value to be used as detail string upon RPC completion. 1283 1284 This method need not be called by method implementations if they have 1285 no details to transmit. 1286 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() 1292 1293 def code(self): 1294 """Accesses the value to be used as status code upon RPC completion. 1295 1296 This is an EXPERIMENTAL API. 1297 1298 Returns: 1299 The StatusCode value for the RPC. 1300 """ 1301 raise NotImplementedError() 1302 1303 def details(self): 1304 """Accesses the value to be used as detail string upon RPC completion. 1305 1306 This is an EXPERIMENTAL API. 1307 1308 Returns: 1309 The details string of the RPC. 1310 """ 1311 raise NotImplementedError() 1312 1313 def disable_next_message_compression(self): 1314 """Disables compression for the next response message. 1315 1316 This method will override any compression configuration set during 1317 server creation or set on the call. 1318 """ 1319 raise NotImplementedError() 1320 1321 1322##################### Service-Side Handler Interfaces ######################## 1323 1324 1325class RpcMethodHandler(abc.ABC): 1326 """An implementation of a single RPC method. 1327 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 """ 1359 1360 1361class HandlerCallDetails(abc.ABC): 1362 """Describes an RPC that has just arrived for service. 1363 1364 Attributes: 1365 method: The method name of the RPC. 1366 invocation_metadata: The :term:`metadata` sent by the client. 1367 """ 1368 1369 1370class GenericRpcHandler(abc.ABC): 1371 """An implementation of arbitrarily many RPC methods.""" 1372 1373 @abc.abstractmethod 1374 def service(self, handler_call_details): 1375 """Returns the handler for servicing the RPC. 1376 1377 Args: 1378 handler_call_details: A HandlerCallDetails describing the RPC. 1379 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() 1385 1386 1387class ServiceRpcHandler(GenericRpcHandler, metaclass=abc.ABCMeta): 1388 """An implementation of RPC methods belonging to a service. 1389 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 """ 1396 1397 @abc.abstractmethod 1398 def service_name(self): 1399 """Returns this service's name. 1400 1401 Returns: 1402 The service name. 1403 """ 1404 raise NotImplementedError() 1405 1406 1407#################### Service-Side Interceptor Interfaces ##################### 1408 1409 1410class ServerInterceptor(abc.ABC): 1411 """Affords intercepting incoming RPCs on the service-side.""" 1412 1413 @abc.abstractmethod 1414 def intercept_service(self, continuation, handler_call_details): 1415 """Intercepts incoming RPCs before handing them over to a handler. 1416 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. 1423 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. 1431 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() 1437 1438 1439############################# Server Interface ############################### 1440 1441 1442class Server(abc.ABC): 1443 """Services RPCs.""" 1444 1445 @abc.abstractmethod 1446 def add_generic_rpc_handlers(self, generic_rpc_handlers): 1447 """Registers GenericRpcHandlers with this Server. 1448 1449 This method is only safe to call before the server is started. 1450 1451 Args: 1452 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be 1453 used to service RPCs. 1454 """ 1455 raise NotImplementedError() 1456 1457 @abc.abstractmethod 1458 def add_insecure_port(self, address): 1459 """Opens an insecure port for accepting RPCs. 1460 1461 This method may only be called before starting the server. 1462 1463 Args: 1464 address: The address for which to open a port. If the port is 0, 1465 or not specified in the address, then gRPC runtime will choose a port. 1466 1467 Returns: 1468 An integer port on which server will accept RPC requests. 1469 """ 1470 raise NotImplementedError() 1471 1472 @abc.abstractmethod 1473 def add_secure_port(self, address, server_credentials): 1474 """Opens a secure port for accepting RPCs. 1475 1476 This method may only be called before starting the server. 1477 1478 Args: 1479 address: The address for which to open a port. 1480 if the port is 0, or not specified in the address, then gRPC 1481 runtime will choose a port. 1482 server_credentials: A ServerCredentials object. 1483 1484 Returns: 1485 An integer port on which server will accept RPC requests. 1486 """ 1487 raise NotImplementedError() 1488 1489 @abc.abstractmethod 1490 def start(self): 1491 """Starts this Server. 1492 1493 This method may only be called once. (i.e. it is not idempotent). 1494 """ 1495 raise NotImplementedError() 1496 1497 @abc.abstractmethod 1498 def stop(self, grace): 1499 """Stops this Server. 1500 1501 This method immediately stop service of new RPCs in all cases. 1502 1503 If a grace period is specified, this method waits until all active 1504 RPCs are finished or until the grace period is reached. RPCs that haven't 1505 been terminated within the grace period are aborted. 1506 If a grace period is not specified (by passing None for `grace`), 1507 all existing RPCs are aborted immediately and this method 1508 blocks until the last RPC handler terminates. 1509 1510 This method is idempotent and may be called at any time. 1511 Passing a smaller grace value in a subsequent call will have 1512 the effect of stopping the Server sooner (passing None will 1513 have the effect of stopping the server immediately). Passing 1514 a larger grace value in a subsequent call *will not* have the 1515 effect of stopping the server later (i.e. the most restrictive 1516 grace value is used). 1517 1518 Args: 1519 grace: A duration of time in seconds or None. 1520 1521 Returns: 1522 A threading.Event that will be set when this Server has completely 1523 stopped, i.e. when running RPCs either complete or are aborted and 1524 all handlers have terminated. 1525 """ 1526 raise NotImplementedError() 1527 1528 def wait_for_termination(self, timeout=None): 1529 """Block current thread until the server stops. 1530 1531 This is an EXPERIMENTAL API. 1532 1533 The wait will not consume computational resources during blocking, and 1534 it will block until one of the two following conditions are met: 1535 1536 1) The server is stopped or terminated; 1537 2) A timeout occurs if timeout is not `None`. 1538 1539 The timeout argument works in the same way as `threading.Event.wait()`. 1540 https://docs.python.org/3/library/threading.html#threading.Event.wait 1541 1542 Args: 1543 timeout: A floating point number specifying a timeout for the 1544 operation in seconds. 1545 1546 Returns: 1547 A bool indicates if the operation times out. 1548 """ 1549 raise NotImplementedError() 1550 1551 1552################################# Functions ################################ 1553 1554 1555def unary_unary_rpc_method_handler( 1556 behavior, request_deserializer=None, response_serializer=None 1557): 1558 """Creates an RpcMethodHandler for a unary-unary RPC method. 1559 1560 Args: 1561 behavior: The implementation of an RPC that accepts one request 1562 and returns one response. 1563 request_deserializer: An optional :term:`deserializer` for request deserialization. 1564 response_serializer: An optional :term:`serializer` for response serialization. 1565 1566 Returns: 1567 An RpcMethodHandler object that is typically used by grpc.Server. 1568 """ 1569 from grpc import _utilities # pylint: disable=cyclic-import 1570 1571 return _utilities.RpcMethodHandler( 1572 False, 1573 False, 1574 request_deserializer, 1575 response_serializer, 1576 behavior, 1577 None, 1578 None, 1579 None, 1580 ) 1581 1582 1583def unary_stream_rpc_method_handler( 1584 behavior, request_deserializer=None, response_serializer=None 1585): 1586 """Creates an RpcMethodHandler for a unary-stream RPC method. 1587 1588 Args: 1589 behavior: The implementation of an RPC that accepts one request 1590 and returns an iterator of response values. 1591 request_deserializer: An optional :term:`deserializer` for request deserialization. 1592 response_serializer: An optional :term:`serializer` for response serialization. 1593 1594 Returns: 1595 An RpcMethodHandler object that is typically used by grpc.Server. 1596 """ 1597 from grpc import _utilities # pylint: disable=cyclic-import 1598 1599 return _utilities.RpcMethodHandler( 1600 False, 1601 True, 1602 request_deserializer, 1603 response_serializer, 1604 None, 1605 behavior, 1606 None, 1607 None, 1608 ) 1609 1610 1611def stream_unary_rpc_method_handler( 1612 behavior, request_deserializer=None, response_serializer=None 1613): 1614 """Creates an RpcMethodHandler for a stream-unary RPC method. 1615 1616 Args: 1617 behavior: The implementation of an RPC that accepts an iterator of 1618 request values and returns a single response value. 1619 request_deserializer: An optional :term:`deserializer` for request deserialization. 1620 response_serializer: An optional :term:`serializer` for response serialization. 1621 1622 Returns: 1623 An RpcMethodHandler object that is typically used by grpc.Server. 1624 """ 1625 from grpc import _utilities # pylint: disable=cyclic-import 1626 1627 return _utilities.RpcMethodHandler( 1628 True, 1629 False, 1630 request_deserializer, 1631 response_serializer, 1632 None, 1633 None, 1634 behavior, 1635 None, 1636 ) 1637 1638 1639def stream_stream_rpc_method_handler( 1640 behavior, request_deserializer=None, response_serializer=None 1641): 1642 """Creates an RpcMethodHandler for a stream-stream RPC method. 1643 1644 Args: 1645 behavior: The implementation of an RPC that accepts an iterator of 1646 request values and returns an iterator of response values. 1647 request_deserializer: An optional :term:`deserializer` for request deserialization. 1648 response_serializer: An optional :term:`serializer` for response serialization. 1649 1650 Returns: 1651 An RpcMethodHandler object that is typically used by grpc.Server. 1652 """ 1653 from grpc import _utilities # pylint: disable=cyclic-import 1654 1655 return _utilities.RpcMethodHandler( 1656 True, 1657 True, 1658 request_deserializer, 1659 response_serializer, 1660 None, 1661 None, 1662 None, 1663 behavior, 1664 ) 1665 1666 1667def method_handlers_generic_handler(service, method_handlers): 1668 """Creates a GenericRpcHandler from RpcMethodHandlers. 1669 1670 Args: 1671 service: The name of the service that is implemented by the 1672 method_handlers. 1673 method_handlers: A dictionary that maps method names to corresponding 1674 RpcMethodHandler. 1675 1676 Returns: 1677 A GenericRpcHandler. This is typically added to the grpc.Server object 1678 with add_generic_rpc_handlers() before starting the server. 1679 """ 1680 from grpc import _utilities # pylint: disable=cyclic-import 1681 1682 return _utilities.DictionaryGenericHandler(service, method_handlers) 1683 1684 1685def ssl_channel_credentials( 1686 root_certificates=None, private_key=None, certificate_chain=None 1687): 1688 """Creates a ChannelCredentials for use with an SSL-enabled Channel. 1689 1690 Args: 1691 root_certificates: The PEM-encoded root certificates as a byte string, 1692 or None to retrieve them from a default location chosen by gRPC 1693 runtime. 1694 private_key: The PEM-encoded private key as a byte string, or None if no 1695 private key should be used. 1696 certificate_chain: The PEM-encoded certificate chain as a byte string 1697 to use or None if no certificate chain should be used. 1698 1699 Returns: 1700 A ChannelCredentials for use with an SSL-enabled Channel. 1701 """ 1702 return ChannelCredentials( 1703 _cygrpc.SSLChannelCredentials( 1704 root_certificates, private_key, certificate_chain 1705 ) 1706 ) 1707 1708 1709def xds_channel_credentials(fallback_credentials=None): 1710 """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL 1711 API. 1712 1713 Args: 1714 fallback_credentials: Credentials to use in case it is not possible to 1715 establish a secure connection via xDS. If no fallback_credentials 1716 argument is supplied, a default SSLChannelCredentials is used. 1717 """ 1718 fallback_credentials = ( 1719 ssl_channel_credentials() 1720 if fallback_credentials is None 1721 else fallback_credentials 1722 ) 1723 return ChannelCredentials( 1724 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials) 1725 ) 1726 1727 1728def metadata_call_credentials(metadata_plugin, name=None): 1729 """Construct CallCredentials from an AuthMetadataPlugin. 1730 1731 Args: 1732 metadata_plugin: An AuthMetadataPlugin to use for authentication. 1733 name: An optional name for the plugin. 1734 1735 Returns: 1736 A CallCredentials. 1737 """ 1738 from grpc import _plugin_wrapping # pylint: disable=cyclic-import 1739 1740 return _plugin_wrapping.metadata_plugin_call_credentials( 1741 metadata_plugin, name 1742 ) 1743 1744 1745def access_token_call_credentials(access_token): 1746 """Construct CallCredentials from an access token. 1747 1748 Args: 1749 access_token: A string to place directly in the http request 1750 authorization header, for example 1751 "authorization: Bearer <access_token>". 1752 1753 Returns: 1754 A CallCredentials. 1755 """ 1756 from grpc import _auth # pylint: disable=cyclic-import 1757 from grpc import _plugin_wrapping # pylint: disable=cyclic-import 1758 1759 return _plugin_wrapping.metadata_plugin_call_credentials( 1760 _auth.AccessTokenAuthMetadataPlugin(access_token), None 1761 ) 1762 1763 1764def composite_call_credentials(*call_credentials): 1765 """Compose multiple CallCredentials to make a new CallCredentials. 1766 1767 Args: 1768 *call_credentials: At least two CallCredentials objects. 1769 1770 Returns: 1771 A CallCredentials object composed of the given CallCredentials objects. 1772 """ 1773 return CallCredentials( 1774 _cygrpc.CompositeCallCredentials( 1775 tuple( 1776 single_call_credentials._credentials 1777 for single_call_credentials in call_credentials 1778 ) 1779 ) 1780 ) 1781 1782 1783def composite_channel_credentials(channel_credentials, *call_credentials): 1784 """Compose a ChannelCredentials and one or more CallCredentials objects. 1785 1786 Args: 1787 channel_credentials: A ChannelCredentials object. 1788 *call_credentials: One or more CallCredentials objects. 1789 1790 Returns: 1791 A ChannelCredentials composed of the given ChannelCredentials and 1792 CallCredentials objects. 1793 """ 1794 return ChannelCredentials( 1795 _cygrpc.CompositeChannelCredentials( 1796 tuple( 1797 single_call_credentials._credentials 1798 for single_call_credentials in call_credentials 1799 ), 1800 channel_credentials._credentials, 1801 ) 1802 ) 1803 1804 1805def ssl_server_credentials( 1806 private_key_certificate_chain_pairs, 1807 root_certificates=None, 1808 require_client_auth=False, 1809): 1810 """Creates a ServerCredentials for use with an SSL-enabled Server. 1811 1812 Args: 1813 private_key_certificate_chain_pairs: A list of pairs of the form 1814 [PEM-encoded private key, PEM-encoded certificate chain]. 1815 root_certificates: An optional byte string of PEM-encoded client root 1816 certificates that the server will use to verify client authentication. 1817 If omitted, require_client_auth must also be False. 1818 require_client_auth: A boolean indicating whether or not to require 1819 clients to be authenticated. May only be True if root_certificates 1820 is not None. 1821 1822 Returns: 1823 A ServerCredentials for use with an SSL-enabled Server. Typically, this 1824 object is an argument to add_secure_port() method during server setup. 1825 """ 1826 if not private_key_certificate_chain_pairs: 1827 raise ValueError( 1828 "At least one private key-certificate chain pair is required!" 1829 ) 1830 elif require_client_auth and root_certificates is None: 1831 raise ValueError( 1832 "Illegal to require client auth without providing root" 1833 " certificates!" 1834 ) 1835 else: 1836 return ServerCredentials( 1837 _cygrpc.server_credentials_ssl( 1838 root_certificates, 1839 [ 1840 _cygrpc.SslPemKeyCertPair(key, pem) 1841 for key, pem in private_key_certificate_chain_pairs 1842 ], 1843 require_client_auth, 1844 ) 1845 ) 1846 1847 1848def xds_server_credentials(fallback_credentials): 1849 """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL 1850 API. 1851 1852 Args: 1853 fallback_credentials: Credentials to use in case it is not possible to 1854 establish a secure connection via xDS. No default value is provided. 1855 """ 1856 return ServerCredentials( 1857 _cygrpc.xds_server_credentials(fallback_credentials._credentials) 1858 ) 1859 1860 1861def insecure_server_credentials(): 1862 """Creates a credentials object directing the server to use no credentials. 1863 This is an EXPERIMENTAL API. 1864 1865 This object cannot be used directly in a call to `add_secure_port`. 1866 Instead, it should be used to construct other credentials objects, e.g. 1867 with xds_server_credentials. 1868 """ 1869 return ServerCredentials(_cygrpc.insecure_server_credentials()) 1870 1871 1872def ssl_server_certificate_configuration( 1873 private_key_certificate_chain_pairs, root_certificates=None 1874): 1875 """Creates a ServerCertificateConfiguration for use with a Server. 1876 1877 Args: 1878 private_key_certificate_chain_pairs: A collection of pairs of 1879 the form [PEM-encoded private key, PEM-encoded certificate 1880 chain]. 1881 root_certificates: An optional byte string of PEM-encoded client root 1882 certificates that the server will use to verify client authentication. 1883 1884 Returns: 1885 A ServerCertificateConfiguration that can be returned in the certificate 1886 configuration fetching callback. 1887 """ 1888 if private_key_certificate_chain_pairs: 1889 return ServerCertificateConfiguration( 1890 _cygrpc.server_certificate_config_ssl( 1891 root_certificates, 1892 [ 1893 _cygrpc.SslPemKeyCertPair(key, pem) 1894 for key, pem in private_key_certificate_chain_pairs 1895 ], 1896 ) 1897 ) 1898 else: 1899 raise ValueError( 1900 "At least one private key-certificate chain pair is required!" 1901 ) 1902 1903 1904def dynamic_ssl_server_credentials( 1905 initial_certificate_configuration, 1906 certificate_configuration_fetcher, 1907 require_client_authentication=False, 1908): 1909 """Creates a ServerCredentials for use with an SSL-enabled Server. 1910 1911 Args: 1912 initial_certificate_configuration (ServerCertificateConfiguration): The 1913 certificate configuration with which the server will be initialized. 1914 certificate_configuration_fetcher (callable): A callable that takes no 1915 arguments and should return a ServerCertificateConfiguration to 1916 replace the server's current certificate, or None for no change 1917 (i.e., the server will continue its current certificate 1918 config). The library will call this callback on *every* new 1919 client connection before starting the TLS handshake with the 1920 client, thus allowing the user application to optionally 1921 return a new ServerCertificateConfiguration that the server will then 1922 use for the handshake. 1923 require_client_authentication: A boolean indicating whether or not to 1924 require clients to be authenticated. 1925 1926 Returns: 1927 A ServerCredentials. 1928 """ 1929 return ServerCredentials( 1930 _cygrpc.server_credentials_ssl_dynamic_cert_config( 1931 initial_certificate_configuration, 1932 certificate_configuration_fetcher, 1933 require_client_authentication, 1934 ) 1935 ) 1936 1937 1938@enum.unique 1939class LocalConnectionType(enum.Enum): 1940 """Types of local connection for local credential creation. 1941 1942 Attributes: 1943 UDS: Unix domain socket connections 1944 LOCAL_TCP: Local TCP connections. 1945 """ 1946 1947 UDS = _cygrpc.LocalConnectionType.uds 1948 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp 1949 1950 1951def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 1952 """Creates a local ChannelCredentials used for local connections. 1953 1954 This is an EXPERIMENTAL API. 1955 1956 Local credentials are used by local TCP endpoints (e.g. localhost:10000) 1957 also UDS connections. 1958 1959 The connections created by local channel credentials are not 1960 encrypted, but will be checked if they are local or not. 1961 The UDS connections are considered secure by providing peer authentication 1962 and data confidentiality while TCP connections are considered insecure. 1963 1964 It is allowed to transmit call credentials over connections created by 1965 local channel credentials. 1966 1967 Local channel credentials are useful for 1) eliminating insecure_channel usage; 1968 2) enable unit testing for call credentials without setting up secrets. 1969 1970 Args: 1971 local_connect_type: Local connection type (either 1972 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 1973 1974 Returns: 1975 A ChannelCredentials for use with a local Channel 1976 """ 1977 return ChannelCredentials( 1978 _cygrpc.channel_credentials_local(local_connect_type.value) 1979 ) 1980 1981 1982def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 1983 """Creates a local ServerCredentials used for local connections. 1984 1985 This is an EXPERIMENTAL API. 1986 1987 Local credentials are used by local TCP endpoints (e.g. localhost:10000) 1988 also UDS connections. 1989 1990 The connections created by local server credentials are not 1991 encrypted, but will be checked if they are local or not. 1992 The UDS connections are considered secure by providing peer authentication 1993 and data confidentiality while TCP connections are considered insecure. 1994 1995 It is allowed to transmit call credentials over connections created by local 1996 server credentials. 1997 1998 Local server credentials are useful for 1) eliminating insecure_channel usage; 1999 2) enable unit testing for call credentials without setting up secrets. 2000 2001 Args: 2002 local_connect_type: Local connection type (either 2003 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 2004 2005 Returns: 2006 A ServerCredentials for use with a local Server 2007 """ 2008 return ServerCredentials( 2009 _cygrpc.server_credentials_local(local_connect_type.value) 2010 ) 2011 2012 2013def alts_channel_credentials(service_accounts=None): 2014 """Creates a ChannelCredentials for use with an ALTS-enabled Channel. 2015 2016 This is an EXPERIMENTAL API. 2017 ALTS credentials API can only be used in GCP environment as it relies on 2018 handshaker service being available. For more info about ALTS see 2019 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security 2020 2021 Args: 2022 service_accounts: A list of server identities accepted by the client. 2023 If target service accounts are provided and none of them matches the 2024 peer identity of the server, handshake will fail. The arg can be empty 2025 if the client does not have any information about trusted server 2026 identity. 2027 Returns: 2028 A ChannelCredentials for use with an ALTS-enabled Channel 2029 """ 2030 return ChannelCredentials( 2031 _cygrpc.channel_credentials_alts(service_accounts or []) 2032 ) 2033 2034 2035def alts_server_credentials(): 2036 """Creates a ServerCredentials for use with an ALTS-enabled connection. 2037 2038 This is an EXPERIMENTAL API. 2039 ALTS credentials API can only be used in GCP environment as it relies on 2040 handshaker service being available. For more info about ALTS see 2041 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security 2042 2043 Returns: 2044 A ServerCredentials for use with an ALTS-enabled Server 2045 """ 2046 return ServerCredentials(_cygrpc.server_credentials_alts()) 2047 2048 2049def compute_engine_channel_credentials(call_credentials): 2050 """Creates a compute engine channel credential. 2051 2052 This credential can only be used in a GCP environment as it relies on 2053 a handshaker service. For more info about ALTS, see 2054 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security 2055 2056 This channel credential is expected to be used as part of a composite 2057 credential in conjunction with a call credentials that authenticates the 2058 VM's default service account. If used with any other sort of call 2059 credential, the connection may suddenly and unexpectedly begin failing RPCs. 2060 """ 2061 return ChannelCredentials( 2062 _cygrpc.channel_credentials_compute_engine( 2063 call_credentials._credentials 2064 ) 2065 ) 2066 2067 2068def channel_ready_future(channel): 2069 """Creates a Future that tracks when a Channel is ready. 2070 2071 Cancelling the Future does not affect the channel's state machine. 2072 It merely decouples the Future from channel state machine. 2073 2074 Args: 2075 channel: A Channel object. 2076 2077 Returns: 2078 A Future object that matures when the channel connectivity is 2079 ChannelConnectivity.READY. 2080 """ 2081 from grpc import _utilities # pylint: disable=cyclic-import 2082 2083 return _utilities.channel_ready_future(channel) 2084 2085 2086def insecure_channel(target, options=None, compression=None): 2087 """Creates an insecure Channel to a server. 2088 2089 The returned Channel is thread-safe. 2090 2091 Args: 2092 target: The server address 2093 options: An optional list of key-value pairs (:term:`channel_arguments` 2094 in gRPC Core runtime) to configure the channel. 2095 compression: An optional value indicating the compression method to be 2096 used over the lifetime of the channel. 2097 2098 Returns: 2099 A Channel. 2100 """ 2101 from grpc import _channel # pylint: disable=cyclic-import 2102 2103 return _channel.Channel( 2104 target, () if options is None else options, None, compression 2105 ) 2106 2107 2108def secure_channel(target, credentials, options=None, compression=None): 2109 """Creates a secure Channel to a server. 2110 2111 The returned Channel is thread-safe. 2112 2113 Args: 2114 target: The server address. 2115 credentials: A ChannelCredentials instance. 2116 options: An optional list of key-value pairs (:term:`channel_arguments` 2117 in gRPC Core runtime) to configure the channel. 2118 compression: An optional value indicating the compression method to be 2119 used over the lifetime of the channel. 2120 2121 Returns: 2122 A Channel. 2123 """ 2124 from grpc import _channel # pylint: disable=cyclic-import 2125 from grpc.experimental import _insecure_channel_credentials 2126 2127 if credentials._credentials is _insecure_channel_credentials: 2128 raise ValueError( 2129 "secure_channel cannot be called with insecure credentials." 2130 + " Call insecure_channel instead." 2131 ) 2132 return _channel.Channel( 2133 target, 2134 () if options is None else options, 2135 credentials._credentials, 2136 compression, 2137 ) 2138 2139 2140def intercept_channel(channel, *interceptors): 2141 """Intercepts a channel through a set of interceptors. 2142 2143 Args: 2144 channel: A Channel. 2145 interceptors: Zero or more objects of type 2146 UnaryUnaryClientInterceptor, 2147 UnaryStreamClientInterceptor, 2148 StreamUnaryClientInterceptor, or 2149 StreamStreamClientInterceptor. 2150 Interceptors are given control in the order they are listed. 2151 2152 Returns: 2153 A Channel that intercepts each invocation via the provided interceptors. 2154 2155 Raises: 2156 TypeError: If interceptor does not derive from any of 2157 UnaryUnaryClientInterceptor, 2158 UnaryStreamClientInterceptor, 2159 StreamUnaryClientInterceptor, or 2160 StreamStreamClientInterceptor. 2161 """ 2162 from grpc import _interceptor # pylint: disable=cyclic-import 2163 2164 return _interceptor.intercept_channel(channel, *interceptors) 2165 2166 2167def server( 2168 thread_pool, 2169 handlers=None, 2170 interceptors=None, 2171 options=None, 2172 maximum_concurrent_rpcs=None, 2173 compression=None, 2174 xds=False, 2175): 2176 """Creates a Server with which RPCs can be serviced. 2177 2178 Args: 2179 thread_pool: A futures.ThreadPoolExecutor to be used by the Server 2180 to execute RPC handlers. 2181 handlers: An optional list of GenericRpcHandlers used for executing RPCs. 2182 More handlers may be added by calling add_generic_rpc_handlers any time 2183 before the server is started. 2184 interceptors: An optional list of ServerInterceptor objects that observe 2185 and optionally manipulate the incoming RPCs before handing them over to 2186 handlers. The interceptors are given control in the order they are 2187 specified. This is an EXPERIMENTAL API. 2188 options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime) 2189 to configure the channel. 2190 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server 2191 will service before returning RESOURCE_EXHAUSTED status, or None to 2192 indicate no limit. 2193 compression: An element of grpc.compression, e.g. 2194 grpc.compression.Gzip. This compression algorithm will be used for the 2195 lifetime of the server unless overridden. 2196 xds: If set to true, retrieves server configuration via xDS. This is an 2197 EXPERIMENTAL option. 2198 2199 Returns: 2200 A Server object. 2201 """ 2202 from grpc import _server # pylint: disable=cyclic-import 2203 2204 return _server.create_server( 2205 thread_pool, 2206 () if handlers is None else handlers, 2207 () if interceptors is None else interceptors, 2208 () if options is None else options, 2209 maximum_concurrent_rpcs, 2210 compression, 2211 xds, 2212 ) 2213 2214 2215@contextlib.contextmanager 2216def _create_servicer_context(rpc_event, state, request_deserializer): 2217 from grpc import _server # pylint: disable=cyclic-import 2218 2219 context = _server._Context(rpc_event, state, request_deserializer) 2220 yield context 2221 context._finalize_state() # pylint: disable=protected-access 2222 2223 2224@enum.unique 2225class Compression(enum.IntEnum): 2226 """Indicates the compression method to be used for an RPC. 2227 2228 Attributes: 2229 NoCompression: Do not use compression algorithm. 2230 Deflate: Use "Deflate" compression algorithm. 2231 Gzip: Use "Gzip" compression algorithm. 2232 """ 2233 2234 NoCompression = _compression.NoCompression 2235 Deflate = _compression.Deflate 2236 Gzip = _compression.Gzip 2237 2238 2239################################### __all__ ################################# 2240 2241__all__ = ( 2242 "FutureTimeoutError", 2243 "FutureCancelledError", 2244 "Future", 2245 "ChannelConnectivity", 2246 "StatusCode", 2247 "Status", 2248 "RpcError", 2249 "RpcContext", 2250 "Call", 2251 "ChannelCredentials", 2252 "CallCredentials", 2253 "AuthMetadataContext", 2254 "AuthMetadataPluginCallback", 2255 "AuthMetadataPlugin", 2256 "Compression", 2257 "ClientCallDetails", 2258 "ServerCertificateConfiguration", 2259 "ServerCredentials", 2260 "LocalConnectionType", 2261 "UnaryUnaryMultiCallable", 2262 "UnaryStreamMultiCallable", 2263 "StreamUnaryMultiCallable", 2264 "StreamStreamMultiCallable", 2265 "UnaryUnaryClientInterceptor", 2266 "UnaryStreamClientInterceptor", 2267 "StreamUnaryClientInterceptor", 2268 "StreamStreamClientInterceptor", 2269 "Channel", 2270 "ServicerContext", 2271 "RpcMethodHandler", 2272 "HandlerCallDetails", 2273 "GenericRpcHandler", 2274 "ServiceRpcHandler", 2275 "Server", 2276 "ServerInterceptor", 2277 "unary_unary_rpc_method_handler", 2278 "unary_stream_rpc_method_handler", 2279 "stream_unary_rpc_method_handler", 2280 "stream_stream_rpc_method_handler", 2281 "method_handlers_generic_handler", 2282 "ssl_channel_credentials", 2283 "metadata_call_credentials", 2284 "access_token_call_credentials", 2285 "composite_call_credentials", 2286 "composite_channel_credentials", 2287 "compute_engine_channel_credentials", 2288 "local_channel_credentials", 2289 "local_server_credentials", 2290 "alts_channel_credentials", 2291 "alts_server_credentials", 2292 "ssl_server_credentials", 2293 "ssl_server_certificate_configuration", 2294 "dynamic_ssl_server_credentials", 2295 "channel_ready_future", 2296 "insecure_channel", 2297 "secure_channel", 2298 "intercept_channel", 2299 "server", 2300 "protos", 2301 "services", 2302 "protos_and_services", 2303 "xds_channel_credentials", 2304 "xds_server_credentials", 2305 "insecure_server_credentials", 2306) 2307 2308############################### Extension Shims ################################ 2309 2310# Here to maintain backwards compatibility; avoid using these in new code! 2311try: 2312 import grpc_tools 2313 2314 sys.modules.update({"grpc.tools": grpc_tools}) 2315except ImportError: 2316 pass 2317try: 2318 import grpc_health 2319 2320 sys.modules.update({"grpc.health": grpc_health}) 2321except ImportError: 2322 pass 2323try: 2324 import grpc_reflection 2325 2326 sys.modules.update({"grpc.reflection": grpc_reflection}) 2327except ImportError: 2328 pass 2329 2330# Prevents import order issue in the case of renamed path. 2331if sys.version_info >= (3, 6) and __name__ == "grpc": 2332 from grpc import aio # pylint: disable=ungrouped-imports 2333 2334 sys.modules.update({"grpc.aio": aio}) 2335