Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/grpc/__init__.py: 2%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

383 statements  

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 

21import typing 

22from typing import Any, Protocol 

23 

24from grpc import _compression 

25from grpc._cython import cygrpc as _cygrpc 

26from grpc._runtime_protos import protos 

27from grpc._runtime_protos import protos_and_services 

28from grpc._runtime_protos import services 

29 

30logging.getLogger(__name__).addHandler(logging.NullHandler()) 

31 

32try: 

33 # pylint: disable=ungrouped-imports 

34 from grpc._grpcio_metadata import __version__ 

35except ImportError: 

36 __version__ = "dev0" 

37 

38############################## Future Interface ############################### 

39 

40 

41class FutureTimeoutError(Exception): 

42 """Indicates that a method call on a Future timed out.""" 

43 

44 

45class FutureCancelledError(Exception): 

46 """Indicates that the computation underlying a Future was cancelled.""" 

47 

48 

49class Future(abc.ABC): 

50 """A representation of a computation in another control flow. 

51 

52 Computations represented by a Future may be yet to be begun, 

53 may be ongoing, or may have already completed. 

54 """ 

55 

56 @abc.abstractmethod 

57 def cancel(self): 

58 """Attempts to cancel the computation. 

59 

60 This method does not block. 

61 

62 Returns: 

63 bool: 

64 Returns True if the computation was canceled. 

65 

66 Returns False under all other circumstances, for example: 

67 

68 1. computation has begun and could not be canceled. 

69 2. computation has finished 

70 3. computation is scheduled for execution and it is impossible 

71 to determine its state without blocking. 

72 """ 

73 raise NotImplementedError() 

74 

75 @abc.abstractmethod 

76 def cancelled(self): 

77 """Describes whether the computation was cancelled. 

78 

79 This method does not block. 

80 

81 Returns: 

82 bool: 

83 Returns True if the computation was cancelled before its result became 

84 available. 

85 

86 Returns False under all other circumstances, for example: 

87 

88 1. computation was not cancelled. 

89 2. computation's result is available. 

90 """ 

91 raise NotImplementedError() 

92 

93 @abc.abstractmethod 

94 def running(self): 

95 """Describes whether the computation is taking place. 

96 

97 This method does not block. 

98 

99 Returns: 

100 Returns True if the computation is scheduled for execution or 

101 currently executing. 

102 

103 Returns False if the computation already executed or was cancelled. 

104 """ 

105 raise NotImplementedError() 

106 

107 @abc.abstractmethod 

108 def done(self): 

109 """Describes whether the computation has taken place. 

110 

111 This method does not block. 

112 

113 Returns: 

114 bool: 

115 Returns True if the computation already executed or was cancelled. 

116 Returns False if the computation is scheduled for execution or 

117 currently executing. 

118 This is exactly opposite of the running() method's result. 

119 """ 

120 raise NotImplementedError() 

121 

122 @abc.abstractmethod 

123 def result(self, timeout=None): 

124 """Returns the result of the computation or raises its exception. 

125 

126 This method may return immediately or may block. 

127 

128 Args: 

129 timeout: The length of time in seconds to wait for the computation to 

130 finish or be cancelled. If None, the call will block until the 

131 computations's termination. 

132 

133 Returns: 

134 The return value of the computation. 

135 

136 Raises: 

137 FutureTimeoutError: If a timeout value is passed and the computation 

138 does not terminate within the allotted time. 

139 FutureCancelledError: If the computation was cancelled. 

140 Exception: If the computation raised an exception, this call will 

141 raise the same exception. 

142 """ 

143 raise NotImplementedError() 

144 

145 @abc.abstractmethod 

146 def exception(self, timeout=None): 

147 """Return the exception raised by the computation. 

148 

149 This method may return immediately or may block. 

150 

151 Args: 

152 timeout: The length of time in seconds to wait for the computation to 

153 terminate or be cancelled. If None, the call will block until the 

154 computations's termination. 

155 

156 Returns: 

157 The exception raised by the computation, or None if the computation 

158 did not raise an exception. 

159 

160 Raises: 

161 FutureTimeoutError: If a timeout value is passed and the computation 

162 does not terminate within the allotted time. 

163 FutureCancelledError: If the computation was cancelled. 

164 """ 

165 raise NotImplementedError() 

166 

167 @abc.abstractmethod 

168 def traceback(self, timeout=None): 

169 """Access the traceback of the exception raised by the computation. 

170 

171 This method may return immediately or may block. 

172 

173 Args: 

174 timeout: The length of time in seconds to wait for the computation 

175 to terminate or be cancelled. If None, the call will block until 

176 the computation's termination. 

177 

178 Returns: 

179 The traceback of the exception raised by the computation, or None 

180 if the computation did not raise an exception. 

181 

182 Raises: 

183 FutureTimeoutError: If a timeout value is passed and the computation 

184 does not terminate within the allotted time. 

185 FutureCancelledError: If the computation was cancelled. 

186 """ 

187 raise NotImplementedError() 

188 

189 @abc.abstractmethod 

190 def add_done_callback(self, fn): 

191 """Adds a function to be called at completion of the computation. 

192 

193 The callback will be passed this Future object describing the outcome 

194 of the computation. Callbacks will be invoked after the future is 

195 terminated, whether successfully or not. 

196 

197 If the computation has already completed, the callback will be called 

198 immediately. 

199 

200 Exceptions raised in the callback will be logged at ERROR level, but 

201 will not terminate any threads of execution. 

202 

203 Args: 

204 fn: A callable taking this Future object as its single parameter. 

205 """ 

206 raise NotImplementedError() 

207 

208 

209################################ gRPC Enums ################################## 

210 

211 

212@enum.unique 

213class ChannelConnectivity(enum.Enum): 

214 """Mirrors grpc_connectivity_state in the gRPC Core. 

215 

216 Attributes: 

217 IDLE: The channel is idle. 

218 CONNECTING: The channel is connecting. 

219 READY: The channel is ready to conduct RPCs. 

220 TRANSIENT_FAILURE: The channel has seen a failure from which it expects 

221 to recover. 

222 SHUTDOWN: The channel has seen a failure from which it cannot recover. 

223 """ 

224 

225 IDLE = (_cygrpc.ConnectivityState.idle, "idle") 

226 CONNECTING = (_cygrpc.ConnectivityState.connecting, "connecting") 

227 READY = (_cygrpc.ConnectivityState.ready, "ready") 

228 TRANSIENT_FAILURE = ( 

229 _cygrpc.ConnectivityState.transient_failure, 

230 "transient failure", 

231 ) 

232 SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, "shutdown") 

233 

234 

235@enum.unique 

236class StatusCode(enum.Enum): 

237 """Mirrors grpc_status_code in the gRPC Core. 

238 

239 Attributes: 

240 OK: Not an error; returned on success 

241 CANCELLED: The operation was cancelled (typically by the caller). 

242 UNKNOWN: Unknown error. 

243 INVALID_ARGUMENT: Client specified an invalid argument. 

244 DEADLINE_EXCEEDED: Deadline expired before operation could complete. 

245 NOT_FOUND: Some requested entity (e.g., file or directory) was not found. 

246 ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory) 

247 already exists. 

248 PERMISSION_DENIED: The caller does not have permission to execute the specified 

249 operation. 

250 UNAUTHENTICATED: The request does not have valid authentication credentials for the 

251 operation. 

252 RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or 

253 perhaps the entire file system is out of space. 

254 FAILED_PRECONDITION: Operation was rejected because the system is not in a state 

255 required for the operation's execution. 

256 ABORTED: The operation was aborted, typically due to a concurrency issue 

257 like sequencer check failures, transaction aborts, etc. 

258 UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service. 

259 INTERNAL: Internal errors. Means some invariants expected by underlying 

260 system has been broken. 

261 UNAVAILABLE: The service is currently unavailable. 

262 DATA_LOSS: Unrecoverable data loss or corruption. 

263 """ 

264 

265 OK = (_cygrpc.StatusCode.ok, "ok") 

266 CANCELLED = (_cygrpc.StatusCode.cancelled, "cancelled") 

267 UNKNOWN = (_cygrpc.StatusCode.unknown, "unknown") 

268 INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, "invalid argument") 

269 DEADLINE_EXCEEDED = ( 

270 _cygrpc.StatusCode.deadline_exceeded, 

271 "deadline exceeded", 

272 ) 

273 NOT_FOUND = (_cygrpc.StatusCode.not_found, "not found") 

274 ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, "already exists") 

275 PERMISSION_DENIED = ( 

276 _cygrpc.StatusCode.permission_denied, 

277 "permission denied", 

278 ) 

279 RESOURCE_EXHAUSTED = ( 

280 _cygrpc.StatusCode.resource_exhausted, 

281 "resource exhausted", 

282 ) 

283 FAILED_PRECONDITION = ( 

284 _cygrpc.StatusCode.failed_precondition, 

285 "failed precondition", 

286 ) 

287 ABORTED = (_cygrpc.StatusCode.aborted, "aborted") 

288 OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, "out of range") 

289 UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, "unimplemented") 

290 INTERNAL = (_cygrpc.StatusCode.internal, "internal") 

291 UNAVAILABLE = (_cygrpc.StatusCode.unavailable, "unavailable") 

292 DATA_LOSS = (_cygrpc.StatusCode.data_loss, "data loss") 

293 UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, "unauthenticated") 

294 

295 

296############################# gRPC Status ################################ 

297 

298 

299class Status(abc.ABC): 

300 """Describes the status of an RPC. 

301 

302 This is an EXPERIMENTAL API. 

303 

304 Attributes: 

305 code: A StatusCode object to be sent to the client. 

306 details: A UTF-8-encodable string to be sent to the client upon 

307 termination of the RPC. 

308 trailing_metadata: The trailing :term:`metadata` in the RPC. 

309 """ 

310 

311 

312############################# gRPC Exceptions ################################ 

313 

314 

315class RpcError(Exception): 

316 """Raised by the gRPC library to indicate non-OK-status RPC termination.""" 

317 

318 

319############################## Shared Context ################################ 

320 

321 

322class RpcContext(abc.ABC): 

323 """Provides RPC-related information and action.""" 

324 

325 @abc.abstractmethod 

326 def is_active(self): 

327 """Describes whether the RPC is active or has terminated. 

328 

329 Returns: 

330 bool: 

331 True if RPC is active, False otherwise. 

332 """ 

333 raise NotImplementedError() 

334 

335 @abc.abstractmethod 

336 def time_remaining(self): 

337 """Describes the length of allowed time remaining for the RPC. 

338 

339 Returns: 

340 A nonnegative float indicating the length of allowed time in seconds 

341 remaining for the RPC to complete before it is considered to have 

342 timed out, or None if no deadline was specified for the RPC. 

343 """ 

344 raise NotImplementedError() 

345 

346 @abc.abstractmethod 

347 def cancel(self): 

348 """Cancels the RPC. 

349 

350 Idempotent and has no effect if the RPC has already terminated. 

351 """ 

352 raise NotImplementedError() 

353 

354 @abc.abstractmethod 

355 def add_callback(self, callback): 

356 """Registers a callback to be called on RPC termination. 

357 

358 Args: 

359 callback: A no-parameter callable to be called on RPC termination. 

360 

361 Returns: 

362 True if the callback was added and will be called later; False if 

363 the callback was not added and will not be called (because the RPC 

364 already terminated or some other reason). 

365 """ 

366 raise NotImplementedError() 

367 

368 

369######################### Invocation-Side Context ############################ 

370 

371 

372class Call(RpcContext, metaclass=abc.ABCMeta): 

373 """Invocation-side utility object for an RPC.""" 

374 

375 @abc.abstractmethod 

376 def initial_metadata(self): 

377 """Accesses the initial metadata sent by the server. 

378 

379 This method blocks until the value is available. 

380 

381 Returns: 

382 The initial :term:`metadata`. 

383 """ 

384 raise NotImplementedError() 

385 

386 @abc.abstractmethod 

387 def trailing_metadata(self): 

388 """Accesses the trailing metadata sent by the server. 

389 

390 This method blocks until the value is available. 

391 

392 Returns: 

393 The trailing :term:`metadata`. 

394 """ 

395 raise NotImplementedError() 

396 

397 @abc.abstractmethod 

398 def code(self): 

399 """Accesses the status code sent by the server. 

400 

401 This method blocks until the value is available. 

402 

403 Returns: 

404 The StatusCode value for the RPC. 

405 """ 

406 raise NotImplementedError() 

407 

408 @abc.abstractmethod 

409 def details(self): 

410 """Accesses the details sent by the server. 

411 

412 This method blocks until the value is available. 

413 

414 Returns: 

415 The details string of the RPC. 

416 """ 

417 raise NotImplementedError() 

418 

419 

420############## Invocation-Side Interceptor Interfaces & Classes ############## 

421 

422 

423class ClientCallDetails(abc.ABC): 

424 """Describes an RPC to be invoked. 

425 

426 Attributes: 

427 method: The method name of the RPC. 

428 timeout: An optional duration of time in seconds to allow for the RPC. 

429 metadata: Optional :term:`metadata` to be transmitted to 

430 the service-side of the RPC. 

431 credentials: An optional CallCredentials for the RPC. 

432 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. 

433 compression: An element of grpc.Compression, e.g. 

434 grpc.Compression.Gzip. 

435 """ 

436 

437 

438class UnaryUnaryClientInterceptor(abc.ABC): 

439 """Affords intercepting unary-unary invocations.""" 

440 

441 @abc.abstractmethod 

442 def intercept_unary_unary(self, continuation, client_call_details, request): 

443 """Intercepts a unary-unary invocation asynchronously. 

444 

445 Args: 

446 continuation: A function that proceeds with the invocation by 

447 executing the next interceptor in chain or invoking the 

448 actual RPC on the underlying Channel. It is the interceptor's 

449 responsibility to call it if it decides to move the RPC forward. 

450 The interceptor can use 

451 `response_future = continuation(client_call_details, request)` 

452 to continue with the RPC. `continuation` returns an object that is 

453 both a Call for the RPC and a Future. In the event of RPC 

454 completion, the return Call-Future's result value will be 

455 the response message of the RPC. Should the event terminate 

456 with non-OK status, the returned Call-Future's exception value 

457 will be an RpcError. 

458 client_call_details: A ClientCallDetails object describing the 

459 outgoing RPC. 

460 request: The request value for the RPC. 

461 

462 Returns: 

463 An object that is both a Call for the RPC and a Future. 

464 In the event of RPC completion, the return Call-Future's 

465 result value will be the response message of the RPC. 

466 Should the event terminate with non-OK status, the returned 

467 Call-Future's exception value will be an RpcError. 

468 """ 

469 raise NotImplementedError() 

470 

471 

472class UnaryStreamClientInterceptor(abc.ABC): 

473 """Affords intercepting unary-stream invocations.""" 

474 

475 @abc.abstractmethod 

476 def intercept_unary_stream( 

477 self, continuation, client_call_details, request 

478 ): 

479 """Intercepts a unary-stream invocation. 

480 

481 Args: 

482 continuation: A function that proceeds with the invocation by 

483 executing the next interceptor in chain or invoking the 

484 actual RPC on the underlying Channel. It is the interceptor's 

485 responsibility to call it if it decides to move the RPC forward. 

486 The interceptor can use 

487 `response_iterator = continuation(client_call_details, request)` 

488 to continue with the RPC. `continuation` returns an object that is 

489 both a Call for the RPC and an iterator for response values. 

490 Drawing response values from the returned Call-iterator may 

491 raise RpcError indicating termination of the RPC with non-OK 

492 status. 

493 client_call_details: A ClientCallDetails object describing the 

494 outgoing RPC. 

495 request: The request value for the RPC. 

496 

497 Returns: 

498 An object that is both a Call for the RPC and an iterator of 

499 response values. Drawing response values from the returned 

500 Call-iterator may raise RpcError indicating termination of 

501 the RPC with non-OK status. This object *should* also fulfill the 

502 Future interface, though it may not. 

503 """ 

504 raise NotImplementedError() 

505 

506 

507class StreamUnaryClientInterceptor(abc.ABC): 

508 """Affords intercepting stream-unary invocations.""" 

509 

510 @abc.abstractmethod 

511 def intercept_stream_unary( 

512 self, continuation, client_call_details, request_iterator 

513 ): 

514 """Intercepts a stream-unary invocation asynchronously. 

515 

516 Args: 

517 continuation: A function that proceeds with the invocation by 

518 executing the next interceptor in chain or invoking the 

519 actual RPC on the underlying Channel. It is the interceptor's 

520 responsibility to call it if it decides to move the RPC forward. 

521 The interceptor can use 

522 `response_future = continuation(client_call_details, request_iterator)` 

523 to continue with the RPC. `continuation` returns an object that is 

524 both a Call for the RPC and a Future. In the event of RPC completion, 

525 the return Call-Future's result value will be the response message 

526 of the RPC. Should the event terminate with non-OK status, the 

527 returned Call-Future's exception value will be an RpcError. 

528 client_call_details: A ClientCallDetails object describing the 

529 outgoing RPC. 

530 request_iterator: An iterator that yields request values for the RPC. 

531 

532 Returns: 

533 An object that is both a Call for the RPC and a Future. 

534 In the event of RPC completion, the return Call-Future's 

535 result value will be the response message of the RPC. 

536 Should the event terminate with non-OK status, the returned 

537 Call-Future's exception value will be an RpcError. 

538 """ 

539 raise NotImplementedError() 

540 

541 

542class StreamStreamClientInterceptor(abc.ABC): 

543 """Affords intercepting stream-stream invocations.""" 

544 

545 @abc.abstractmethod 

546 def intercept_stream_stream( 

547 self, continuation, client_call_details, request_iterator 

548 ): 

549 """Intercepts a stream-stream invocation. 

550 

551 Args: 

552 continuation: A function that proceeds with the invocation by 

553 executing the next interceptor in chain or invoking the 

554 actual RPC on the underlying Channel. It is the interceptor's 

555 responsibility to call it if it decides to move the RPC forward. 

556 The interceptor can use 

557 `response_iterator = continuation(client_call_details, request_iterator)` 

558 to continue with the RPC. `continuation` returns an object that is 

559 both a Call for the RPC and an iterator for response values. 

560 Drawing response values from the returned Call-iterator may 

561 raise RpcError indicating termination of the RPC with non-OK 

562 status. 

563 client_call_details: A ClientCallDetails object describing the 

564 outgoing RPC. 

565 request_iterator: An iterator that yields request values for the RPC. 

566 

567 Returns: 

568 An object that is both a Call for the RPC and an iterator of 

569 response values. Drawing response values from the returned 

570 Call-iterator may raise RpcError indicating termination of 

571 the RPC with non-OK status. This object *should* also fulfill the 

572 Future interface, though it may not. 

573 """ 

574 raise NotImplementedError() 

575 

576 

577############ Authentication & Authorization Interfaces & Classes ############# 

578 

579 

580class ChannelCredentials: 

581 """An encapsulation of the data required to create a secure Channel. 

582 

583 This class has no supported interface - it exists to define the type of its 

584 instances and its instances exist to be passed to other functions. For 

585 example, ssl_channel_credentials returns an instance of this class and 

586 secure_channel requires an instance of this class. 

587 """ 

588 

589 _credentials: _cygrpc.ChannelCredentials 

590 

591 def __init__(self, credentials): 

592 self._credentials = credentials 

593 

594 

595class CallCredentials: 

596 """An encapsulation of the data required to assert an identity over a call. 

597 

598 A CallCredentials has to be used with secure Channel, otherwise the 

599 metadata will not be transmitted to the server. 

600 

601 A CallCredentials may be composed with ChannelCredentials to always assert 

602 identity for every call over that Channel. 

603 

604 This class has no supported interface - it exists to define the type of its 

605 instances and its instances exist to be passed to other functions. 

606 """ 

607 

608 def __init__(self, credentials): 

609 self._credentials = credentials 

610 

611 

612class AuthMetadataContext(abc.ABC): 

613 """Provides information to call credentials metadata plugins. 

614 

615 Attributes: 

616 service_url: A string URL of the service being called into. 

617 method_name: A string of the fully qualified method name being called. 

618 """ 

619 

620 

621class AuthMetadataPluginCallback(abc.ABC): 

622 """Callback object received by a metadata plugin.""" 

623 

624 def __call__(self, metadata, error): 

625 """Passes to the gRPC runtime authentication metadata for an RPC. 

626 

627 Args: 

628 metadata: The :term:`metadata` used to construct the CallCredentials. 

629 error: An Exception to indicate error or None to indicate success. 

630 """ 

631 raise NotImplementedError() 

632 

633 

634class AuthMetadataPlugin(abc.ABC): 

635 """A specification for custom authentication.""" 

636 

637 def __call__(self, context, callback): 

638 """Implements authentication by passing metadata to a callback. 

639 

640 This method will be invoked asynchronously in a separate thread. 

641 

642 Args: 

643 context: An AuthMetadataContext providing information on the RPC that 

644 the plugin is being called to authenticate. 

645 callback: An AuthMetadataPluginCallback to be invoked either 

646 synchronously or asynchronously. 

647 """ 

648 raise NotImplementedError() 

649 

650 

651class ServerCredentials: 

652 """An encapsulation of the data required to open a secure port on a Server. 

653 

654 This class has no supported interface - it exists to define the type of its 

655 instances and its instances exist to be passed to other functions. 

656 """ 

657 

658 def __init__(self, credentials): 

659 self._credentials = credentials 

660 

661 

662class ServerCertificateConfiguration: 

663 """A certificate configuration for use with an SSL-enabled Server. 

664 

665 Instances of this class can be returned in the certificate configuration 

666 fetching callback. 

667 

668 This class has no supported interface -- it exists to define the 

669 type of its instances and its instances exist to be passed to 

670 other functions. 

671 """ 

672 

673 def __init__(self, certificate_configuration): 

674 self._certificate_configuration = certificate_configuration 

675 

676 

677######################## Multi-Callable Interfaces ########################### 

678 

679 

680class UnaryUnaryMultiCallable(abc.ABC): 

681 """Affords invoking a unary-unary RPC from client-side.""" 

682 

683 @abc.abstractmethod 

684 def __call__( 

685 self, 

686 request, 

687 timeout=None, 

688 metadata=None, 

689 credentials=None, 

690 wait_for_ready=None, 

691 compression=None, 

692 ): 

693 """Synchronously invokes the underlying RPC. 

694 

695 Args: 

696 request: The request value for the RPC. 

697 timeout: An optional duration of time in seconds to allow 

698 for the RPC. 

699 metadata: Optional :term:`metadata` to be transmitted to the 

700 service-side of the RPC. 

701 credentials: An optional CallCredentials for the RPC. Only valid for 

702 secure Channel. 

703 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. 

704 compression: An element of grpc.Compression, e.g. 

705 grpc.Compression.Gzip. 

706 

707 Returns: 

708 The response value for the RPC. 

709 

710 Raises: 

711 RpcError: Indicating that the RPC terminated with non-OK status. The 

712 raised RpcError will also be a Call for the RPC affording the RPC's 

713 metadata, status code, and details. 

714 """ 

715 raise NotImplementedError() 

716 

717 @abc.abstractmethod 

718 def with_call( 

719 self, 

720 request, 

721 timeout=None, 

722 metadata=None, 

723 credentials=None, 

724 wait_for_ready=None, 

725 compression=None, 

726 ): 

727 """Synchronously invokes the underlying RPC. 

728 

729 Args: 

730 request: The request value for the RPC. 

731 timeout: An optional durating of time in seconds to allow for 

732 the RPC. 

733 metadata: Optional :term:`metadata` to be transmitted to the 

734 service-side of the RPC. 

735 credentials: An optional CallCredentials for the RPC. Only valid for 

736 secure Channel. 

737 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. 

738 compression: An element of grpc.Compression, e.g. 

739 grpc.Compression.Gzip. 

740 

741 Returns: 

742 The response value for the RPC and a Call value for the RPC. 

743 

744 Raises: 

745 RpcError: Indicating that the RPC terminated with non-OK status. The 

746 raised RpcError will also be a Call for the RPC affording the RPC's 

747 metadata, status code, and details. 

748 """ 

749 raise NotImplementedError() 

750 

751 @abc.abstractmethod 

752 def future( 

753 self, 

754 request, 

755 timeout=None, 

756 metadata=None, 

757 credentials=None, 

758 wait_for_ready=None, 

759 compression=None, 

760 ): 

761 """Asynchronously invokes the underlying RPC. 

762 

763 Args: 

764 request: The request value for the RPC. 

765 timeout: An optional duration of time in seconds to allow for 

766 the RPC. 

767 metadata: Optional :term:`metadata` to be transmitted to the 

768 service-side of the RPC. 

769 credentials: An optional CallCredentials for the RPC. Only valid for 

770 secure Channel. 

771 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. 

772 compression: An element of grpc.Compression, e.g. 

773 grpc.Compression.Gzip. 

774 

775 Returns: 

776 An object that is both a Call for the RPC and a Future. 

777 In the event of RPC completion, the return Call-Future's result 

778 value will be the response message of the RPC. 

779 Should the event terminate with non-OK status, 

780 the returned Call-Future's exception value will be an RpcError. 

781 """ 

782 raise NotImplementedError() 

783 

784 

785class UnaryStreamMultiCallable(abc.ABC): 

786 """Affords invoking a unary-stream RPC from client-side.""" 

787 

788 @abc.abstractmethod 

789 def __call__( 

790 self, 

791 request, 

792 timeout=None, 

793 metadata=None, 

794 credentials=None, 

795 wait_for_ready=None, 

796 compression=None, 

797 ): 

798 """Invokes the underlying RPC. 

799 

800 Args: 

801 request: The request value for the RPC. 

802 timeout: An optional duration of time in seconds to allow for 

803 the RPC. If None, the timeout is considered infinite. 

804 metadata: An optional :term:`metadata` to be transmitted to the 

805 service-side of the RPC. 

806 credentials: An optional CallCredentials for the RPC. Only valid for 

807 secure Channel. 

808 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. 

809 compression: An element of grpc.Compression, e.g. 

810 grpc.Compression.Gzip. 

811 

812 Returns: 

813 An object that is a Call for the RPC, an iterator of response 

814 values, and a Future for the RPC. Drawing response values from the 

815 returned Call-iterator may raise RpcError indicating termination of 

816 the RPC with non-OK status. 

817 """ 

818 raise NotImplementedError() 

819 

820 

821class StreamUnaryMultiCallable(abc.ABC): 

822 """Affords invoking a stream-unary RPC from client-side.""" 

823 

824 @abc.abstractmethod 

825 def __call__( 

826 self, 

827 request_iterator, 

828 timeout=None, 

829 metadata=None, 

830 credentials=None, 

831 wait_for_ready=None, 

832 compression=None, 

833 ): 

834 """Synchronously invokes the underlying RPC. 

835 

836 Args: 

837 request_iterator: An iterator that yields request values for 

838 the RPC. 

839 timeout: An optional duration of time in seconds to allow for 

840 the RPC. If None, the timeout is considered infinite. 

841 metadata: Optional :term:`metadata` to be transmitted to the 

842 service-side of the RPC. 

843 credentials: An optional CallCredentials for the RPC. Only valid for 

844 secure Channel. 

845 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. 

846 compression: An element of grpc.Compression, e.g. 

847 grpc.Compression.Gzip. 

848 

849 Returns: 

850 The response value for the RPC. 

851 

852 Raises: 

853 RpcError: Indicating that the RPC terminated with non-OK status. The 

854 raised RpcError will also implement grpc.Call, affording methods 

855 such as metadata, code, and details. 

856 """ 

857 raise NotImplementedError() 

858 

859 @abc.abstractmethod 

860 def with_call( 

861 self, 

862 request_iterator, 

863 timeout=None, 

864 metadata=None, 

865 credentials=None, 

866 wait_for_ready=None, 

867 compression=None, 

868 ): 

869 """Synchronously invokes the underlying RPC on the client. 

870 

871 Args: 

872 request_iterator: An iterator that yields request values for 

873 the RPC. 

874 timeout: An optional duration of time in seconds to allow for 

875 the RPC. If None, the timeout is considered infinite. 

876 metadata: Optional :term:`metadata` to be transmitted to the 

877 service-side of the RPC. 

878 credentials: An optional CallCredentials for the RPC. Only valid for 

879 secure Channel. 

880 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. 

881 compression: An element of grpc.Compression, e.g. 

882 grpc.Compression.Gzip. 

883 

884 Returns: 

885 The response value for the RPC and a Call object for the RPC. 

886 

887 Raises: 

888 RpcError: Indicating that the RPC terminated with non-OK status. The 

889 raised RpcError will also be a Call for the RPC affording the RPC's 

890 metadata, status code, and details. 

891 """ 

892 raise NotImplementedError() 

893 

894 @abc.abstractmethod 

895 def future( 

896 self, 

897 request_iterator, 

898 timeout=None, 

899 metadata=None, 

900 credentials=None, 

901 wait_for_ready=None, 

902 compression=None, 

903 ): 

904 """Asynchronously invokes the underlying RPC on the client. 

905 

906 Args: 

907 request_iterator: An iterator that yields request values for the RPC. 

908 timeout: An optional duration of time in seconds to allow for 

909 the RPC. If None, the timeout is considered infinite. 

910 metadata: Optional :term:`metadata` to be transmitted to the 

911 service-side of the RPC. 

912 credentials: An optional CallCredentials for the RPC. Only valid for 

913 secure Channel. 

914 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. 

915 compression: An element of grpc.Compression, e.g. 

916 grpc.Compression.Gzip. 

917 

918 Returns: 

919 An object that is both a Call for the RPC and a Future. 

920 In the event of RPC completion, the return Call-Future's result value 

921 will be the response message of the RPC. Should the event terminate 

922 with non-OK status, the returned Call-Future's exception value will 

923 be an RpcError. 

924 """ 

925 raise NotImplementedError() 

926 

927 

928class StreamStreamMultiCallable(abc.ABC): 

929 """Affords invoking a stream-stream RPC on client-side.""" 

930 

931 @abc.abstractmethod 

932 def __call__( 

933 self, 

934 request_iterator, 

935 timeout=None, 

936 metadata=None, 

937 credentials=None, 

938 wait_for_ready=None, 

939 compression=None, 

940 ): 

941 """Invokes the underlying RPC on the client. 

942 

943 Args: 

944 request_iterator: An iterator that yields request values for the RPC. 

945 timeout: An optional duration of time in seconds to allow for 

946 the RPC. If not specified, the timeout is considered infinite. 

947 metadata: Optional :term:`metadata` to be transmitted to the 

948 service-side of the RPC. 

949 credentials: An optional CallCredentials for the RPC. Only valid for 

950 secure Channel. 

951 wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. 

952 compression: An element of grpc.Compression, e.g. 

953 grpc.Compression.Gzip. 

954 

955 Returns: 

956 An object that is a Call for the RPC, an iterator of response 

957 values, and a Future for the RPC. Drawing response values from the 

958 returned Call-iterator may raise RpcError indicating termination of 

959 the RPC with non-OK status. 

960 """ 

961 raise NotImplementedError() 

962 

963 

964############################# Channel Interface ############################## 

965 

966 

967class Channel(abc.ABC): 

968 """Affords RPC invocation via generic methods on client-side. 

969 

970 Channel objects implement the Context Manager type, although they need not 

971 support being entered and exited multiple times. 

972 """ 

973 

974 @abc.abstractmethod 

975 def subscribe(self, callback, try_to_connect=False): 

976 """Subscribe to this Channel's connectivity state machine. 

977 

978 A Channel may be in any of the states described by ChannelConnectivity. 

979 This method allows application to monitor the state transitions. 

980 The typical use case is to debug or gain better visibility into gRPC 

981 runtime's state. 

982 

983 Args: 

984 callback: A callable to be invoked with ChannelConnectivity argument. 

985 ChannelConnectivity describes current state of the channel. 

986 The callable will be invoked immediately upon subscription 

987 and again for every change to ChannelConnectivity until it 

988 is unsubscribed or this Channel object goes out of scope. 

989 try_to_connect: A boolean indicating whether or not this Channel 

990 should attempt to connect immediately. If set to False, gRPC 

991 runtime decides when to connect. 

992 """ 

993 raise NotImplementedError() 

994 

995 @abc.abstractmethod 

996 def unsubscribe(self, callback): 

997 """Unsubscribes a subscribed callback from this Channel's connectivity. 

998 

999 Args: 

1000 callback: A callable previously registered with this Channel from 

1001 having been passed to its "subscribe" method. 

1002 """ 

1003 raise NotImplementedError() 

1004 

1005 @abc.abstractmethod 

1006 def unary_unary( 

1007 self, 

1008 method, 

1009 request_serializer=None, 

1010 response_deserializer=None, 

1011 _registered_method=False, 

1012 ): 

1013 """Creates a UnaryUnaryMultiCallable for a unary-unary method. 

1014 

1015 Args: 

1016 method: The name of the RPC method. 

1017 request_serializer: Optional :term:`serializer` for serializing the request 

1018 message. Request goes unserialized in case None is passed. 

1019 response_deserializer: Optional :term:`deserializer` for deserializing the 

1020 response message. Response goes undeserialized in case None 

1021 is passed. 

1022 _registered_method: Implementation Private. A bool representing whether the method 

1023 is registered. 

1024 

1025 Returns: 

1026 A UnaryUnaryMultiCallable value for the named unary-unary method. 

1027 """ 

1028 raise NotImplementedError() 

1029 

1030 @abc.abstractmethod 

1031 def unary_stream( 

1032 self, 

1033 method, 

1034 request_serializer=None, 

1035 response_deserializer=None, 

1036 _registered_method=False, 

1037 ): 

1038 """Creates a UnaryStreamMultiCallable for a unary-stream method. 

1039 

1040 Args: 

1041 method: The name of the RPC method. 

1042 request_serializer: Optional :term:`serializer` for serializing the request 

1043 message. Request goes unserialized in case None is passed. 

1044 response_deserializer: Optional :term:`deserializer` for deserializing the 

1045 response message. Response goes undeserialized in case None is 

1046 passed. 

1047 _registered_method: Implementation Private. A bool representing whether the method 

1048 is registered. 

1049 

1050 Returns: 

1051 A UnaryStreamMultiCallable value for the name unary-stream method. 

1052 """ 

1053 raise NotImplementedError() 

1054 

1055 @abc.abstractmethod 

1056 def stream_unary( 

1057 self, 

1058 method, 

1059 request_serializer=None, 

1060 response_deserializer=None, 

1061 _registered_method=False, 

1062 ): 

1063 """Creates a StreamUnaryMultiCallable for a stream-unary method. 

1064 

1065 Args: 

1066 method: The name of the RPC method. 

1067 request_serializer: Optional :term:`serializer` for serializing the request 

1068 message. Request goes unserialized in case None is passed. 

1069 response_deserializer: Optional :term:`deserializer` for deserializing the 

1070 response message. Response goes undeserialized in case None is 

1071 passed. 

1072 _registered_method: Implementation Private. A bool representing whether the method 

1073 is registered. 

1074 

1075 Returns: 

1076 A StreamUnaryMultiCallable value for the named stream-unary method. 

1077 """ 

1078 raise NotImplementedError() 

1079 

1080 @abc.abstractmethod 

1081 def stream_stream( 

1082 self, 

1083 method, 

1084 request_serializer=None, 

1085 response_deserializer=None, 

1086 _registered_method=False, 

1087 ): 

1088 """Creates a StreamStreamMultiCallable for a stream-stream method. 

1089 

1090 Args: 

1091 method: The name of the RPC method. 

1092 request_serializer: Optional :term:`serializer` for serializing the request 

1093 message. Request goes unserialized in case None is passed. 

1094 response_deserializer: Optional :term:`deserializer` for deserializing the 

1095 response message. Response goes undeserialized in case None 

1096 is passed. 

1097 _registered_method: Implementation Private. A bool representing whether the method 

1098 is registered. 

1099 

1100 Returns: 

1101 A StreamStreamMultiCallable value for the named stream-stream method. 

1102 """ 

1103 raise NotImplementedError() 

1104 

1105 @abc.abstractmethod 

1106 def close(self): 

1107 """Closes this Channel and releases all resources held by it. 

1108 

1109 Closing the Channel will immediately terminate all RPCs active with the 

1110 Channel and it is not valid to invoke new RPCs with the Channel. 

1111 

1112 This method is idempotent. 

1113 """ 

1114 raise NotImplementedError() 

1115 

1116 def __enter__(self): 

1117 """Enters the runtime context related to the channel object.""" 

1118 raise NotImplementedError() 

1119 

1120 def __exit__(self, exc_type, exc_val, exc_tb): 

1121 """Exits the runtime context related to the channel object.""" 

1122 raise NotImplementedError() 

1123 

1124 

1125########################## Service-Side Context ############################## 

1126 

1127 

1128class ServicerContext(RpcContext, metaclass=abc.ABCMeta): 

1129 """A context object passed to method implementations.""" 

1130 

1131 @abc.abstractmethod 

1132 def invocation_metadata(self): 

1133 """Accesses the metadata sent by the client. 

1134 

1135 Returns: 

1136 The invocation :term:`metadata`. 

1137 """ 

1138 raise NotImplementedError() 

1139 

1140 @abc.abstractmethod 

1141 def peer(self): 

1142 """Identifies the peer that invoked the RPC being serviced. 

1143 

1144 Returns: 

1145 A string identifying the peer that invoked the RPC being serviced. 

1146 The string format is determined by gRPC runtime. 

1147 """ 

1148 raise NotImplementedError() 

1149 

1150 @abc.abstractmethod 

1151 def peer_identities(self): 

1152 """Gets one or more peer identity(s). 

1153 

1154 Equivalent to 

1155 servicer_context.auth_context().get(servicer_context.peer_identity_key()) 

1156 

1157 Returns: 

1158 An iterable of the identities, or None if the call is not 

1159 authenticated. Each identity is returned as a raw bytes type. 

1160 """ 

1161 raise NotImplementedError() 

1162 

1163 @abc.abstractmethod 

1164 def peer_identity_key(self): 

1165 """The auth property used to identify the peer. 

1166 

1167 For example, "x509_common_name" or "x509_subject_alternative_name" are 

1168 used to identify an SSL peer. 

1169 

1170 Returns: 

1171 The auth property (string) that indicates the 

1172 peer identity, or None if the call is not authenticated. 

1173 """ 

1174 raise NotImplementedError() 

1175 

1176 @abc.abstractmethod 

1177 def auth_context(self): 

1178 """Gets the auth context for the call. 

1179 

1180 Returns: 

1181 A map of strings to an iterable of bytes for each auth property. 

1182 """ 

1183 raise NotImplementedError() 

1184 

1185 def set_compression(self, compression): 

1186 """Set the compression algorithm to be used for the entire call. 

1187 

1188 Args: 

1189 compression: An element of grpc.Compression, e.g. 

1190 grpc.Compression.Gzip. 

1191 """ 

1192 raise NotImplementedError() 

1193 

1194 @abc.abstractmethod 

1195 def send_initial_metadata(self, initial_metadata): 

1196 """Sends the initial metadata value to the client. 

1197 

1198 This method need not be called by implementations if they have no 

1199 metadata to add to what the gRPC runtime will transmit. 

1200 

1201 Args: 

1202 initial_metadata: The initial :term:`metadata`. 

1203 """ 

1204 raise NotImplementedError() 

1205 

1206 @abc.abstractmethod 

1207 def set_trailing_metadata(self, trailing_metadata): 

1208 """Sets the trailing metadata for the RPC. 

1209 

1210 Sets the trailing metadata to be sent upon completion of the RPC. 

1211 

1212 If this method is invoked multiple times throughout the lifetime of an 

1213 RPC, the value supplied in the final invocation will be the value sent 

1214 over the wire. 

1215 

1216 This method need not be called by implementations if they have no 

1217 metadata to add to what the gRPC runtime will transmit. 

1218 

1219 Args: 

1220 trailing_metadata: The trailing :term:`metadata`. 

1221 """ 

1222 raise NotImplementedError() 

1223 

1224 def trailing_metadata(self): 

1225 """Access value to be used as trailing metadata upon RPC completion. 

1226 

1227 This is an EXPERIMENTAL API. 

1228 

1229 Returns: 

1230 The trailing :term:`metadata` for the RPC. 

1231 """ 

1232 raise NotImplementedError() 

1233 

1234 @abc.abstractmethod 

1235 def abort(self, code, details): 

1236 """Raises an exception to terminate the RPC with a non-OK status. 

1237 

1238 The code and details passed as arguments will supersede any existing 

1239 ones. 

1240 

1241 Args: 

1242 code: A StatusCode object to be sent to the client. 

1243 It must not be StatusCode.OK. 

1244 details: A UTF-8-encodable string to be sent to the client upon 

1245 termination of the RPC. 

1246 

1247 Raises: 

1248 Exception: An exception is always raised to signal the abortion the 

1249 RPC to the gRPC runtime. 

1250 """ 

1251 raise NotImplementedError() 

1252 

1253 @abc.abstractmethod 

1254 def abort_with_status(self, status): 

1255 """Raises an exception to terminate the RPC with a non-OK status. 

1256 

1257 The status passed as argument will supersede any existing status code, 

1258 status message and trailing metadata. 

1259 

1260 This is an EXPERIMENTAL API. 

1261 

1262 Args: 

1263 status: A grpc.Status object. The status code in it must not be 

1264 StatusCode.OK. 

1265 

1266 Raises: 

1267 Exception: An exception is always raised to signal the abortion the 

1268 RPC to the gRPC runtime. 

1269 """ 

1270 raise NotImplementedError() 

1271 

1272 @abc.abstractmethod 

1273 def set_code(self, code): 

1274 """Sets the value to be used as status code upon RPC completion. 

1275 

1276 This method need not be called by method implementations if they wish 

1277 the gRPC runtime to determine the status code of the RPC. 

1278 

1279 Args: 

1280 code: A StatusCode object to be sent to the client. 

1281 """ 

1282 raise NotImplementedError() 

1283 

1284 @abc.abstractmethod 

1285 def set_details(self, details): 

1286 """Sets the value to be used as detail string upon RPC completion. 

1287 

1288 This method need not be called by method implementations if they have 

1289 no details to transmit. 

1290 

1291 Args: 

1292 details: A UTF-8-encodable string to be sent to the client upon 

1293 termination of the RPC. 

1294 """ 

1295 raise NotImplementedError() 

1296 

1297 def code(self): 

1298 """Accesses the value to be used as status code upon RPC completion. 

1299 

1300 This is an EXPERIMENTAL API. 

1301 

1302 Returns: 

1303 The StatusCode value for the RPC. 

1304 """ 

1305 raise NotImplementedError() 

1306 

1307 def details(self): 

1308 """Accesses the value to be used as detail string upon RPC completion. 

1309 

1310 This is an EXPERIMENTAL API. 

1311 

1312 Returns: 

1313 The details string of the RPC. 

1314 """ 

1315 raise NotImplementedError() 

1316 

1317 def disable_next_message_compression(self): 

1318 """Disables compression for the next response message. 

1319 

1320 This method will override any compression configuration set during 

1321 server creation or set on the call. 

1322 """ 

1323 raise NotImplementedError() 

1324 

1325 

1326##################### Service-Side Handler Interfaces ######################## 

1327 

1328 

1329class RpcMethodHandler(abc.ABC): 

1330 """An implementation of a single RPC method. 

1331 

1332 Attributes: 

1333 request_streaming: Whether the RPC supports exactly one request message 

1334 or any arbitrary number of request messages. 

1335 response_streaming: Whether the RPC supports exactly one response message 

1336 or any arbitrary number of response messages. 

1337 request_deserializer: A callable :term:`deserializer` that accepts a byte string and 

1338 returns an object suitable to be passed to this object's business 

1339 logic, or None to indicate that this object's business logic should be 

1340 passed the raw request bytes. 

1341 response_serializer: A callable :term:`serializer` that accepts an object produced 

1342 by this object's business logic and returns a byte string, or None to 

1343 indicate that the byte strings produced by this object's business logic 

1344 should be transmitted on the wire as they are. 

1345 unary_unary: This object's application-specific business logic as a 

1346 callable value that takes a request value and a ServicerContext object 

1347 and returns a response value. Only non-None if both request_streaming 

1348 and response_streaming are False. 

1349 unary_stream: This object's application-specific business logic as a 

1350 callable value that takes a request value and a ServicerContext object 

1351 and returns an iterator of response values. Only non-None if 

1352 request_streaming is False and response_streaming is True. 

1353 stream_unary: 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 a response value. Only non-None if 

1356 request_streaming is True and response_streaming is False. 

1357 stream_stream: This object's application-specific business logic as a 

1358 callable value that takes an iterator of request values and a 

1359 ServicerContext object and returns an iterator of response values. 

1360 Only non-None if request_streaming and response_streaming are both 

1361 True. 

1362 """ 

1363 

1364 

1365@typing.runtime_checkable 

1366class HandlerCallDetails(Protocol): 

1367 """Describes an RPC that has just arrived for service. 

1368 

1369 Attributes: 

1370 method: The method name of the RPC. 

1371 invocation_metadata: The :term:`metadata` sent by the client. 

1372 """ 

1373 

1374 method: str 

1375 invocation_metadata: Any 

1376 

1377 

1378class GenericRpcHandler(abc.ABC): 

1379 """An implementation of arbitrarily many RPC methods.""" 

1380 

1381 @abc.abstractmethod 

1382 def service(self, handler_call_details): 

1383 """Returns the handler for servicing the RPC. 

1384 

1385 Args: 

1386 handler_call_details: A HandlerCallDetails describing the RPC. 

1387 

1388 Returns: 

1389 An RpcMethodHandler with which the RPC may be serviced if the 

1390 implementation chooses to service this RPC, or None otherwise. 

1391 """ 

1392 raise NotImplementedError() 

1393 

1394 

1395class ServiceRpcHandler(GenericRpcHandler, metaclass=abc.ABCMeta): 

1396 """An implementation of RPC methods belonging to a service. 

1397 

1398 A service handles RPC methods with structured names of the form 

1399 '/Service.Name/Service.Method', where 'Service.Name' is the value 

1400 returned by service_name(), and 'Service.Method' is the method 

1401 name. A service can have multiple method names, but only a single 

1402 service name. 

1403 """ 

1404 

1405 @abc.abstractmethod 

1406 def service_name(self): 

1407 """Returns this service's name. 

1408 

1409 Returns: 

1410 The service name. 

1411 """ 

1412 raise NotImplementedError() 

1413 

1414 

1415#################### Service-Side Interceptor Interfaces ##################### 

1416 

1417 

1418class ServerInterceptor(abc.ABC): 

1419 """Affords intercepting incoming RPCs on the service-side.""" 

1420 

1421 @abc.abstractmethod 

1422 def intercept_service(self, continuation, handler_call_details): 

1423 """Intercepts incoming RPCs before handing them over to a handler. 

1424 

1425 State can be passed from an interceptor to downstream interceptors 

1426 via contextvars. The first interceptor is called from an empty 

1427 contextvars.Context, and the same Context is used for downstream 

1428 interceptors and for the final handler call. Note that there are no 

1429 guarantees that interceptors and handlers will be called from the 

1430 same thread. 

1431 

1432 Args: 

1433 continuation: A function that takes a HandlerCallDetails and 

1434 proceeds to invoke the next interceptor in the chain, if any, 

1435 or the RPC handler lookup logic, with the call details passed 

1436 as an argument, and returns an RpcMethodHandler instance if 

1437 the RPC is considered serviced, or None otherwise. 

1438 handler_call_details: A HandlerCallDetails describing the RPC. 

1439 

1440 Returns: 

1441 An RpcMethodHandler with which the RPC may be serviced if the 

1442 interceptor chooses to service this RPC, or None otherwise. 

1443 """ 

1444 raise NotImplementedError() 

1445 

1446 

1447############################# Server Interface ############################### 

1448 

1449 

1450class Server(abc.ABC): 

1451 """Services RPCs.""" 

1452 

1453 @abc.abstractmethod 

1454 def add_generic_rpc_handlers(self, generic_rpc_handlers): 

1455 """Registers GenericRpcHandlers with this Server. 

1456 

1457 This method is only safe to call before the server is started. 

1458 

1459 Args: 

1460 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be 

1461 used to service RPCs. 

1462 """ 

1463 raise NotImplementedError() 

1464 

1465 def add_registered_method_handlers( # noqa: B027 

1466 self, service_name, method_handlers 

1467 ): 

1468 """Registers GenericRpcHandlers with this Server. 

1469 

1470 This method is only safe to call before the server is started. 

1471 

1472 If the same method have both generic and registered handler, 

1473 registered handler will take precedence. 

1474 

1475 Args: 

1476 service_name: The service name. 

1477 method_handlers: A dictionary that maps method names to corresponding 

1478 RpcMethodHandler. 

1479 """ 

1480 

1481 @abc.abstractmethod 

1482 def add_insecure_port(self, address): 

1483 """Opens an insecure port for accepting RPCs. 

1484 

1485 This method may only be called before starting the server. 

1486 

1487 Args: 

1488 address: The address for which to open a port. If the port is 0, 

1489 or not specified in the address, then gRPC runtime will choose a port. 

1490 

1491 Returns: 

1492 An integer port on which server will accept RPC requests. 

1493 """ 

1494 raise NotImplementedError() 

1495 

1496 @abc.abstractmethod 

1497 def add_secure_port(self, address, server_credentials): 

1498 """Opens a secure port for accepting RPCs. 

1499 

1500 This method may only be called before starting the server. 

1501 

1502 Args: 

1503 address: The address for which to open a port. 

1504 if the port is 0, or not specified in the address, then gRPC 

1505 runtime will choose a port. 

1506 server_credentials: A ServerCredentials object. 

1507 

1508 Returns: 

1509 An integer port on which server will accept RPC requests. 

1510 """ 

1511 raise NotImplementedError() 

1512 

1513 @abc.abstractmethod 

1514 def start(self): 

1515 """Starts this Server. 

1516 

1517 This method may only be called once. (i.e. it is not idempotent). 

1518 """ 

1519 raise NotImplementedError() 

1520 

1521 @abc.abstractmethod 

1522 def stop(self, grace): 

1523 """Stops this Server. 

1524 

1525 This method immediately stop service of new RPCs in all cases. 

1526 

1527 If a grace period is specified, this method waits until all active 

1528 RPCs are finished or until the grace period is reached. RPCs that haven't 

1529 been terminated within the grace period are aborted. 

1530 If a grace period is not specified (by passing None for `grace`), 

1531 all existing RPCs are aborted immediately and this method 

1532 blocks until the last RPC handler terminates. 

1533 

1534 This method is idempotent and may be called at any time. 

1535 Passing a smaller grace value in a subsequent call will have 

1536 the effect of stopping the Server sooner (passing None will 

1537 have the effect of stopping the server immediately). Passing 

1538 a larger grace value in a subsequent call *will not* have the 

1539 effect of stopping the server later (i.e. the most restrictive 

1540 grace value is used). 

1541 

1542 Args: 

1543 grace: A duration of time in seconds or None. 

1544 

1545 Returns: 

1546 A threading.Event that will be set when this Server has completely 

1547 stopped, i.e. when running RPCs either complete or are aborted and 

1548 all handlers have terminated. 

1549 """ 

1550 raise NotImplementedError() 

1551 

1552 def wait_for_termination(self, timeout=None): 

1553 """Block current thread until the server stops. 

1554 

1555 This is an EXPERIMENTAL API. 

1556 

1557 The wait will not consume computational resources during blocking, and 

1558 it will block until one of the two following conditions are met: 

1559 

1560 1) The server is stopped or terminated; 

1561 2) A timeout occurs if timeout is not `None`. 

1562 

1563 The timeout argument works in the same way as `threading.Event.wait()`. 

1564 https://docs.python.org/3/library/threading.html#threading.Event.wait 

1565 

1566 Args: 

1567 timeout: A floating point number specifying a timeout for the 

1568 operation in seconds. 

1569 

1570 Returns: 

1571 A bool indicates if the operation times out. 

1572 """ 

1573 raise NotImplementedError() 

1574 

1575 

1576################################# Functions ################################ 

1577 

1578 

1579def unary_unary_rpc_method_handler( 

1580 behavior, request_deserializer=None, response_serializer=None 

1581): 

1582 """Creates an RpcMethodHandler for a unary-unary RPC method. 

1583 

1584 Args: 

1585 behavior: The implementation of an RPC that accepts one request 

1586 and returns one response. 

1587 request_deserializer: An optional :term:`deserializer` for request deserialization. 

1588 response_serializer: An optional :term:`serializer` for response serialization. 

1589 

1590 Returns: 

1591 An RpcMethodHandler object that is typically used by grpc.Server. 

1592 """ 

1593 from grpc import _utilities # pylint: disable=cyclic-import 

1594 

1595 return _utilities.RpcMethodHandler( 

1596 False, 

1597 False, 

1598 request_deserializer, 

1599 response_serializer, 

1600 behavior, 

1601 None, 

1602 None, 

1603 None, 

1604 ) 

1605 

1606 

1607def unary_stream_rpc_method_handler( 

1608 behavior, request_deserializer=None, response_serializer=None 

1609): 

1610 """Creates an RpcMethodHandler for a unary-stream RPC method. 

1611 

1612 Args: 

1613 behavior: The implementation of an RPC that accepts one request 

1614 and returns an iterator of response values. 

1615 request_deserializer: An optional :term:`deserializer` for request deserialization. 

1616 response_serializer: An optional :term:`serializer` for response serialization. 

1617 

1618 Returns: 

1619 An RpcMethodHandler object that is typically used by grpc.Server. 

1620 """ 

1621 from grpc import _utilities # pylint: disable=cyclic-import 

1622 

1623 return _utilities.RpcMethodHandler( 

1624 False, 

1625 True, 

1626 request_deserializer, 

1627 response_serializer, 

1628 None, 

1629 behavior, 

1630 None, 

1631 None, 

1632 ) 

1633 

1634 

1635def stream_unary_rpc_method_handler( 

1636 behavior, request_deserializer=None, response_serializer=None 

1637): 

1638 """Creates an RpcMethodHandler for a stream-unary RPC method. 

1639 

1640 Args: 

1641 behavior: The implementation of an RPC that accepts an iterator of 

1642 request values and returns a single response value. 

1643 request_deserializer: An optional :term:`deserializer` for request deserialization. 

1644 response_serializer: An optional :term:`serializer` for response serialization. 

1645 

1646 Returns: 

1647 An RpcMethodHandler object that is typically used by grpc.Server. 

1648 """ 

1649 from grpc import _utilities # pylint: disable=cyclic-import 

1650 

1651 return _utilities.RpcMethodHandler( 

1652 True, 

1653 False, 

1654 request_deserializer, 

1655 response_serializer, 

1656 None, 

1657 None, 

1658 behavior, 

1659 None, 

1660 ) 

1661 

1662 

1663def stream_stream_rpc_method_handler( 

1664 behavior, request_deserializer=None, response_serializer=None 

1665): 

1666 """Creates an RpcMethodHandler for a stream-stream RPC method. 

1667 

1668 Args: 

1669 behavior: The implementation of an RPC that accepts an iterator of 

1670 request values and returns an iterator of response values. 

1671 request_deserializer: An optional :term:`deserializer` for request deserialization. 

1672 response_serializer: An optional :term:`serializer` for response serialization. 

1673 

1674 Returns: 

1675 An RpcMethodHandler object that is typically used by grpc.Server. 

1676 """ 

1677 from grpc import _utilities # pylint: disable=cyclic-import 

1678 

1679 return _utilities.RpcMethodHandler( 

1680 True, 

1681 True, 

1682 request_deserializer, 

1683 response_serializer, 

1684 None, 

1685 None, 

1686 None, 

1687 behavior, 

1688 ) 

1689 

1690 

1691def method_handlers_generic_handler(service, method_handlers): 

1692 """Creates a GenericRpcHandler from RpcMethodHandlers. 

1693 

1694 Args: 

1695 service: The name of the service that is implemented by the 

1696 method_handlers. 

1697 method_handlers: A dictionary that maps method names to corresponding 

1698 RpcMethodHandler. 

1699 

1700 Returns: 

1701 A GenericRpcHandler. This is typically added to the grpc.Server object 

1702 with add_generic_rpc_handlers() before starting the server. 

1703 """ 

1704 from grpc import _utilities # pylint: disable=cyclic-import 

1705 

1706 return _utilities.DictionaryGenericHandler(service, method_handlers) 

1707 

1708 

1709def ssl_channel_credentials( 

1710 root_certificates=None, private_key=None, certificate_chain=None 

1711): 

1712 """Creates a ChannelCredentials for use with an SSL-enabled Channel. 

1713 

1714 Args: 

1715 root_certificates: The PEM-encoded root certificates as a byte string, 

1716 or None to retrieve them from a default location chosen by gRPC 

1717 runtime. 

1718 private_key: The PEM-encoded private key as a byte string, or None if no 

1719 private key should be used. 

1720 certificate_chain: The PEM-encoded certificate chain as a byte string 

1721 to use or None if no certificate chain should be used. 

1722 

1723 Returns: 

1724 A ChannelCredentials for use with an SSL-enabled Channel. 

1725 """ 

1726 return ChannelCredentials( 

1727 _cygrpc.SSLChannelCredentials( 

1728 root_certificates, private_key, certificate_chain 

1729 ) 

1730 ) 

1731 

1732 

1733def xds_channel_credentials(fallback_credentials=None): 

1734 """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL 

1735 API. 

1736 

1737 Args: 

1738 fallback_credentials: Credentials to use in case it is not possible to 

1739 establish a secure connection via xDS. If no fallback_credentials 

1740 argument is supplied, a default SSLChannelCredentials is used. 

1741 """ 

1742 fallback_credentials = ( 

1743 ssl_channel_credentials() 

1744 if fallback_credentials is None 

1745 else fallback_credentials 

1746 ) 

1747 return ChannelCredentials( 

1748 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials) 

1749 ) 

1750 

1751 

1752def metadata_call_credentials(metadata_plugin, name=None): 

1753 """Construct CallCredentials from an AuthMetadataPlugin. 

1754 

1755 Args: 

1756 metadata_plugin: An AuthMetadataPlugin to use for authentication. 

1757 name: An optional name for the plugin. 

1758 

1759 Returns: 

1760 A CallCredentials. 

1761 """ 

1762 from grpc import _plugin_wrapping # pylint: disable=cyclic-import 

1763 

1764 return _plugin_wrapping.metadata_plugin_call_credentials( 

1765 metadata_plugin, name 

1766 ) 

1767 

1768 

1769def access_token_call_credentials(access_token): 

1770 """Construct CallCredentials from an access token. 

1771 

1772 Args: 

1773 access_token: A string to place directly in the http request 

1774 authorization header, for example 

1775 "authorization: Bearer <access_token>". 

1776 

1777 Returns: 

1778 A CallCredentials. 

1779 """ 

1780 from grpc import _auth # pylint: disable=cyclic-import 

1781 from grpc import _plugin_wrapping # pylint: disable=cyclic-import 

1782 

1783 return _plugin_wrapping.metadata_plugin_call_credentials( 

1784 _auth.AccessTokenAuthMetadataPlugin(access_token), None 

1785 ) 

1786 

1787 

1788def composite_call_credentials(*call_credentials): 

1789 """Compose multiple CallCredentials to make a new CallCredentials. 

1790 

1791 Args: 

1792 *call_credentials: At least two CallCredentials objects. 

1793 

1794 Returns: 

1795 A CallCredentials object composed of the given CallCredentials objects. 

1796 """ 

1797 return CallCredentials( 

1798 _cygrpc.CompositeCallCredentials( 

1799 tuple( 

1800 single_call_credentials._credentials 

1801 for single_call_credentials in call_credentials 

1802 ) 

1803 ) 

1804 ) 

1805 

1806 

1807def composite_channel_credentials(channel_credentials, *call_credentials): 

1808 """Compose a ChannelCredentials and one or more CallCredentials objects. 

1809 

1810 Args: 

1811 channel_credentials: A ChannelCredentials object. 

1812 *call_credentials: One or more CallCredentials objects. 

1813 

1814 Returns: 

1815 A ChannelCredentials composed of the given ChannelCredentials and 

1816 CallCredentials objects. 

1817 """ 

1818 return ChannelCredentials( 

1819 _cygrpc.CompositeChannelCredentials( 

1820 tuple( 

1821 single_call_credentials._credentials 

1822 for single_call_credentials in call_credentials 

1823 ), 

1824 channel_credentials._credentials, 

1825 ) 

1826 ) 

1827 

1828 

1829def ssl_server_credentials( 

1830 private_key_certificate_chain_pairs, 

1831 root_certificates=None, 

1832 require_client_auth=False, 

1833): 

1834 """Creates a ServerCredentials for use with an SSL-enabled Server. 

1835 

1836 Args: 

1837 private_key_certificate_chain_pairs: A list of pairs of the form 

1838 [PEM-encoded private key, PEM-encoded certificate chain]. 

1839 root_certificates: An optional byte string of PEM-encoded client root 

1840 certificates that the server will use to verify client authentication. 

1841 If omitted, require_client_auth must also be False. 

1842 require_client_auth: A boolean indicating whether or not to require 

1843 clients to be authenticated. May only be True if root_certificates 

1844 is not None. 

1845 

1846 Returns: 

1847 A ServerCredentials for use with an SSL-enabled Server. Typically, this 

1848 object is an argument to add_secure_port() method during server setup. 

1849 """ 

1850 if not private_key_certificate_chain_pairs: 

1851 error_msg = ( 

1852 "At least one private key-certificate chain pair is required!" 

1853 ) 

1854 raise ValueError(error_msg) 

1855 if require_client_auth and root_certificates is None: 

1856 error_msg = "Illegal to require client auth without providing root certificates!" 

1857 raise ValueError(error_msg) 

1858 return ServerCredentials( 

1859 _cygrpc.server_credentials_ssl( 

1860 root_certificates, 

1861 [ 

1862 _cygrpc.SslPemKeyCertPair(key, pem) 

1863 for key, pem in private_key_certificate_chain_pairs 

1864 ], 

1865 require_client_auth, 

1866 ) 

1867 ) 

1868 

1869 

1870def xds_server_credentials(fallback_credentials): 

1871 """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL 

1872 API. 

1873 

1874 Args: 

1875 fallback_credentials: Credentials to use in case it is not possible to 

1876 establish a secure connection via xDS. No default value is provided. 

1877 """ 

1878 return ServerCredentials( 

1879 _cygrpc.xds_server_credentials(fallback_credentials._credentials) 

1880 ) 

1881 

1882 

1883def insecure_server_credentials(): 

1884 """Creates a credentials object directing the server to use no credentials. 

1885 This is an EXPERIMENTAL API. 

1886 

1887 This object cannot be used directly in a call to `add_secure_port`. 

1888 Instead, it should be used to construct other credentials objects, e.g. 

1889 with xds_server_credentials. 

1890 """ 

1891 return ServerCredentials(_cygrpc.insecure_server_credentials()) 

1892 

1893 

1894def ssl_server_certificate_configuration( 

1895 private_key_certificate_chain_pairs, root_certificates=None 

1896): 

1897 """Creates a ServerCertificateConfiguration for use with a Server. 

1898 

1899 Args: 

1900 private_key_certificate_chain_pairs: A collection of pairs of 

1901 the form [PEM-encoded private key, PEM-encoded certificate 

1902 chain]. 

1903 root_certificates: An optional byte string of PEM-encoded client root 

1904 certificates that the server will use to verify client authentication. 

1905 

1906 Returns: 

1907 A ServerCertificateConfiguration that can be returned in the certificate 

1908 configuration fetching callback. 

1909 """ 

1910 if private_key_certificate_chain_pairs: 

1911 return ServerCertificateConfiguration( 

1912 _cygrpc.server_certificate_config_ssl( 

1913 root_certificates, 

1914 [ 

1915 _cygrpc.SslPemKeyCertPair(key, pem) 

1916 for key, pem in private_key_certificate_chain_pairs 

1917 ], 

1918 ) 

1919 ) 

1920 error_msg = "At least one private key-certificate chain pair is required!" 

1921 raise ValueError(error_msg) 

1922 

1923 

1924def dynamic_ssl_server_credentials( 

1925 initial_certificate_configuration, 

1926 certificate_configuration_fetcher, 

1927 require_client_authentication=False, 

1928): 

1929 """Creates a ServerCredentials for use with an SSL-enabled Server. 

1930 

1931 Args: 

1932 initial_certificate_configuration (ServerCertificateConfiguration): The 

1933 certificate configuration with which the server will be initialized. 

1934 certificate_configuration_fetcher (callable): A callable that takes no 

1935 arguments and should return a ServerCertificateConfiguration to 

1936 replace the server's current certificate, or None for no change 

1937 (i.e., the server will continue its current certificate 

1938 config). The library will call this callback on *every* new 

1939 client connection before starting the TLS handshake with the 

1940 client, thus allowing the user application to optionally 

1941 return a new ServerCertificateConfiguration that the server will then 

1942 use for the handshake. 

1943 require_client_authentication: A boolean indicating whether or not to 

1944 require clients to be authenticated. 

1945 

1946 Returns: 

1947 A ServerCredentials. 

1948 """ 

1949 return ServerCredentials( 

1950 _cygrpc.server_credentials_ssl_dynamic_cert_config( 

1951 initial_certificate_configuration, 

1952 certificate_configuration_fetcher, 

1953 require_client_authentication, 

1954 ) 

1955 ) 

1956 

1957 

1958@enum.unique 

1959class LocalConnectionType(enum.Enum): 

1960 """Types of local connection for local credential creation. 

1961 

1962 Attributes: 

1963 UDS: Unix domain socket connections 

1964 LOCAL_TCP: Local TCP connections. 

1965 """ 

1966 

1967 UDS = _cygrpc.LocalConnectionType.uds 

1968 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp 

1969 

1970 

1971def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 

1972 """Creates a local ChannelCredentials used for local connections. 

1973 

1974 This is an EXPERIMENTAL API. 

1975 

1976 Local credentials are used by local TCP endpoints (e.g. localhost:10000) 

1977 also UDS connections. 

1978 

1979 The connections created by local channel credentials are not 

1980 encrypted, but will be checked if they are local or not. 

1981 The UDS connections are considered secure by providing peer authentication 

1982 and data confidentiality while TCP connections are considered insecure. 

1983 

1984 It is allowed to transmit call credentials over connections created by 

1985 local channel credentials. 

1986 

1987 Local channel credentials are useful for 1) eliminating insecure_channel usage; 

1988 2) enable unit testing for call credentials without setting up secrets. 

1989 

1990 Args: 

1991 local_connect_type: Local connection type (either 

1992 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 

1993 

1994 Returns: 

1995 A ChannelCredentials for use with a local Channel 

1996 """ 

1997 return ChannelCredentials( 

1998 _cygrpc.channel_credentials_local(local_connect_type.value) 

1999 ) 

2000 

2001 

2002def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 

2003 """Creates a local ServerCredentials used for local connections. 

2004 

2005 This is an EXPERIMENTAL API. 

2006 

2007 Local credentials are used by local TCP endpoints (e.g. localhost:10000) 

2008 also UDS connections. 

2009 

2010 The connections created by local server credentials are not 

2011 encrypted, but will be checked if they are local or not. 

2012 The UDS connections are considered secure by providing peer authentication 

2013 and data confidentiality while TCP connections are considered insecure. 

2014 

2015 It is allowed to transmit call credentials over connections created by local 

2016 server credentials. 

2017 

2018 Local server credentials are useful for 1) eliminating insecure_channel usage; 

2019 2) enable unit testing for call credentials without setting up secrets. 

2020 

2021 Args: 

2022 local_connect_type: Local connection type (either 

2023 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 

2024 

2025 Returns: 

2026 A ServerCredentials for use with a local Server 

2027 """ 

2028 return ServerCredentials( 

2029 _cygrpc.server_credentials_local(local_connect_type.value) 

2030 ) 

2031 

2032 

2033def alts_channel_credentials(service_accounts=None): 

2034 """Creates a ChannelCredentials for use with an ALTS-enabled Channel. 

2035 

2036 This is an EXPERIMENTAL API. 

2037 ALTS credentials API can only be used in GCP environment as it relies on 

2038 handshaker service being available. For more info about ALTS see 

2039 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security 

2040 

2041 Args: 

2042 service_accounts: A list of server identities accepted by the client. 

2043 If target service accounts are provided and none of them matches the 

2044 peer identity of the server, handshake will fail. The arg can be empty 

2045 if the client does not have any information about trusted server 

2046 identity. 

2047 

2048 Returns: 

2049 A ChannelCredentials for use with an ALTS-enabled Channel 

2050 """ 

2051 return ChannelCredentials( 

2052 _cygrpc.channel_credentials_alts(service_accounts or []) 

2053 ) 

2054 

2055 

2056def alts_server_credentials(): 

2057 """Creates a ServerCredentials for use with an ALTS-enabled connection. 

2058 

2059 This is an EXPERIMENTAL API. 

2060 ALTS credentials API can only be used in GCP environment as it relies on 

2061 handshaker service being available. For more info about ALTS see 

2062 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security 

2063 

2064 Returns: 

2065 A ServerCredentials for use with an ALTS-enabled Server 

2066 """ 

2067 return ServerCredentials(_cygrpc.server_credentials_alts()) 

2068 

2069 

2070def compute_engine_channel_credentials(call_credentials): 

2071 """Creates a compute engine channel credential. 

2072 

2073 This credential can only be used in a GCP environment as it relies on 

2074 a handshaker service. For more info about ALTS, see 

2075 https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security 

2076 

2077 This channel credential is expected to be used as part of a composite 

2078 credential in conjunction with a call credentials that authenticates the 

2079 VM's default service account. If used with any other sort of call 

2080 credential, the connection may suddenly and unexpectedly begin failing RPCs. 

2081 """ 

2082 return ChannelCredentials( 

2083 _cygrpc.channel_credentials_compute_engine( 

2084 call_credentials._credentials 

2085 ) 

2086 ) 

2087 

2088 

2089def channel_ready_future(channel): 

2090 """Creates a Future that tracks when a Channel is ready. 

2091 

2092 Cancelling the Future does not affect the channel's state machine. 

2093 It merely decouples the Future from channel state machine. 

2094 

2095 Args: 

2096 channel: A Channel object. 

2097 

2098 Returns: 

2099 A Future object that matures when the channel connectivity is 

2100 ChannelConnectivity.READY. 

2101 """ 

2102 from grpc import _utilities # pylint: disable=cyclic-import 

2103 

2104 return _utilities.channel_ready_future(channel) 

2105 

2106 

2107def insecure_channel(target, options=None, compression=None): 

2108 """Creates an insecure Channel to a server. 

2109 

2110 The returned Channel is thread-safe. 

2111 

2112 Args: 

2113 target: The server address 

2114 options: An optional list of key-value pairs (:term:`channel_arguments` 

2115 in gRPC Core runtime) to configure the channel. 

2116 compression: An optional value indicating the compression method to be 

2117 used over the lifetime of the channel. 

2118 

2119 Returns: 

2120 A Channel. 

2121 """ 

2122 from grpc import _channel # pylint: disable=cyclic-import 

2123 

2124 return _channel.Channel( 

2125 target, () if options is None else options, None, compression 

2126 ) 

2127 

2128 

2129def secure_channel(target, credentials, options=None, compression=None): 

2130 """Creates a secure Channel to a server. 

2131 

2132 The returned Channel is thread-safe. 

2133 

2134 Args: 

2135 target: The server address. 

2136 credentials: A ChannelCredentials instance. 

2137 options: An optional list of key-value pairs (:term:`channel_arguments` 

2138 in gRPC Core runtime) to configure the channel. 

2139 compression: An optional value indicating the compression method to be 

2140 used over the lifetime of the channel. 

2141 

2142 Returns: 

2143 A Channel. 

2144 """ 

2145 from grpc import _channel # pylint: disable=cyclic-import 

2146 from grpc.experimental import _insecure_channel_credentials 

2147 

2148 if credentials._credentials is _insecure_channel_credentials: 

2149 raise ValueError( 

2150 "secure_channel cannot be called with insecure credentials." 

2151 + " Call insecure_channel instead." 

2152 ) 

2153 return _channel.Channel( 

2154 target, 

2155 () if options is None else options, 

2156 credentials._credentials, 

2157 compression, 

2158 ) 

2159 

2160 

2161def intercept_channel(channel, *interceptors): 

2162 """Intercepts a channel through a set of interceptors. 

2163 

2164 Args: 

2165 channel: A Channel. 

2166 interceptors: Zero or more objects of type 

2167 UnaryUnaryClientInterceptor, 

2168 UnaryStreamClientInterceptor, 

2169 StreamUnaryClientInterceptor, or 

2170 StreamStreamClientInterceptor. 

2171 Interceptors are given control in the order they are listed. 

2172 

2173 Returns: 

2174 A Channel that intercepts each invocation via the provided interceptors. 

2175 

2176 Raises: 

2177 TypeError: If interceptor does not derive from any of 

2178 UnaryUnaryClientInterceptor, 

2179 UnaryStreamClientInterceptor, 

2180 StreamUnaryClientInterceptor, or 

2181 StreamStreamClientInterceptor. 

2182 """ 

2183 from grpc import _interceptor # pylint: disable=cyclic-import 

2184 

2185 return _interceptor.intercept_channel(channel, *interceptors) 

2186 

2187 

2188def server( 

2189 thread_pool, 

2190 handlers=None, 

2191 interceptors=None, 

2192 options=None, 

2193 maximum_concurrent_rpcs=None, 

2194 compression=None, 

2195 xds=False, 

2196): 

2197 """Creates a Server with which RPCs can be serviced. 

2198 

2199 Args: 

2200 thread_pool: A futures.ThreadPoolExecutor to be used by the Server 

2201 to execute RPC handlers. 

2202 handlers: An optional list of GenericRpcHandlers used for executing RPCs. 

2203 More handlers may be added by calling add_generic_rpc_handlers any time 

2204 before the server is started. 

2205 interceptors: An optional list of ServerInterceptor objects that observe 

2206 and optionally manipulate the incoming RPCs before handing them over to 

2207 handlers. The interceptors are given control in the order they are 

2208 specified. This is an EXPERIMENTAL API. 

2209 options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime) 

2210 to configure the channel. 

2211 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server 

2212 will service before returning RESOURCE_EXHAUSTED status, or None to 

2213 indicate no limit. 

2214 compression: An element of grpc.Compression, e.g. 

2215 grpc.Compression.Gzip. This compression algorithm will be used for the 

2216 lifetime of the server unless overridden. 

2217 xds: If set to true, retrieves server configuration via xDS. This is an 

2218 EXPERIMENTAL option. 

2219 

2220 Returns: 

2221 A Server object. 

2222 """ 

2223 from grpc import _server # pylint: disable=cyclic-import 

2224 

2225 return _server.create_server( 

2226 thread_pool, 

2227 () if handlers is None else handlers, 

2228 () if interceptors is None else interceptors, 

2229 () if options is None else options, 

2230 maximum_concurrent_rpcs, 

2231 compression, 

2232 xds, 

2233 ) 

2234 

2235 

2236@contextlib.contextmanager 

2237def _create_servicer_context(rpc_event, state, request_deserializer): 

2238 from grpc import _server # pylint: disable=cyclic-import 

2239 

2240 context = _server._Context(rpc_event, state, request_deserializer) 

2241 yield context 

2242 context._finalize_state() # pylint: disable=protected-access 

2243 

2244 

2245@enum.unique 

2246class Compression(enum.IntEnum): 

2247 """Indicates the compression method to be used for an RPC. 

2248 

2249 Attributes: 

2250 NoCompression: Do not use compression algorithm. 

2251 Deflate: Use "Deflate" compression algorithm. 

2252 Gzip: Use "Gzip" compression algorithm. 

2253 """ 

2254 

2255 NoCompression = _compression.NoCompression 

2256 Deflate = _compression.Deflate 

2257 Gzip = _compression.Gzip 

2258 

2259 

2260################################### __all__ ################################# 

2261 

2262__all__ = ( 

2263 "AuthMetadataContext", 

2264 "AuthMetadataPlugin", 

2265 "AuthMetadataPluginCallback", 

2266 "Call", 

2267 "CallCredentials", 

2268 "Channel", 

2269 "ChannelConnectivity", 

2270 "ChannelCredentials", 

2271 "ClientCallDetails", 

2272 "Compression", 

2273 "Future", 

2274 "FutureCancelledError", 

2275 "FutureTimeoutError", 

2276 "GenericRpcHandler", 

2277 "HandlerCallDetails", 

2278 "LocalConnectionType", 

2279 "RpcContext", 

2280 "RpcError", 

2281 "RpcMethodHandler", 

2282 "Server", 

2283 "ServerCertificateConfiguration", 

2284 "ServerCredentials", 

2285 "ServerInterceptor", 

2286 "ServiceRpcHandler", 

2287 "ServicerContext", 

2288 "Status", 

2289 "StatusCode", 

2290 "StreamStreamClientInterceptor", 

2291 "StreamStreamMultiCallable", 

2292 "StreamUnaryClientInterceptor", 

2293 "StreamUnaryMultiCallable", 

2294 "UnaryStreamClientInterceptor", 

2295 "UnaryStreamMultiCallable", 

2296 "UnaryUnaryClientInterceptor", 

2297 "UnaryUnaryMultiCallable", 

2298 "access_token_call_credentials", 

2299 "alts_channel_credentials", 

2300 "alts_server_credentials", 

2301 "channel_ready_future", 

2302 "composite_call_credentials", 

2303 "composite_channel_credentials", 

2304 "compute_engine_channel_credentials", 

2305 "dynamic_ssl_server_credentials", 

2306 "insecure_channel", 

2307 "insecure_server_credentials", 

2308 "intercept_channel", 

2309 "local_channel_credentials", 

2310 "local_server_credentials", 

2311 "metadata_call_credentials", 

2312 "method_handlers_generic_handler", 

2313 "protos", 

2314 "protos_and_services", 

2315 "secure_channel", 

2316 "server", 

2317 "services", 

2318 "ssl_channel_credentials", 

2319 "ssl_server_certificate_configuration", 

2320 "ssl_server_credentials", 

2321 "stream_stream_rpc_method_handler", 

2322 "stream_unary_rpc_method_handler", 

2323 "unary_stream_rpc_method_handler", 

2324 "unary_unary_rpc_method_handler", 

2325 "xds_channel_credentials", 

2326 "xds_server_credentials", 

2327) 

2328 

2329############################### Extension Shims ################################ 

2330 

2331# Here to maintain backwards compatibility; avoid using these in new code! 

2332try: 

2333 import grpc_tools 

2334 

2335 sys.modules.update({"grpc.tools": grpc_tools}) 

2336except ImportError: 

2337 pass 

2338try: 

2339 import grpc_health 

2340 

2341 sys.modules.update({"grpc.health": grpc_health}) 

2342except ImportError: 

2343 pass 

2344try: 

2345 import grpc_reflection 

2346 

2347 sys.modules.update({"grpc.reflection": grpc_reflection}) 

2348except ImportError: 

2349 pass 

2350 

2351# Prevents import order issue in the case of renamed path. 

2352if sys.version_info >= (3, 6) and __name__ == "grpc": 

2353 from grpc import aio # pylint: disable=ungrouped-imports 

2354 

2355 sys.modules.update({"grpc.aio": aio})