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

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

382 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 = (int(_cygrpc.StatusCode.ok), "ok") 

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

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

268 INVALID_ARGUMENT = ( 

269 int(_cygrpc.StatusCode.invalid_argument), 

270 "invalid argument", 

271 ) 

272 DEADLINE_EXCEEDED = ( 

273 int(_cygrpc.StatusCode.deadline_exceeded), 

274 "deadline exceeded", 

275 ) 

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

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

278 PERMISSION_DENIED = ( 

279 int(_cygrpc.StatusCode.permission_denied), 

280 "permission denied", 

281 ) 

282 RESOURCE_EXHAUSTED = ( 

283 int(_cygrpc.StatusCode.resource_exhausted), 

284 "resource exhausted", 

285 ) 

286 FAILED_PRECONDITION = ( 

287 int(_cygrpc.StatusCode.failed_precondition), 

288 "failed precondition", 

289 ) 

290 ABORTED = (int(_cygrpc.StatusCode.aborted), "aborted") 

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

292 UNIMPLEMENTED = (int(_cygrpc.StatusCode.unimplemented), "unimplemented") 

293 INTERNAL = (int(_cygrpc.StatusCode.internal), "internal") 

294 UNAVAILABLE = (int(_cygrpc.StatusCode.unavailable), "unavailable") 

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

296 UNAUTHENTICATED = ( 

297 int(_cygrpc.StatusCode.unauthenticated), 

298 "unauthenticated", 

299 ) 

300 

301 

302############################# gRPC Status ################################ 

303 

304 

305class Status(abc.ABC): 

306 """Describes the status of an RPC. 

307 

308 This is an EXPERIMENTAL API. 

309 

310 Attributes: 

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

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

313 termination of the RPC. 

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

315 """ 

316 

317 

318############################# gRPC Exceptions ################################ 

319 

320 

321class RpcError(Exception): 

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

323 

324 

325############################## Shared Context ################################ 

326 

327 

328class RpcContext(abc.ABC): 

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

330 

331 @abc.abstractmethod 

332 def is_active(self): 

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

334 

335 Returns: 

336 bool: 

337 True if RPC is active, False otherwise. 

338 """ 

339 raise NotImplementedError() 

340 

341 @abc.abstractmethod 

342 def time_remaining(self): 

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

344 

345 Returns: 

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

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

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

349 """ 

350 raise NotImplementedError() 

351 

352 @abc.abstractmethod 

353 def cancel(self): 

354 """Cancels the RPC. 

355 

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

357 """ 

358 raise NotImplementedError() 

359 

360 @abc.abstractmethod 

361 def add_callback(self, callback): 

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

363 

364 Args: 

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

366 

367 Returns: 

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

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

370 already terminated or some other reason). 

371 """ 

372 raise NotImplementedError() 

373 

374 

375######################### Invocation-Side Context ############################ 

376 

377 

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

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

380 

381 @abc.abstractmethod 

382 def initial_metadata(self): 

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

384 

385 This method blocks until the value is available. 

386 

387 Returns: 

388 The initial :term:`metadata`. 

389 """ 

390 raise NotImplementedError() 

391 

392 @abc.abstractmethod 

393 def trailing_metadata(self): 

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

395 

396 This method blocks until the value is available. 

397 

398 Returns: 

399 The trailing :term:`metadata`. 

400 """ 

401 raise NotImplementedError() 

402 

403 @abc.abstractmethod 

404 def code(self): 

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

406 

407 This method blocks until the value is available. 

408 

409 Returns: 

410 The StatusCode value for the RPC. 

411 """ 

412 raise NotImplementedError() 

413 

414 @abc.abstractmethod 

415 def details(self): 

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

417 

418 This method blocks until the value is available. 

419 

420 Returns: 

421 The details string of the RPC. 

422 """ 

423 raise NotImplementedError() 

424 

425 

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

427 

428 

429class ClientCallDetails(abc.ABC): 

430 """Describes an RPC to be invoked. 

431 

432 Attributes: 

433 method: The method name of the RPC. 

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

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

436 the service-side of the RPC. 

437 credentials: An optional CallCredentials for the RPC. 

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

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

440 grpc.Compression.Gzip. 

441 """ 

442 

443 

444class UnaryUnaryClientInterceptor(abc.ABC): 

445 """Affords intercepting unary-unary invocations.""" 

446 

447 @abc.abstractmethod 

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

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

450 

451 Args: 

452 continuation: A function that proceeds with the invocation by 

453 executing the next interceptor in chain or invoking the 

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

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

456 The interceptor can use 

457 `response_future = continuation(client_call_details, request)` 

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

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

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

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

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

463 will be an RpcError. 

464 client_call_details: A ClientCallDetails object describing the 

465 outgoing RPC. 

466 request: The request value for the RPC. 

467 

468 Returns: 

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

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

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

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

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

474 """ 

475 raise NotImplementedError() 

476 

477 

478class UnaryStreamClientInterceptor(abc.ABC): 

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

480 

481 @abc.abstractmethod 

482 def intercept_unary_stream( 

483 self, continuation, client_call_details, request 

484 ): 

485 """Intercepts a unary-stream invocation. 

486 

487 Args: 

488 continuation: A function that proceeds with the invocation by 

489 executing the next interceptor in chain or invoking the 

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

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

492 The interceptor can use 

493 `response_iterator = continuation(client_call_details, request)` 

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

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

496 Drawing response values from the returned Call-iterator may 

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

498 status. 

499 client_call_details: A ClientCallDetails object describing the 

500 outgoing RPC. 

501 request: The request value for the RPC. 

502 

503 Returns: 

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

505 response values. Drawing response values from the returned 

506 Call-iterator may raise RpcError indicating termination of 

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

508 Future interface, though it may not. 

509 """ 

510 raise NotImplementedError() 

511 

512 

513class StreamUnaryClientInterceptor(abc.ABC): 

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

515 

516 @abc.abstractmethod 

517 def intercept_stream_unary( 

518 self, continuation, client_call_details, request_iterator 

519 ): 

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

521 

522 Args: 

523 continuation: A function that proceeds with the invocation by 

524 executing the next interceptor in chain or invoking the 

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

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

527 The interceptor can use 

528 `response_future = continuation(client_call_details, request_iterator)` 

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

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

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

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

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

534 client_call_details: A ClientCallDetails object describing the 

535 outgoing RPC. 

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

537 

538 Returns: 

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

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

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

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

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

544 """ 

545 raise NotImplementedError() 

546 

547 

548class StreamStreamClientInterceptor(abc.ABC): 

549 """Affords intercepting stream-stream invocations.""" 

550 

551 @abc.abstractmethod 

552 def intercept_stream_stream( 

553 self, continuation, client_call_details, request_iterator 

554 ): 

555 """Intercepts a stream-stream invocation. 

556 

557 Args: 

558 continuation: A function that proceeds with the invocation by 

559 executing the next interceptor in chain or invoking the 

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

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

562 The interceptor can use 

563 `response_iterator = continuation(client_call_details, request_iterator)` 

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

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

566 Drawing response values from the returned Call-iterator may 

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

568 status. 

569 client_call_details: A ClientCallDetails object describing the 

570 outgoing RPC. 

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

572 

573 Returns: 

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

575 response values. Drawing response values from the returned 

576 Call-iterator may raise RpcError indicating termination of 

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

578 Future interface, though it may not. 

579 """ 

580 raise NotImplementedError() 

581 

582 

583############ Authentication & Authorization Interfaces & Classes ############# 

584 

585 

586class ChannelCredentials: 

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

588 

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

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

591 example, ssl_channel_credentials returns an instance of this class and 

592 secure_channel requires an instance of this class. 

593 """ 

594 

595 def __init__(self, credentials): 

596 self._credentials = credentials 

597 

598 

599class CallCredentials: 

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

601 

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

603 metadata will not be transmitted to the server. 

604 

605 A CallCredentials may be composed with ChannelCredentials to always assert 

606 identity for every call over that Channel. 

607 

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

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

610 """ 

611 

612 def __init__(self, credentials): 

613 self._credentials = credentials 

614 

615 

616class AuthMetadataContext(abc.ABC): 

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

618 

619 Attributes: 

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

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

622 """ 

623 

624 

625class AuthMetadataPluginCallback(abc.ABC): 

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

627 

628 def __call__(self, metadata, error): 

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

630 

631 Args: 

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

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

634 """ 

635 raise NotImplementedError() 

636 

637 

638class AuthMetadataPlugin(abc.ABC): 

639 """A specification for custom authentication.""" 

640 

641 def __call__(self, context, callback): 

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

643 

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

645 

646 Args: 

647 context: An AuthMetadataContext providing information on the RPC that 

648 the plugin is being called to authenticate. 

649 callback: An AuthMetadataPluginCallback to be invoked either 

650 synchronously or asynchronously. 

651 """ 

652 raise NotImplementedError() 

653 

654 

655class ServerCredentials: 

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

657 

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

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

660 """ 

661 

662 def __init__(self, credentials): 

663 self._credentials = credentials 

664 

665 

666class ServerCertificateConfiguration: 

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

668 

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

670 fetching callback. 

671 

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

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

674 other functions. 

675 """ 

676 

677 def __init__(self, certificate_configuration): 

678 self._certificate_configuration = certificate_configuration 

679 

680 

681######################## Multi-Callable Interfaces ########################### 

682 

683 

684class UnaryUnaryMultiCallable(abc.ABC): 

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

686 

687 @abc.abstractmethod 

688 def __call__( 

689 self, 

690 request, 

691 timeout=None, 

692 metadata=None, 

693 credentials=None, 

694 wait_for_ready=None, 

695 compression=None, 

696 ): 

697 """Synchronously invokes the underlying RPC. 

698 

699 Args: 

700 request: The request value for the RPC. 

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

702 for the RPC. 

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

704 service-side of the RPC. 

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

706 secure Channel. 

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

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

709 grpc.Compression.Gzip. 

710 

711 Returns: 

712 The response value for the RPC. 

713 

714 Raises: 

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

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

717 metadata, status code, and details. 

718 """ 

719 raise NotImplementedError() 

720 

721 @abc.abstractmethod 

722 def with_call( 

723 self, 

724 request, 

725 timeout=None, 

726 metadata=None, 

727 credentials=None, 

728 wait_for_ready=None, 

729 compression=None, 

730 ): 

731 """Synchronously invokes the underlying RPC. 

732 

733 Args: 

734 request: The request value for the RPC. 

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

736 the RPC. 

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

738 service-side of the RPC. 

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

740 secure Channel. 

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

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

743 grpc.Compression.Gzip. 

744 

745 Returns: 

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

747 

748 Raises: 

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

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

751 metadata, status code, and details. 

752 """ 

753 raise NotImplementedError() 

754 

755 @abc.abstractmethod 

756 def future( 

757 self, 

758 request, 

759 timeout=None, 

760 metadata=None, 

761 credentials=None, 

762 wait_for_ready=None, 

763 compression=None, 

764 ): 

765 """Asynchronously invokes the underlying RPC. 

766 

767 Args: 

768 request: The request value for the RPC. 

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

770 the RPC. 

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

772 service-side of the RPC. 

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

774 secure Channel. 

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

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

777 grpc.Compression.Gzip. 

778 

779 Returns: 

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

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

782 value will be the response message of the RPC. 

783 Should the event terminate with non-OK status, 

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

785 """ 

786 raise NotImplementedError() 

787 

788 

789class UnaryStreamMultiCallable(abc.ABC): 

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

791 

792 @abc.abstractmethod 

793 def __call__( 

794 self, 

795 request, 

796 timeout=None, 

797 metadata=None, 

798 credentials=None, 

799 wait_for_ready=None, 

800 compression=None, 

801 ): 

802 """Invokes the underlying RPC. 

803 

804 Args: 

805 request: The request value for the RPC. 

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

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

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

809 service-side of the RPC. 

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

811 secure Channel. 

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

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

814 grpc.Compression.Gzip. 

815 

816 Returns: 

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

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

819 returned Call-iterator may raise RpcError indicating termination of 

820 the RPC with non-OK status. 

821 """ 

822 raise NotImplementedError() 

823 

824 

825class StreamUnaryMultiCallable(abc.ABC): 

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

827 

828 @abc.abstractmethod 

829 def __call__( 

830 self, 

831 request_iterator, 

832 timeout=None, 

833 metadata=None, 

834 credentials=None, 

835 wait_for_ready=None, 

836 compression=None, 

837 ): 

838 """Synchronously invokes the underlying RPC. 

839 

840 Args: 

841 request_iterator: An iterator that yields request values for 

842 the RPC. 

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

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

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

846 service-side of the RPC. 

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

848 secure Channel. 

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

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

851 grpc.Compression.Gzip. 

852 

853 Returns: 

854 The response value for the RPC. 

855 

856 Raises: 

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

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

859 such as metadata, code, and details. 

860 """ 

861 raise NotImplementedError() 

862 

863 @abc.abstractmethod 

864 def with_call( 

865 self, 

866 request_iterator, 

867 timeout=None, 

868 metadata=None, 

869 credentials=None, 

870 wait_for_ready=None, 

871 compression=None, 

872 ): 

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

874 

875 Args: 

876 request_iterator: An iterator that yields request values for 

877 the RPC. 

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

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

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

881 service-side of the RPC. 

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

883 secure Channel. 

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

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

886 grpc.Compression.Gzip. 

887 

888 Returns: 

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

890 

891 Raises: 

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

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

894 metadata, status code, and details. 

895 """ 

896 raise NotImplementedError() 

897 

898 @abc.abstractmethod 

899 def future( 

900 self, 

901 request_iterator, 

902 timeout=None, 

903 metadata=None, 

904 credentials=None, 

905 wait_for_ready=None, 

906 compression=None, 

907 ): 

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

909 

910 Args: 

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

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

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

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

915 service-side of the RPC. 

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

917 secure Channel. 

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

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

920 grpc.Compression.Gzip. 

921 

922 Returns: 

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

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

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

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

927 be an RpcError. 

928 """ 

929 raise NotImplementedError() 

930 

931 

932class StreamStreamMultiCallable(abc.ABC): 

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

934 

935 @abc.abstractmethod 

936 def __call__( 

937 self, 

938 request_iterator, 

939 timeout=None, 

940 metadata=None, 

941 credentials=None, 

942 wait_for_ready=None, 

943 compression=None, 

944 ): 

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

946 

947 Args: 

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

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

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

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

952 service-side of the RPC. 

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

954 secure Channel. 

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

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

957 grpc.Compression.Gzip. 

958 

959 Returns: 

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

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

962 returned Call-iterator may raise RpcError indicating termination of 

963 the RPC with non-OK status. 

964 """ 

965 raise NotImplementedError() 

966 

967 

968############################# Channel Interface ############################## 

969 

970 

971class Channel(abc.ABC): 

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

973 

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

975 support being entered and exited multiple times. 

976 """ 

977 

978 @abc.abstractmethod 

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

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

981 

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

983 This method allows application to monitor the state transitions. 

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

985 runtime's state. 

986 

987 Args: 

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

989 ChannelConnectivity describes current state of the channel. 

990 The callable will be invoked immediately upon subscription 

991 and again for every change to ChannelConnectivity until it 

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

993 try_to_connect: A boolean indicating whether or not this Channel 

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

995 runtime decides when to connect. 

996 """ 

997 raise NotImplementedError() 

998 

999 @abc.abstractmethod 

1000 def unsubscribe(self, callback): 

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

1002 

1003 Args: 

1004 callback: A callable previously registered with this Channel from 

1005 having been passed to its "subscribe" method. 

1006 """ 

1007 raise NotImplementedError() 

1008 

1009 @abc.abstractmethod 

1010 def unary_unary( 

1011 self, 

1012 method, 

1013 request_serializer=None, 

1014 response_deserializer=None, 

1015 _registered_method=False, 

1016 ): 

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

1018 

1019 Args: 

1020 method: The name of the RPC method. 

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

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

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

1024 response message. Response goes undeserialized in case None 

1025 is passed. 

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

1027 is registered. 

1028 

1029 Returns: 

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

1031 """ 

1032 raise NotImplementedError() 

1033 

1034 @abc.abstractmethod 

1035 def unary_stream( 

1036 self, 

1037 method, 

1038 request_serializer=None, 

1039 response_deserializer=None, 

1040 _registered_method=False, 

1041 ): 

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

1043 

1044 Args: 

1045 method: The name of the RPC method. 

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

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

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

1049 response message. Response goes undeserialized in case None is 

1050 passed. 

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

1052 is registered. 

1053 

1054 Returns: 

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

1056 """ 

1057 raise NotImplementedError() 

1058 

1059 @abc.abstractmethod 

1060 def stream_unary( 

1061 self, 

1062 method, 

1063 request_serializer=None, 

1064 response_deserializer=None, 

1065 _registered_method=False, 

1066 ): 

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

1068 

1069 Args: 

1070 method: The name of the RPC method. 

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

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

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

1074 response message. Response goes undeserialized in case None is 

1075 passed. 

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

1077 is registered. 

1078 

1079 Returns: 

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

1081 """ 

1082 raise NotImplementedError() 

1083 

1084 @abc.abstractmethod 

1085 def stream_stream( 

1086 self, 

1087 method, 

1088 request_serializer=None, 

1089 response_deserializer=None, 

1090 _registered_method=False, 

1091 ): 

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

1093 

1094 Args: 

1095 method: The name of the RPC method. 

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

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

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

1099 response message. Response goes undeserialized in case None 

1100 is passed. 

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

1102 is registered. 

1103 

1104 Returns: 

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

1106 """ 

1107 raise NotImplementedError() 

1108 

1109 @abc.abstractmethod 

1110 def close(self): 

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

1112 

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

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

1115 

1116 This method is idempotent. 

1117 """ 

1118 raise NotImplementedError() 

1119 

1120 def __enter__(self): 

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

1122 raise NotImplementedError() 

1123 

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

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

1126 raise NotImplementedError() 

1127 

1128 

1129########################## Service-Side Context ############################## 

1130 

1131 

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

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

1134 

1135 @abc.abstractmethod 

1136 def invocation_metadata(self): 

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

1138 

1139 Returns: 

1140 The invocation :term:`metadata`. 

1141 """ 

1142 raise NotImplementedError() 

1143 

1144 @abc.abstractmethod 

1145 def peer(self): 

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

1147 

1148 Returns: 

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

1150 The string format is determined by gRPC runtime. 

1151 """ 

1152 raise NotImplementedError() 

1153 

1154 @abc.abstractmethod 

1155 def peer_identities(self): 

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

1157 

1158 Equivalent to 

1159 servicer_context.auth_context().get(servicer_context.peer_identity_key()) 

1160 

1161 Returns: 

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

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

1164 """ 

1165 raise NotImplementedError() 

1166 

1167 @abc.abstractmethod 

1168 def peer_identity_key(self): 

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

1170 

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

1172 used to identify an SSL peer. 

1173 

1174 Returns: 

1175 The auth property (string) that indicates the 

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

1177 """ 

1178 raise NotImplementedError() 

1179 

1180 @abc.abstractmethod 

1181 def auth_context(self): 

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

1183 

1184 Returns: 

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

1186 """ 

1187 raise NotImplementedError() 

1188 

1189 def set_compression(self, compression): 

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

1191 

1192 Args: 

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

1194 grpc.Compression.Gzip. 

1195 """ 

1196 raise NotImplementedError() 

1197 

1198 @abc.abstractmethod 

1199 def send_initial_metadata(self, initial_metadata): 

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

1201 

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

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

1204 

1205 Args: 

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

1207 """ 

1208 raise NotImplementedError() 

1209 

1210 @abc.abstractmethod 

1211 def set_trailing_metadata(self, trailing_metadata): 

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

1213 

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

1215 

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

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

1218 over the wire. 

1219 

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

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

1222 

1223 Args: 

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

1225 """ 

1226 raise NotImplementedError() 

1227 

1228 def trailing_metadata(self): 

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

1230 

1231 This is an EXPERIMENTAL API. 

1232 

1233 Returns: 

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

1235 """ 

1236 raise NotImplementedError() 

1237 

1238 @abc.abstractmethod 

1239 def abort(self, code, details): 

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

1241 

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

1243 ones. 

1244 

1245 Args: 

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

1247 It must not be StatusCode.OK. 

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

1249 termination of the RPC. 

1250 

1251 Raises: 

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

1253 RPC to the gRPC runtime. 

1254 """ 

1255 raise NotImplementedError() 

1256 

1257 @abc.abstractmethod 

1258 def abort_with_status(self, status): 

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

1260 

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

1262 status message and trailing metadata. 

1263 

1264 This is an EXPERIMENTAL API. 

1265 

1266 Args: 

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

1268 StatusCode.OK. 

1269 

1270 Raises: 

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

1272 RPC to the gRPC runtime. 

1273 """ 

1274 raise NotImplementedError() 

1275 

1276 @abc.abstractmethod 

1277 def set_code(self, code): 

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

1279 

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

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

1282 

1283 Args: 

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

1285 """ 

1286 raise NotImplementedError() 

1287 

1288 @abc.abstractmethod 

1289 def set_details(self, details): 

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

1291 

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

1293 no details to transmit. 

1294 

1295 Args: 

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

1297 termination of the RPC. 

1298 """ 

1299 raise NotImplementedError() 

1300 

1301 def code(self): 

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

1303 

1304 This is an EXPERIMENTAL API. 

1305 

1306 Returns: 

1307 The StatusCode value for the RPC. 

1308 """ 

1309 raise NotImplementedError() 

1310 

1311 def details(self): 

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

1313 

1314 This is an EXPERIMENTAL API. 

1315 

1316 Returns: 

1317 The details string of the RPC. 

1318 """ 

1319 raise NotImplementedError() 

1320 

1321 def disable_next_message_compression(self): 

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

1323 

1324 This method will override any compression configuration set during 

1325 server creation or set on the call. 

1326 """ 

1327 raise NotImplementedError() 

1328 

1329 

1330##################### Service-Side Handler Interfaces ######################## 

1331 

1332 

1333class RpcMethodHandler(abc.ABC): 

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

1335 

1336 Attributes: 

1337 request_streaming: Whether the RPC supports exactly one request message 

1338 or any arbitrary number of request messages. 

1339 response_streaming: Whether the RPC supports exactly one response message 

1340 or any arbitrary number of response messages. 

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

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

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

1344 passed the raw request bytes. 

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

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

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

1348 should be transmitted on the wire as they are. 

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

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

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

1352 and response_streaming are False. 

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

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

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

1356 request_streaming is False and response_streaming is True. 

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

1360 request_streaming is True and response_streaming is False. 

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

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

1363 ServicerContext object and returns an iterator of response values. 

1364 Only non-None if request_streaming and response_streaming are both 

1365 True. 

1366 """ 

1367 

1368 

1369@typing.runtime_checkable 

1370class HandlerCallDetails(Protocol): 

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

1372 

1373 Attributes: 

1374 method: The method name of the RPC. 

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

1376 """ 

1377 

1378 method: str 

1379 invocation_metadata: Any 

1380 

1381 

1382class GenericRpcHandler(abc.ABC): 

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

1384 

1385 @abc.abstractmethod 

1386 def service(self, handler_call_details): 

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

1388 

1389 Args: 

1390 handler_call_details: A HandlerCallDetails describing the RPC. 

1391 

1392 Returns: 

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

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

1395 """ 

1396 raise NotImplementedError() 

1397 

1398 

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

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

1401 

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

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

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

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

1406 service name. 

1407 """ 

1408 

1409 @abc.abstractmethod 

1410 def service_name(self): 

1411 """Returns this service's name. 

1412 

1413 Returns: 

1414 The service name. 

1415 """ 

1416 raise NotImplementedError() 

1417 

1418 

1419#################### Service-Side Interceptor Interfaces ##################### 

1420 

1421 

1422class ServerInterceptor(abc.ABC): 

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

1424 

1425 @abc.abstractmethod 

1426 def intercept_service(self, continuation, handler_call_details): 

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

1428 

1429 State can be passed from an interceptor to downstream interceptors 

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

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

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

1433 guarantees that interceptors and handlers will be called from the 

1434 same thread. 

1435 

1436 Args: 

1437 continuation: A function that takes a HandlerCallDetails and 

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

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

1440 as an argument, and returns an RpcMethodHandler instance if 

1441 the RPC is considered serviced, or None otherwise. 

1442 handler_call_details: A HandlerCallDetails describing the RPC. 

1443 

1444 Returns: 

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

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

1447 """ 

1448 raise NotImplementedError() 

1449 

1450 

1451############################# Server Interface ############################### 

1452 

1453 

1454class Server(abc.ABC): 

1455 """Services RPCs.""" 

1456 

1457 @abc.abstractmethod 

1458 def add_generic_rpc_handlers(self, generic_rpc_handlers): 

1459 """Registers GenericRpcHandlers with this Server. 

1460 

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

1462 

1463 Args: 

1464 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be 

1465 used to service RPCs. 

1466 """ 

1467 raise NotImplementedError() 

1468 

1469 def add_registered_method_handlers( # noqa: B027 

1470 self, service_name, method_handlers 

1471 ): 

1472 """Registers GenericRpcHandlers with this Server. 

1473 

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

1475 

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

1477 registered handler will take precedence. 

1478 

1479 Args: 

1480 service_name: The service name. 

1481 method_handlers: A dictionary that maps method names to corresponding 

1482 RpcMethodHandler. 

1483 """ 

1484 

1485 @abc.abstractmethod 

1486 def add_insecure_port(self, address): 

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

1488 

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

1490 

1491 Args: 

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

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

1494 

1495 Returns: 

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

1497 """ 

1498 raise NotImplementedError() 

1499 

1500 @abc.abstractmethod 

1501 def add_secure_port(self, address, server_credentials): 

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

1503 

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

1505 

1506 Args: 

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

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

1509 runtime will choose a port. 

1510 server_credentials: A ServerCredentials object. 

1511 

1512 Returns: 

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

1514 """ 

1515 raise NotImplementedError() 

1516 

1517 @abc.abstractmethod 

1518 def start(self): 

1519 """Starts this Server. 

1520 

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

1522 """ 

1523 raise NotImplementedError() 

1524 

1525 @abc.abstractmethod 

1526 def stop(self, grace): 

1527 """Stops this Server. 

1528 

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

1530 

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

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

1533 been terminated within the grace period are aborted. 

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

1535 all existing RPCs are aborted immediately and this method 

1536 blocks until the last RPC handler terminates. 

1537 

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

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

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

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

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

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

1544 grace value is used). 

1545 

1546 Args: 

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

1548 

1549 Returns: 

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

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

1552 all handlers have terminated. 

1553 """ 

1554 raise NotImplementedError() 

1555 

1556 def wait_for_termination(self, timeout=None): 

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

1558 

1559 This is an EXPERIMENTAL API. 

1560 

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

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

1563 

1564 1) The server is stopped or terminated; 

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

1566 

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

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

1569 

1570 Args: 

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

1572 operation in seconds. 

1573 

1574 Returns: 

1575 A bool indicates if the operation times out. 

1576 """ 

1577 raise NotImplementedError() 

1578 

1579 

1580################################# Functions ################################ 

1581 

1582 

1583def unary_unary_rpc_method_handler( 

1584 behavior, request_deserializer=None, response_serializer=None 

1585): 

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

1587 

1588 Args: 

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

1590 and returns one response. 

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 False, 

1602 request_deserializer, 

1603 response_serializer, 

1604 behavior, 

1605 None, 

1606 None, 

1607 None, 

1608 ) 

1609 

1610 

1611def unary_stream_rpc_method_handler( 

1612 behavior, request_deserializer=None, response_serializer=None 

1613): 

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

1615 

1616 Args: 

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

1618 and returns an iterator of response values. 

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 False, 

1629 True, 

1630 request_deserializer, 

1631 response_serializer, 

1632 None, 

1633 behavior, 

1634 None, 

1635 None, 

1636 ) 

1637 

1638 

1639def stream_unary_rpc_method_handler( 

1640 behavior, request_deserializer=None, response_serializer=None 

1641): 

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

1643 

1644 Args: 

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

1646 request values and returns a single response value. 

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 False, 

1658 request_deserializer, 

1659 response_serializer, 

1660 None, 

1661 None, 

1662 behavior, 

1663 None, 

1664 ) 

1665 

1666 

1667def stream_stream_rpc_method_handler( 

1668 behavior, request_deserializer=None, response_serializer=None 

1669): 

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

1671 

1672 Args: 

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

1674 request values and returns an iterator of response values. 

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

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

1677 

1678 Returns: 

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

1680 """ 

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

1682 

1683 return _utilities.RpcMethodHandler( 

1684 True, 

1685 True, 

1686 request_deserializer, 

1687 response_serializer, 

1688 None, 

1689 None, 

1690 None, 

1691 behavior, 

1692 ) 

1693 

1694 

1695def method_handlers_generic_handler(service, method_handlers): 

1696 """Creates a GenericRpcHandler from RpcMethodHandlers. 

1697 

1698 Args: 

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

1700 method_handlers. 

1701 method_handlers: A dictionary that maps method names to corresponding 

1702 RpcMethodHandler. 

1703 

1704 Returns: 

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

1706 with add_generic_rpc_handlers() before starting the server. 

1707 """ 

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

1709 

1710 return _utilities.DictionaryGenericHandler(service, method_handlers) 

1711 

1712 

1713def ssl_channel_credentials( 

1714 root_certificates=None, private_key=None, certificate_chain=None 

1715): 

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

1717 

1718 Args: 

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

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

1721 runtime. 

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

1723 private key should be used. 

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

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

1726 

1727 Returns: 

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

1729 """ 

1730 return ChannelCredentials( 

1731 _cygrpc.SSLChannelCredentials( 

1732 root_certificates, private_key, certificate_chain 

1733 ) 

1734 ) 

1735 

1736 

1737def xds_channel_credentials(fallback_credentials=None): 

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

1739 API. 

1740 

1741 Args: 

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

1743 establish a secure connection via xDS. If no fallback_credentials 

1744 argument is supplied, a default SSLChannelCredentials is used. 

1745 """ 

1746 fallback_credentials = ( 

1747 ssl_channel_credentials() 

1748 if fallback_credentials is None 

1749 else fallback_credentials 

1750 ) 

1751 return ChannelCredentials( 

1752 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials) 

1753 ) 

1754 

1755 

1756def metadata_call_credentials(metadata_plugin, name=None): 

1757 """Construct CallCredentials from an AuthMetadataPlugin. 

1758 

1759 Args: 

1760 metadata_plugin: An AuthMetadataPlugin to use for authentication. 

1761 name: An optional name for the plugin. 

1762 

1763 Returns: 

1764 A CallCredentials. 

1765 """ 

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

1767 

1768 return _plugin_wrapping.metadata_plugin_call_credentials( 

1769 metadata_plugin, name 

1770 ) 

1771 

1772 

1773def access_token_call_credentials(access_token): 

1774 """Construct CallCredentials from an access token. 

1775 

1776 Args: 

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

1778 authorization header, for example 

1779 "authorization: Bearer <access_token>". 

1780 

1781 Returns: 

1782 A CallCredentials. 

1783 """ 

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

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

1786 

1787 return _plugin_wrapping.metadata_plugin_call_credentials( 

1788 _auth.AccessTokenAuthMetadataPlugin(access_token), None 

1789 ) 

1790 

1791 

1792def composite_call_credentials(*call_credentials): 

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

1794 

1795 Args: 

1796 *call_credentials: At least two CallCredentials objects. 

1797 

1798 Returns: 

1799 A CallCredentials object composed of the given CallCredentials objects. 

1800 """ 

1801 return CallCredentials( 

1802 _cygrpc.CompositeCallCredentials( 

1803 tuple( 

1804 single_call_credentials._credentials 

1805 for single_call_credentials in call_credentials 

1806 ) 

1807 ) 

1808 ) 

1809 

1810 

1811def composite_channel_credentials(channel_credentials, *call_credentials): 

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

1813 

1814 Args: 

1815 channel_credentials: A ChannelCredentials object. 

1816 *call_credentials: One or more CallCredentials objects. 

1817 

1818 Returns: 

1819 A ChannelCredentials composed of the given ChannelCredentials and 

1820 CallCredentials objects. 

1821 """ 

1822 return ChannelCredentials( 

1823 _cygrpc.CompositeChannelCredentials( 

1824 tuple( 

1825 single_call_credentials._credentials 

1826 for single_call_credentials in call_credentials 

1827 ), 

1828 channel_credentials._credentials, 

1829 ) 

1830 ) 

1831 

1832 

1833def ssl_server_credentials( 

1834 private_key_certificate_chain_pairs, 

1835 root_certificates=None, 

1836 require_client_auth=False, 

1837): 

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

1839 

1840 Args: 

1841 private_key_certificate_chain_pairs: A list of pairs of the form 

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

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

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

1845 If omitted, require_client_auth must also be False. 

1846 require_client_auth: A boolean indicating whether or not to require 

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

1848 is not None. 

1849 

1850 Returns: 

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

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

1853 """ 

1854 if not private_key_certificate_chain_pairs: 

1855 error_msg = ( 

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

1857 ) 

1858 raise ValueError(error_msg) 

1859 if require_client_auth and root_certificates is None: 

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

1861 raise ValueError(error_msg) 

1862 return ServerCredentials( 

1863 _cygrpc.server_credentials_ssl( 

1864 root_certificates, 

1865 [ 

1866 _cygrpc.SslPemKeyCertPair(key, pem) 

1867 for key, pem in private_key_certificate_chain_pairs 

1868 ], 

1869 require_client_auth, 

1870 ) 

1871 ) 

1872 

1873 

1874def xds_server_credentials(fallback_credentials): 

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

1876 API. 

1877 

1878 Args: 

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

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

1881 """ 

1882 return ServerCredentials( 

1883 _cygrpc.xds_server_credentials(fallback_credentials._credentials) 

1884 ) 

1885 

1886 

1887def insecure_server_credentials(): 

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

1889 This is an EXPERIMENTAL API. 

1890 

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

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

1893 with xds_server_credentials. 

1894 """ 

1895 return ServerCredentials(_cygrpc.insecure_server_credentials()) 

1896 

1897 

1898def ssl_server_certificate_configuration( 

1899 private_key_certificate_chain_pairs, root_certificates=None 

1900): 

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

1902 

1903 Args: 

1904 private_key_certificate_chain_pairs: A collection of pairs of 

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

1906 chain]. 

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

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

1909 

1910 Returns: 

1911 A ServerCertificateConfiguration that can be returned in the certificate 

1912 configuration fetching callback. 

1913 """ 

1914 if private_key_certificate_chain_pairs: 

1915 return ServerCertificateConfiguration( 

1916 _cygrpc.server_certificate_config_ssl( 

1917 root_certificates, 

1918 [ 

1919 _cygrpc.SslPemKeyCertPair(key, pem) 

1920 for key, pem in private_key_certificate_chain_pairs 

1921 ], 

1922 ) 

1923 ) 

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

1925 raise ValueError(error_msg) 

1926 

1927 

1928def dynamic_ssl_server_credentials( 

1929 initial_certificate_configuration, 

1930 certificate_configuration_fetcher, 

1931 require_client_authentication=False, 

1932): 

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

1934 

1935 Args: 

1936 initial_certificate_configuration (ServerCertificateConfiguration): The 

1937 certificate configuration with which the server will be initialized. 

1938 certificate_configuration_fetcher (callable): A callable that takes no 

1939 arguments and should return a ServerCertificateConfiguration to 

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

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

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

1943 client connection before starting the TLS handshake with the 

1944 client, thus allowing the user application to optionally 

1945 return a new ServerCertificateConfiguration that the server will then 

1946 use for the handshake. 

1947 require_client_authentication: A boolean indicating whether or not to 

1948 require clients to be authenticated. 

1949 

1950 Returns: 

1951 A ServerCredentials. 

1952 """ 

1953 return ServerCredentials( 

1954 _cygrpc.server_credentials_ssl_dynamic_cert_config( 

1955 initial_certificate_configuration, 

1956 certificate_configuration_fetcher, 

1957 require_client_authentication, 

1958 ) 

1959 ) 

1960 

1961 

1962@enum.unique 

1963class LocalConnectionType(enum.Enum): 

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

1965 

1966 Attributes: 

1967 UDS: Unix domain socket connections 

1968 LOCAL_TCP: Local TCP connections. 

1969 """ 

1970 

1971 UDS = _cygrpc.LocalConnectionType.uds 

1972 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp 

1973 

1974 

1975def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 

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

1977 

1978 This is an EXPERIMENTAL API. 

1979 

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

1981 also UDS connections. 

1982 

1983 The connections created by local channel credentials are not 

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

1985 The UDS connections are considered secure by providing peer authentication 

1986 and data confidentiality while TCP connections are considered insecure. 

1987 

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

1989 local channel credentials. 

1990 

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

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

1993 

1994 Args: 

1995 local_connect_type: Local connection type (either 

1996 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 

1997 

1998 Returns: 

1999 A ChannelCredentials for use with a local Channel 

2000 """ 

2001 return ChannelCredentials( 

2002 _cygrpc.channel_credentials_local(local_connect_type.value) 

2003 ) 

2004 

2005 

2006def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 

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

2008 

2009 This is an EXPERIMENTAL API. 

2010 

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

2012 also UDS connections. 

2013 

2014 The connections created by local server credentials are not 

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

2016 The UDS connections are considered secure by providing peer authentication 

2017 and data confidentiality while TCP connections are considered insecure. 

2018 

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

2020 server credentials. 

2021 

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

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

2024 

2025 Args: 

2026 local_connect_type: Local connection type (either 

2027 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 

2028 

2029 Returns: 

2030 A ServerCredentials for use with a local Server 

2031 """ 

2032 return ServerCredentials( 

2033 _cygrpc.server_credentials_local(local_connect_type.value) 

2034 ) 

2035 

2036 

2037def alts_channel_credentials(service_accounts=None): 

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

2039 

2040 This is an EXPERIMENTAL API. 

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

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

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

2044 

2045 Args: 

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

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

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

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

2050 identity. 

2051 

2052 Returns: 

2053 A ChannelCredentials for use with an ALTS-enabled Channel 

2054 """ 

2055 return ChannelCredentials( 

2056 _cygrpc.channel_credentials_alts(service_accounts or []) 

2057 ) 

2058 

2059 

2060def alts_server_credentials(): 

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

2062 

2063 This is an EXPERIMENTAL API. 

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

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

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

2067 

2068 Returns: 

2069 A ServerCredentials for use with an ALTS-enabled Server 

2070 """ 

2071 return ServerCredentials(_cygrpc.server_credentials_alts()) 

2072 

2073 

2074def compute_engine_channel_credentials(call_credentials): 

2075 """Creates a compute engine channel credential. 

2076 

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

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

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

2080 

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

2082 credential in conjunction with a call credentials that authenticates the 

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

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

2085 """ 

2086 return ChannelCredentials( 

2087 _cygrpc.channel_credentials_compute_engine( 

2088 call_credentials._credentials 

2089 ) 

2090 ) 

2091 

2092 

2093def channel_ready_future(channel): 

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

2095 

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

2097 It merely decouples the Future from channel state machine. 

2098 

2099 Args: 

2100 channel: A Channel object. 

2101 

2102 Returns: 

2103 A Future object that matures when the channel connectivity is 

2104 ChannelConnectivity.READY. 

2105 """ 

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

2107 

2108 return _utilities.channel_ready_future(channel) 

2109 

2110 

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

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

2113 

2114 The returned Channel is thread-safe. 

2115 

2116 Args: 

2117 target: The server address 

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

2119 in gRPC Core runtime) to configure the channel. 

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

2121 used over the lifetime of the channel. 

2122 

2123 Returns: 

2124 A Channel. 

2125 """ 

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

2127 

2128 return _channel.Channel( 

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

2130 ) 

2131 

2132 

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

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

2135 

2136 The returned Channel is thread-safe. 

2137 

2138 Args: 

2139 target: The server address. 

2140 credentials: A ChannelCredentials instance. 

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

2142 in gRPC Core runtime) to configure the channel. 

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

2144 used over the lifetime of the channel. 

2145 

2146 Returns: 

2147 A Channel. 

2148 """ 

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

2150 from grpc.experimental import _insecure_channel_credentials 

2151 

2152 if credentials._credentials is _insecure_channel_credentials: 

2153 raise ValueError( 

2154 "secure_channel cannot be called with insecure credentials." 

2155 + " Call insecure_channel instead." 

2156 ) 

2157 return _channel.Channel( 

2158 target, 

2159 () if options is None else options, 

2160 credentials._credentials, 

2161 compression, 

2162 ) 

2163 

2164 

2165def intercept_channel(channel, *interceptors): 

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

2167 

2168 Args: 

2169 channel: A Channel. 

2170 interceptors: Zero or more objects of type 

2171 UnaryUnaryClientInterceptor, 

2172 UnaryStreamClientInterceptor, 

2173 StreamUnaryClientInterceptor, or 

2174 StreamStreamClientInterceptor. 

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

2176 

2177 Returns: 

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

2179 

2180 Raises: 

2181 TypeError: If interceptor does not derive from any of 

2182 UnaryUnaryClientInterceptor, 

2183 UnaryStreamClientInterceptor, 

2184 StreamUnaryClientInterceptor, or 

2185 StreamStreamClientInterceptor. 

2186 """ 

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

2188 

2189 return _interceptor.intercept_channel(channel, *interceptors) 

2190 

2191 

2192def server( 

2193 thread_pool, 

2194 handlers=None, 

2195 interceptors=None, 

2196 options=None, 

2197 maximum_concurrent_rpcs=None, 

2198 compression=None, 

2199 xds=False, 

2200): 

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

2202 

2203 Args: 

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

2205 to execute RPC handlers. 

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

2207 More handlers may be added by calling add_generic_rpc_handlers any time 

2208 before the server is started. 

2209 interceptors: An optional list of ServerInterceptor objects that observe 

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

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

2212 specified. This is an EXPERIMENTAL API. 

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

2214 to configure the channel. 

2215 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server 

2216 will service before returning RESOURCE_EXHAUSTED status, or None to 

2217 indicate no limit. 

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

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

2220 lifetime of the server unless overridden. 

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

2222 EXPERIMENTAL option. 

2223 

2224 Returns: 

2225 A Server object. 

2226 """ 

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

2228 

2229 return _server.create_server( 

2230 thread_pool, 

2231 () if handlers is None else handlers, 

2232 () if interceptors is None else interceptors, 

2233 () if options is None else options, 

2234 maximum_concurrent_rpcs, 

2235 compression, 

2236 xds, 

2237 ) 

2238 

2239 

2240@contextlib.contextmanager 

2241def _create_servicer_context(rpc_event, state, request_deserializer): 

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

2243 

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

2245 yield context 

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

2247 

2248 

2249@enum.unique 

2250class Compression(enum.IntEnum): 

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

2252 

2253 Attributes: 

2254 NoCompression: Do not use compression algorithm. 

2255 Deflate: Use "Deflate" compression algorithm. 

2256 Gzip: Use "Gzip" compression algorithm. 

2257 """ 

2258 

2259 NoCompression = _compression.NoCompression 

2260 Deflate = _compression.Deflate 

2261 Gzip = _compression.Gzip 

2262 

2263 

2264################################### __all__ ################################# 

2265 

2266__all__ = ( 

2267 "AuthMetadataContext", 

2268 "AuthMetadataPlugin", 

2269 "AuthMetadataPluginCallback", 

2270 "Call", 

2271 "CallCredentials", 

2272 "Channel", 

2273 "ChannelConnectivity", 

2274 "ChannelCredentials", 

2275 "ClientCallDetails", 

2276 "Compression", 

2277 "Future", 

2278 "FutureCancelledError", 

2279 "FutureTimeoutError", 

2280 "GenericRpcHandler", 

2281 "HandlerCallDetails", 

2282 "LocalConnectionType", 

2283 "RpcContext", 

2284 "RpcError", 

2285 "RpcMethodHandler", 

2286 "Server", 

2287 "ServerCertificateConfiguration", 

2288 "ServerCredentials", 

2289 "ServerInterceptor", 

2290 "ServiceRpcHandler", 

2291 "ServicerContext", 

2292 "Status", 

2293 "StatusCode", 

2294 "StreamStreamClientInterceptor", 

2295 "StreamStreamMultiCallable", 

2296 "StreamUnaryClientInterceptor", 

2297 "StreamUnaryMultiCallable", 

2298 "UnaryStreamClientInterceptor", 

2299 "UnaryStreamMultiCallable", 

2300 "UnaryUnaryClientInterceptor", 

2301 "UnaryUnaryMultiCallable", 

2302 "access_token_call_credentials", 

2303 "alts_channel_credentials", 

2304 "alts_server_credentials", 

2305 "channel_ready_future", 

2306 "composite_call_credentials", 

2307 "composite_channel_credentials", 

2308 "compute_engine_channel_credentials", 

2309 "dynamic_ssl_server_credentials", 

2310 "insecure_channel", 

2311 "insecure_server_credentials", 

2312 "intercept_channel", 

2313 "local_channel_credentials", 

2314 "local_server_credentials", 

2315 "metadata_call_credentials", 

2316 "method_handlers_generic_handler", 

2317 "protos", 

2318 "protos_and_services", 

2319 "secure_channel", 

2320 "server", 

2321 "services", 

2322 "ssl_channel_credentials", 

2323 "ssl_server_certificate_configuration", 

2324 "ssl_server_credentials", 

2325 "stream_stream_rpc_method_handler", 

2326 "stream_unary_rpc_method_handler", 

2327 "unary_stream_rpc_method_handler", 

2328 "unary_unary_rpc_method_handler", 

2329 "xds_channel_credentials", 

2330 "xds_server_credentials", 

2331) 

2332 

2333############################### Extension Shims ################################ 

2334 

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

2336try: 

2337 import grpc_tools 

2338 

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

2340except ImportError: 

2341 pass 

2342try: 

2343 import grpc_health 

2344 

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

2346except ImportError: 

2347 pass 

2348try: 

2349 import grpc_reflection 

2350 

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

2352except ImportError: 

2353 pass 

2354 

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

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

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

2358 

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