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

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 = (_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 def __init__(self, credentials): 

590 self._credentials = credentials 

591 

592 

593class CallCredentials: 

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

595 

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

597 metadata will not be transmitted to the server. 

598 

599 A CallCredentials may be composed with ChannelCredentials to always assert 

600 identity for every call over that Channel. 

601 

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

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

604 """ 

605 

606 def __init__(self, credentials): 

607 self._credentials = credentials 

608 

609 

610class AuthMetadataContext(abc.ABC): 

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

612 

613 Attributes: 

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

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

616 """ 

617 

618 

619class AuthMetadataPluginCallback(abc.ABC): 

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

621 

622 def __call__(self, metadata, error): 

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

624 

625 Args: 

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

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

628 """ 

629 raise NotImplementedError() 

630 

631 

632class AuthMetadataPlugin(abc.ABC): 

633 """A specification for custom authentication.""" 

634 

635 def __call__(self, context, callback): 

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

637 

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

639 

640 Args: 

641 context: An AuthMetadataContext providing information on the RPC that 

642 the plugin is being called to authenticate. 

643 callback: An AuthMetadataPluginCallback to be invoked either 

644 synchronously or asynchronously. 

645 """ 

646 raise NotImplementedError() 

647 

648 

649class ServerCredentials: 

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

651 

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

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

654 """ 

655 

656 def __init__(self, credentials): 

657 self._credentials = credentials 

658 

659 

660class ServerCertificateConfiguration: 

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

662 

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

664 fetching callback. 

665 

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

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

668 other functions. 

669 """ 

670 

671 def __init__(self, certificate_configuration): 

672 self._certificate_configuration = certificate_configuration 

673 

674 

675######################## Multi-Callable Interfaces ########################### 

676 

677 

678class UnaryUnaryMultiCallable(abc.ABC): 

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

680 

681 @abc.abstractmethod 

682 def __call__( 

683 self, 

684 request, 

685 timeout=None, 

686 metadata=None, 

687 credentials=None, 

688 wait_for_ready=None, 

689 compression=None, 

690 ): 

691 """Synchronously invokes the underlying RPC. 

692 

693 Args: 

694 request: The request value for the RPC. 

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

696 for the RPC. 

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

698 service-side of the RPC. 

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

700 secure Channel. 

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

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

703 grpc.Compression.Gzip. 

704 

705 Returns: 

706 The response value for the RPC. 

707 

708 Raises: 

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

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

711 metadata, status code, and details. 

712 """ 

713 raise NotImplementedError() 

714 

715 @abc.abstractmethod 

716 def with_call( 

717 self, 

718 request, 

719 timeout=None, 

720 metadata=None, 

721 credentials=None, 

722 wait_for_ready=None, 

723 compression=None, 

724 ): 

725 """Synchronously invokes the underlying RPC. 

726 

727 Args: 

728 request: The request value for the RPC. 

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

730 the RPC. 

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

732 service-side of the RPC. 

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

734 secure Channel. 

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

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

737 grpc.Compression.Gzip. 

738 

739 Returns: 

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

741 

742 Raises: 

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

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

745 metadata, status code, and details. 

746 """ 

747 raise NotImplementedError() 

748 

749 @abc.abstractmethod 

750 def future( 

751 self, 

752 request, 

753 timeout=None, 

754 metadata=None, 

755 credentials=None, 

756 wait_for_ready=None, 

757 compression=None, 

758 ): 

759 """Asynchronously invokes the underlying RPC. 

760 

761 Args: 

762 request: The request value for the RPC. 

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

764 the RPC. 

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

766 service-side of the RPC. 

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

768 secure Channel. 

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

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

771 grpc.Compression.Gzip. 

772 

773 Returns: 

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

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

776 value will be the response message of the RPC. 

777 Should the event terminate with non-OK status, 

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

779 """ 

780 raise NotImplementedError() 

781 

782 

783class UnaryStreamMultiCallable(abc.ABC): 

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

785 

786 @abc.abstractmethod 

787 def __call__( 

788 self, 

789 request, 

790 timeout=None, 

791 metadata=None, 

792 credentials=None, 

793 wait_for_ready=None, 

794 compression=None, 

795 ): 

796 """Invokes the underlying RPC. 

797 

798 Args: 

799 request: The request value for the RPC. 

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

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

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

803 service-side of the RPC. 

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

805 secure Channel. 

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

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

808 grpc.Compression.Gzip. 

809 

810 Returns: 

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

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

813 returned Call-iterator may raise RpcError indicating termination of 

814 the RPC with non-OK status. 

815 """ 

816 raise NotImplementedError() 

817 

818 

819class StreamUnaryMultiCallable(abc.ABC): 

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

821 

822 @abc.abstractmethod 

823 def __call__( 

824 self, 

825 request_iterator, 

826 timeout=None, 

827 metadata=None, 

828 credentials=None, 

829 wait_for_ready=None, 

830 compression=None, 

831 ): 

832 """Synchronously invokes the underlying RPC. 

833 

834 Args: 

835 request_iterator: An iterator that yields request values for 

836 the RPC. 

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

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

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

840 service-side of the RPC. 

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

842 secure Channel. 

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

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

845 grpc.Compression.Gzip. 

846 

847 Returns: 

848 The response value for the RPC. 

849 

850 Raises: 

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

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

853 such as metadata, code, and details. 

854 """ 

855 raise NotImplementedError() 

856 

857 @abc.abstractmethod 

858 def with_call( 

859 self, 

860 request_iterator, 

861 timeout=None, 

862 metadata=None, 

863 credentials=None, 

864 wait_for_ready=None, 

865 compression=None, 

866 ): 

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

868 

869 Args: 

870 request_iterator: An iterator that yields request values for 

871 the RPC. 

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

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

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

875 service-side of the RPC. 

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

877 secure Channel. 

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

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

880 grpc.Compression.Gzip. 

881 

882 Returns: 

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

884 

885 Raises: 

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

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

888 metadata, status code, and details. 

889 """ 

890 raise NotImplementedError() 

891 

892 @abc.abstractmethod 

893 def future( 

894 self, 

895 request_iterator, 

896 timeout=None, 

897 metadata=None, 

898 credentials=None, 

899 wait_for_ready=None, 

900 compression=None, 

901 ): 

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

903 

904 Args: 

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

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

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

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

909 service-side of the RPC. 

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

911 secure Channel. 

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

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

914 grpc.Compression.Gzip. 

915 

916 Returns: 

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

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

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

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

921 be an RpcError. 

922 """ 

923 raise NotImplementedError() 

924 

925 

926class StreamStreamMultiCallable(abc.ABC): 

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

928 

929 @abc.abstractmethod 

930 def __call__( 

931 self, 

932 request_iterator, 

933 timeout=None, 

934 metadata=None, 

935 credentials=None, 

936 wait_for_ready=None, 

937 compression=None, 

938 ): 

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

940 

941 Args: 

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

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

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

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

946 service-side of the RPC. 

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

948 secure Channel. 

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

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

951 grpc.Compression.Gzip. 

952 

953 Returns: 

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

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

956 returned Call-iterator may raise RpcError indicating termination of 

957 the RPC with non-OK status. 

958 """ 

959 raise NotImplementedError() 

960 

961 

962############################# Channel Interface ############################## 

963 

964 

965class Channel(abc.ABC): 

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

967 

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

969 support being entered and exited multiple times. 

970 """ 

971 

972 @abc.abstractmethod 

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

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

975 

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

977 This method allows application to monitor the state transitions. 

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

979 runtime's state. 

980 

981 Args: 

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

983 ChannelConnectivity describes current state of the channel. 

984 The callable will be invoked immediately upon subscription 

985 and again for every change to ChannelConnectivity until it 

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

987 try_to_connect: A boolean indicating whether or not this Channel 

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

989 runtime decides when to connect. 

990 """ 

991 raise NotImplementedError() 

992 

993 @abc.abstractmethod 

994 def unsubscribe(self, callback): 

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

996 

997 Args: 

998 callback: A callable previously registered with this Channel from 

999 having been passed to its "subscribe" method. 

1000 """ 

1001 raise NotImplementedError() 

1002 

1003 @abc.abstractmethod 

1004 def unary_unary( 

1005 self, 

1006 method, 

1007 request_serializer=None, 

1008 response_deserializer=None, 

1009 _registered_method=False, 

1010 ): 

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

1012 

1013 Args: 

1014 method: The name of the RPC method. 

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

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

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

1018 response message. Response goes undeserialized in case None 

1019 is passed. 

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

1021 is registered. 

1022 

1023 Returns: 

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

1025 """ 

1026 raise NotImplementedError() 

1027 

1028 @abc.abstractmethod 

1029 def unary_stream( 

1030 self, 

1031 method, 

1032 request_serializer=None, 

1033 response_deserializer=None, 

1034 _registered_method=False, 

1035 ): 

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

1037 

1038 Args: 

1039 method: The name of the RPC method. 

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

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

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

1043 response message. Response goes undeserialized in case None is 

1044 passed. 

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

1046 is registered. 

1047 

1048 Returns: 

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

1050 """ 

1051 raise NotImplementedError() 

1052 

1053 @abc.abstractmethod 

1054 def stream_unary( 

1055 self, 

1056 method, 

1057 request_serializer=None, 

1058 response_deserializer=None, 

1059 _registered_method=False, 

1060 ): 

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

1062 

1063 Args: 

1064 method: The name of the RPC method. 

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

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

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

1068 response message. Response goes undeserialized in case None is 

1069 passed. 

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

1071 is registered. 

1072 

1073 Returns: 

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

1075 """ 

1076 raise NotImplementedError() 

1077 

1078 @abc.abstractmethod 

1079 def stream_stream( 

1080 self, 

1081 method, 

1082 request_serializer=None, 

1083 response_deserializer=None, 

1084 _registered_method=False, 

1085 ): 

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

1087 

1088 Args: 

1089 method: The name of the RPC method. 

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

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

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

1093 response message. Response goes undeserialized in case None 

1094 is passed. 

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

1096 is registered. 

1097 

1098 Returns: 

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

1100 """ 

1101 raise NotImplementedError() 

1102 

1103 @abc.abstractmethod 

1104 def close(self): 

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

1106 

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

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

1109 

1110 This method is idempotent. 

1111 """ 

1112 raise NotImplementedError() 

1113 

1114 def __enter__(self): 

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

1116 raise NotImplementedError() 

1117 

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

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

1120 raise NotImplementedError() 

1121 

1122 

1123########################## Service-Side Context ############################## 

1124 

1125 

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

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

1128 

1129 @abc.abstractmethod 

1130 def invocation_metadata(self): 

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

1132 

1133 Returns: 

1134 The invocation :term:`metadata`. 

1135 """ 

1136 raise NotImplementedError() 

1137 

1138 @abc.abstractmethod 

1139 def peer(self): 

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

1141 

1142 Returns: 

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

1144 The string format is determined by gRPC runtime. 

1145 """ 

1146 raise NotImplementedError() 

1147 

1148 @abc.abstractmethod 

1149 def peer_identities(self): 

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

1151 

1152 Equivalent to 

1153 servicer_context.auth_context().get(servicer_context.peer_identity_key()) 

1154 

1155 Returns: 

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

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

1158 """ 

1159 raise NotImplementedError() 

1160 

1161 @abc.abstractmethod 

1162 def peer_identity_key(self): 

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

1164 

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

1166 used to identify an SSL peer. 

1167 

1168 Returns: 

1169 The auth property (string) that indicates the 

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

1171 """ 

1172 raise NotImplementedError() 

1173 

1174 @abc.abstractmethod 

1175 def auth_context(self): 

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

1177 

1178 Returns: 

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

1180 """ 

1181 raise NotImplementedError() 

1182 

1183 def set_compression(self, compression): 

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

1185 

1186 Args: 

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

1188 grpc.Compression.Gzip. 

1189 """ 

1190 raise NotImplementedError() 

1191 

1192 @abc.abstractmethod 

1193 def send_initial_metadata(self, initial_metadata): 

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

1195 

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

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

1198 

1199 Args: 

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

1201 """ 

1202 raise NotImplementedError() 

1203 

1204 @abc.abstractmethod 

1205 def set_trailing_metadata(self, trailing_metadata): 

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

1207 

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

1209 

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

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

1212 over the wire. 

1213 

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

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

1216 

1217 Args: 

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

1219 """ 

1220 raise NotImplementedError() 

1221 

1222 def trailing_metadata(self): 

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

1224 

1225 This is an EXPERIMENTAL API. 

1226 

1227 Returns: 

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

1229 """ 

1230 raise NotImplementedError() 

1231 

1232 @abc.abstractmethod 

1233 def abort(self, code, details): 

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

1235 

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

1237 ones. 

1238 

1239 Args: 

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

1241 It must not be StatusCode.OK. 

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

1243 termination of the RPC. 

1244 

1245 Raises: 

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

1247 RPC to the gRPC runtime. 

1248 """ 

1249 raise NotImplementedError() 

1250 

1251 @abc.abstractmethod 

1252 def abort_with_status(self, status): 

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

1254 

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

1256 status message and trailing metadata. 

1257 

1258 This is an EXPERIMENTAL API. 

1259 

1260 Args: 

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

1262 StatusCode.OK. 

1263 

1264 Raises: 

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

1266 RPC to the gRPC runtime. 

1267 """ 

1268 raise NotImplementedError() 

1269 

1270 @abc.abstractmethod 

1271 def set_code(self, code): 

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

1273 

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

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

1276 

1277 Args: 

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

1279 """ 

1280 raise NotImplementedError() 

1281 

1282 @abc.abstractmethod 

1283 def set_details(self, details): 

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

1285 

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

1287 no details to transmit. 

1288 

1289 Args: 

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

1291 termination of the RPC. 

1292 """ 

1293 raise NotImplementedError() 

1294 

1295 def code(self): 

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

1297 

1298 This is an EXPERIMENTAL API. 

1299 

1300 Returns: 

1301 The StatusCode value for the RPC. 

1302 """ 

1303 raise NotImplementedError() 

1304 

1305 def details(self): 

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

1307 

1308 This is an EXPERIMENTAL API. 

1309 

1310 Returns: 

1311 The details string of the RPC. 

1312 """ 

1313 raise NotImplementedError() 

1314 

1315 def disable_next_message_compression(self): 

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

1317 

1318 This method will override any compression configuration set during 

1319 server creation or set on the call. 

1320 """ 

1321 raise NotImplementedError() 

1322 

1323 

1324##################### Service-Side Handler Interfaces ######################## 

1325 

1326 

1327class RpcMethodHandler(abc.ABC): 

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

1329 

1330 Attributes: 

1331 request_streaming: Whether the RPC supports exactly one request message 

1332 or any arbitrary number of request messages. 

1333 response_streaming: Whether the RPC supports exactly one response message 

1334 or any arbitrary number of response messages. 

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

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

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

1338 passed the raw request bytes. 

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

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

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

1342 should be transmitted on the wire as they are. 

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

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

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

1346 and response_streaming are False. 

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

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

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

1350 request_streaming is False and response_streaming is True. 

1351 stream_unary: This object's application-specific business logic as a 

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

1353 ServicerContext object and returns a response value. Only non-None if 

1354 request_streaming is True and response_streaming is False. 

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

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

1357 ServicerContext object and returns an iterator of response values. 

1358 Only non-None if request_streaming and response_streaming are both 

1359 True. 

1360 """ 

1361 

1362 

1363@typing.runtime_checkable 

1364class HandlerCallDetails(Protocol): 

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

1366 

1367 Attributes: 

1368 method: The method name of the RPC. 

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

1370 """ 

1371 

1372 method: str 

1373 invocation_metadata: Any 

1374 

1375 

1376class GenericRpcHandler(abc.ABC): 

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

1378 

1379 @abc.abstractmethod 

1380 def service(self, handler_call_details): 

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

1382 

1383 Args: 

1384 handler_call_details: A HandlerCallDetails describing the RPC. 

1385 

1386 Returns: 

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

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

1389 """ 

1390 raise NotImplementedError() 

1391 

1392 

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

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

1395 

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

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

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

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

1400 service name. 

1401 """ 

1402 

1403 @abc.abstractmethod 

1404 def service_name(self): 

1405 """Returns this service's name. 

1406 

1407 Returns: 

1408 The service name. 

1409 """ 

1410 raise NotImplementedError() 

1411 

1412 

1413#################### Service-Side Interceptor Interfaces ##################### 

1414 

1415 

1416class ServerInterceptor(abc.ABC): 

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

1418 

1419 @abc.abstractmethod 

1420 def intercept_service(self, continuation, handler_call_details): 

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

1422 

1423 State can be passed from an interceptor to downstream interceptors 

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

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

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

1427 guarantees that interceptors and handlers will be called from the 

1428 same thread. 

1429 

1430 Args: 

1431 continuation: A function that takes a HandlerCallDetails and 

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

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

1434 as an argument, and returns an RpcMethodHandler instance if 

1435 the RPC is considered serviced, or None otherwise. 

1436 handler_call_details: A HandlerCallDetails describing the RPC. 

1437 

1438 Returns: 

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

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

1441 """ 

1442 raise NotImplementedError() 

1443 

1444 

1445############################# Server Interface ############################### 

1446 

1447 

1448class Server(abc.ABC): 

1449 """Services RPCs.""" 

1450 

1451 @abc.abstractmethod 

1452 def add_generic_rpc_handlers(self, generic_rpc_handlers): 

1453 """Registers GenericRpcHandlers with this Server. 

1454 

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

1456 

1457 Args: 

1458 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be 

1459 used to service RPCs. 

1460 """ 

1461 raise NotImplementedError() 

1462 

1463 def add_registered_method_handlers( # noqa: B027 

1464 self, service_name, method_handlers 

1465 ): 

1466 """Registers GenericRpcHandlers with this Server. 

1467 

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

1469 

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

1471 registered handler will take precedence. 

1472 

1473 Args: 

1474 service_name: The service name. 

1475 method_handlers: A dictionary that maps method names to corresponding 

1476 RpcMethodHandler. 

1477 """ 

1478 

1479 @abc.abstractmethod 

1480 def add_insecure_port(self, address): 

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

1482 

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

1484 

1485 Args: 

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

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

1488 

1489 Returns: 

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

1491 """ 

1492 raise NotImplementedError() 

1493 

1494 @abc.abstractmethod 

1495 def add_secure_port(self, address, server_credentials): 

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

1497 

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

1499 

1500 Args: 

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

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

1503 runtime will choose a port. 

1504 server_credentials: A ServerCredentials object. 

1505 

1506 Returns: 

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

1508 """ 

1509 raise NotImplementedError() 

1510 

1511 @abc.abstractmethod 

1512 def start(self): 

1513 """Starts this Server. 

1514 

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

1516 """ 

1517 raise NotImplementedError() 

1518 

1519 @abc.abstractmethod 

1520 def stop(self, grace): 

1521 """Stops this Server. 

1522 

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

1524 

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

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

1527 been terminated within the grace period are aborted. 

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

1529 all existing RPCs are aborted immediately and this method 

1530 blocks until the last RPC handler terminates. 

1531 

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

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

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

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

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

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

1538 grace value is used). 

1539 

1540 Args: 

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

1542 

1543 Returns: 

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

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

1546 all handlers have terminated. 

1547 """ 

1548 raise NotImplementedError() 

1549 

1550 def wait_for_termination(self, timeout=None): 

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

1552 

1553 This is an EXPERIMENTAL API. 

1554 

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

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

1557 

1558 1) The server is stopped or terminated; 

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

1560 

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

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

1563 

1564 Args: 

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

1566 operation in seconds. 

1567 

1568 Returns: 

1569 A bool indicates if the operation times out. 

1570 """ 

1571 raise NotImplementedError() 

1572 

1573 

1574################################# Functions ################################ 

1575 

1576 

1577def unary_unary_rpc_method_handler( 

1578 behavior, request_deserializer=None, response_serializer=None 

1579): 

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

1581 

1582 Args: 

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

1584 and returns one response. 

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

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

1587 

1588 Returns: 

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

1590 """ 

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

1592 

1593 return _utilities.RpcMethodHandler( 

1594 False, 

1595 False, 

1596 request_deserializer, 

1597 response_serializer, 

1598 behavior, 

1599 None, 

1600 None, 

1601 None, 

1602 ) 

1603 

1604 

1605def unary_stream_rpc_method_handler( 

1606 behavior, request_deserializer=None, response_serializer=None 

1607): 

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

1609 

1610 Args: 

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

1612 and returns an iterator of response values. 

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

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

1615 

1616 Returns: 

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

1618 """ 

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

1620 

1621 return _utilities.RpcMethodHandler( 

1622 False, 

1623 True, 

1624 request_deserializer, 

1625 response_serializer, 

1626 None, 

1627 behavior, 

1628 None, 

1629 None, 

1630 ) 

1631 

1632 

1633def stream_unary_rpc_method_handler( 

1634 behavior, request_deserializer=None, response_serializer=None 

1635): 

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

1637 

1638 Args: 

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

1640 request values and returns a single response value. 

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

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

1643 

1644 Returns: 

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

1646 """ 

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

1648 

1649 return _utilities.RpcMethodHandler( 

1650 True, 

1651 False, 

1652 request_deserializer, 

1653 response_serializer, 

1654 None, 

1655 None, 

1656 behavior, 

1657 None, 

1658 ) 

1659 

1660 

1661def stream_stream_rpc_method_handler( 

1662 behavior, request_deserializer=None, response_serializer=None 

1663): 

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

1665 

1666 Args: 

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

1668 request values and returns an iterator of response values. 

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

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

1671 

1672 Returns: 

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

1674 """ 

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

1676 

1677 return _utilities.RpcMethodHandler( 

1678 True, 

1679 True, 

1680 request_deserializer, 

1681 response_serializer, 

1682 None, 

1683 None, 

1684 None, 

1685 behavior, 

1686 ) 

1687 

1688 

1689def method_handlers_generic_handler(service, method_handlers): 

1690 """Creates a GenericRpcHandler from RpcMethodHandlers. 

1691 

1692 Args: 

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

1694 method_handlers. 

1695 method_handlers: A dictionary that maps method names to corresponding 

1696 RpcMethodHandler. 

1697 

1698 Returns: 

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

1700 with add_generic_rpc_handlers() before starting the server. 

1701 """ 

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

1703 

1704 return _utilities.DictionaryGenericHandler(service, method_handlers) 

1705 

1706 

1707def ssl_channel_credentials( 

1708 root_certificates=None, private_key=None, certificate_chain=None 

1709): 

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

1711 

1712 Args: 

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

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

1715 runtime. 

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

1717 private key should be used. 

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

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

1720 

1721 Returns: 

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

1723 """ 

1724 return ChannelCredentials( 

1725 _cygrpc.SSLChannelCredentials( 

1726 root_certificates, private_key, certificate_chain 

1727 ) 

1728 ) 

1729 

1730 

1731def xds_channel_credentials(fallback_credentials=None): 

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

1733 API. 

1734 

1735 Args: 

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

1737 establish a secure connection via xDS. If no fallback_credentials 

1738 argument is supplied, a default SSLChannelCredentials is used. 

1739 """ 

1740 fallback_credentials = ( 

1741 ssl_channel_credentials() 

1742 if fallback_credentials is None 

1743 else fallback_credentials 

1744 ) 

1745 return ChannelCredentials( 

1746 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials) 

1747 ) 

1748 

1749 

1750def metadata_call_credentials(metadata_plugin, name=None): 

1751 """Construct CallCredentials from an AuthMetadataPlugin. 

1752 

1753 Args: 

1754 metadata_plugin: An AuthMetadataPlugin to use for authentication. 

1755 name: An optional name for the plugin. 

1756 

1757 Returns: 

1758 A CallCredentials. 

1759 """ 

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

1761 

1762 return _plugin_wrapping.metadata_plugin_call_credentials( 

1763 metadata_plugin, name 

1764 ) 

1765 

1766 

1767def access_token_call_credentials(access_token): 

1768 """Construct CallCredentials from an access token. 

1769 

1770 Args: 

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

1772 authorization header, for example 

1773 "authorization: Bearer <access_token>". 

1774 

1775 Returns: 

1776 A CallCredentials. 

1777 """ 

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

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

1780 

1781 return _plugin_wrapping.metadata_plugin_call_credentials( 

1782 _auth.AccessTokenAuthMetadataPlugin(access_token), None 

1783 ) 

1784 

1785 

1786def composite_call_credentials(*call_credentials): 

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

1788 

1789 Args: 

1790 *call_credentials: At least two CallCredentials objects. 

1791 

1792 Returns: 

1793 A CallCredentials object composed of the given CallCredentials objects. 

1794 """ 

1795 return CallCredentials( 

1796 _cygrpc.CompositeCallCredentials( 

1797 tuple( 

1798 single_call_credentials._credentials 

1799 for single_call_credentials in call_credentials 

1800 ) 

1801 ) 

1802 ) 

1803 

1804 

1805def composite_channel_credentials(channel_credentials, *call_credentials): 

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

1807 

1808 Args: 

1809 channel_credentials: A ChannelCredentials object. 

1810 *call_credentials: One or more CallCredentials objects. 

1811 

1812 Returns: 

1813 A ChannelCredentials composed of the given ChannelCredentials and 

1814 CallCredentials objects. 

1815 """ 

1816 return ChannelCredentials( 

1817 _cygrpc.CompositeChannelCredentials( 

1818 tuple( 

1819 single_call_credentials._credentials 

1820 for single_call_credentials in call_credentials 

1821 ), 

1822 channel_credentials._credentials, 

1823 ) 

1824 ) 

1825 

1826 

1827def ssl_server_credentials( 

1828 private_key_certificate_chain_pairs, 

1829 root_certificates=None, 

1830 require_client_auth=False, 

1831): 

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

1833 

1834 Args: 

1835 private_key_certificate_chain_pairs: A list of pairs of the form 

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

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

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

1839 If omitted, require_client_auth must also be False. 

1840 require_client_auth: A boolean indicating whether or not to require 

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

1842 is not None. 

1843 

1844 Returns: 

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

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

1847 """ 

1848 if not private_key_certificate_chain_pairs: 

1849 error_msg = ( 

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

1851 ) 

1852 raise ValueError(error_msg) 

1853 if require_client_auth and root_certificates is None: 

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

1855 raise ValueError(error_msg) 

1856 return ServerCredentials( 

1857 _cygrpc.server_credentials_ssl( 

1858 root_certificates, 

1859 [ 

1860 _cygrpc.SslPemKeyCertPair(key, pem) 

1861 for key, pem in private_key_certificate_chain_pairs 

1862 ], 

1863 require_client_auth, 

1864 ) 

1865 ) 

1866 

1867 

1868def xds_server_credentials(fallback_credentials): 

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

1870 API. 

1871 

1872 Args: 

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

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

1875 """ 

1876 return ServerCredentials( 

1877 _cygrpc.xds_server_credentials(fallback_credentials._credentials) 

1878 ) 

1879 

1880 

1881def insecure_server_credentials(): 

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

1883 This is an EXPERIMENTAL API. 

1884 

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

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

1887 with xds_server_credentials. 

1888 """ 

1889 return ServerCredentials(_cygrpc.insecure_server_credentials()) 

1890 

1891 

1892def ssl_server_certificate_configuration( 

1893 private_key_certificate_chain_pairs, root_certificates=None 

1894): 

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

1896 

1897 Args: 

1898 private_key_certificate_chain_pairs: A collection of pairs of 

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

1900 chain]. 

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

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

1903 

1904 Returns: 

1905 A ServerCertificateConfiguration that can be returned in the certificate 

1906 configuration fetching callback. 

1907 """ 

1908 if private_key_certificate_chain_pairs: 

1909 return ServerCertificateConfiguration( 

1910 _cygrpc.server_certificate_config_ssl( 

1911 root_certificates, 

1912 [ 

1913 _cygrpc.SslPemKeyCertPair(key, pem) 

1914 for key, pem in private_key_certificate_chain_pairs 

1915 ], 

1916 ) 

1917 ) 

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

1919 raise ValueError(error_msg) 

1920 

1921 

1922def dynamic_ssl_server_credentials( 

1923 initial_certificate_configuration, 

1924 certificate_configuration_fetcher, 

1925 require_client_authentication=False, 

1926): 

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

1928 

1929 Args: 

1930 initial_certificate_configuration (ServerCertificateConfiguration): The 

1931 certificate configuration with which the server will be initialized. 

1932 certificate_configuration_fetcher (callable): A callable that takes no 

1933 arguments and should return a ServerCertificateConfiguration to 

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

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

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

1937 client connection before starting the TLS handshake with the 

1938 client, thus allowing the user application to optionally 

1939 return a new ServerCertificateConfiguration that the server will then 

1940 use for the handshake. 

1941 require_client_authentication: A boolean indicating whether or not to 

1942 require clients to be authenticated. 

1943 

1944 Returns: 

1945 A ServerCredentials. 

1946 """ 

1947 return ServerCredentials( 

1948 _cygrpc.server_credentials_ssl_dynamic_cert_config( 

1949 initial_certificate_configuration, 

1950 certificate_configuration_fetcher, 

1951 require_client_authentication, 

1952 ) 

1953 ) 

1954 

1955 

1956@enum.unique 

1957class LocalConnectionType(enum.Enum): 

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

1959 

1960 Attributes: 

1961 UDS: Unix domain socket connections 

1962 LOCAL_TCP: Local TCP connections. 

1963 """ 

1964 

1965 UDS = _cygrpc.LocalConnectionType.uds 

1966 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp 

1967 

1968 

1969def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 

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

1971 

1972 This is an EXPERIMENTAL API. 

1973 

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

1975 also UDS connections. 

1976 

1977 The connections created by local channel credentials are not 

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

1979 The UDS connections are considered secure by providing peer authentication 

1980 and data confidentiality while TCP connections are considered insecure. 

1981 

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

1983 local channel credentials. 

1984 

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

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

1987 

1988 Args: 

1989 local_connect_type: Local connection type (either 

1990 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 

1991 

1992 Returns: 

1993 A ChannelCredentials for use with a local Channel 

1994 """ 

1995 return ChannelCredentials( 

1996 _cygrpc.channel_credentials_local(local_connect_type.value) 

1997 ) 

1998 

1999 

2000def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 

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

2002 

2003 This is an EXPERIMENTAL API. 

2004 

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

2006 also UDS connections. 

2007 

2008 The connections created by local server credentials are not 

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

2010 The UDS connections are considered secure by providing peer authentication 

2011 and data confidentiality while TCP connections are considered insecure. 

2012 

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

2014 server credentials. 

2015 

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

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

2018 

2019 Args: 

2020 local_connect_type: Local connection type (either 

2021 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 

2022 

2023 Returns: 

2024 A ServerCredentials for use with a local Server 

2025 """ 

2026 return ServerCredentials( 

2027 _cygrpc.server_credentials_local(local_connect_type.value) 

2028 ) 

2029 

2030 

2031def alts_channel_credentials(service_accounts=None): 

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

2033 

2034 This is an EXPERIMENTAL API. 

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

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

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

2038 

2039 Args: 

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

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

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

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

2044 identity. 

2045 

2046 Returns: 

2047 A ChannelCredentials for use with an ALTS-enabled Channel 

2048 """ 

2049 return ChannelCredentials( 

2050 _cygrpc.channel_credentials_alts(service_accounts or []) 

2051 ) 

2052 

2053 

2054def alts_server_credentials(): 

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

2056 

2057 This is an EXPERIMENTAL API. 

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

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

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

2061 

2062 Returns: 

2063 A ServerCredentials for use with an ALTS-enabled Server 

2064 """ 

2065 return ServerCredentials(_cygrpc.server_credentials_alts()) 

2066 

2067 

2068def compute_engine_channel_credentials(call_credentials): 

2069 """Creates a compute engine channel credential. 

2070 

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

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

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

2074 

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

2076 credential in conjunction with a call credentials that authenticates the 

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

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

2079 """ 

2080 return ChannelCredentials( 

2081 _cygrpc.channel_credentials_compute_engine( 

2082 call_credentials._credentials 

2083 ) 

2084 ) 

2085 

2086 

2087def channel_ready_future(channel): 

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

2089 

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

2091 It merely decouples the Future from channel state machine. 

2092 

2093 Args: 

2094 channel: A Channel object. 

2095 

2096 Returns: 

2097 A Future object that matures when the channel connectivity is 

2098 ChannelConnectivity.READY. 

2099 """ 

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

2101 

2102 return _utilities.channel_ready_future(channel) 

2103 

2104 

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

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

2107 

2108 The returned Channel is thread-safe. 

2109 

2110 Args: 

2111 target: The server address 

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

2113 in gRPC Core runtime) to configure the channel. 

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

2115 used over the lifetime of the channel. 

2116 

2117 Returns: 

2118 A Channel. 

2119 """ 

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

2121 

2122 return _channel.Channel( 

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

2124 ) 

2125 

2126 

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

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

2129 

2130 The returned Channel is thread-safe. 

2131 

2132 Args: 

2133 target: The server address. 

2134 credentials: A ChannelCredentials instance. 

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

2136 in gRPC Core runtime) to configure the channel. 

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

2138 used over the lifetime of the channel. 

2139 

2140 Returns: 

2141 A Channel. 

2142 """ 

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

2144 from grpc.experimental import _insecure_channel_credentials 

2145 

2146 if credentials._credentials is _insecure_channel_credentials: 

2147 raise ValueError( 

2148 "secure_channel cannot be called with insecure credentials." 

2149 + " Call insecure_channel instead." 

2150 ) 

2151 return _channel.Channel( 

2152 target, 

2153 () if options is None else options, 

2154 credentials._credentials, 

2155 compression, 

2156 ) 

2157 

2158 

2159def intercept_channel(channel, *interceptors): 

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

2161 

2162 Args: 

2163 channel: A Channel. 

2164 interceptors: Zero or more objects of type 

2165 UnaryUnaryClientInterceptor, 

2166 UnaryStreamClientInterceptor, 

2167 StreamUnaryClientInterceptor, or 

2168 StreamStreamClientInterceptor. 

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

2170 

2171 Returns: 

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

2173 

2174 Raises: 

2175 TypeError: If interceptor does not derive from any of 

2176 UnaryUnaryClientInterceptor, 

2177 UnaryStreamClientInterceptor, 

2178 StreamUnaryClientInterceptor, or 

2179 StreamStreamClientInterceptor. 

2180 """ 

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

2182 

2183 return _interceptor.intercept_channel(channel, *interceptors) 

2184 

2185 

2186def server( 

2187 thread_pool, 

2188 handlers=None, 

2189 interceptors=None, 

2190 options=None, 

2191 maximum_concurrent_rpcs=None, 

2192 compression=None, 

2193 xds=False, 

2194): 

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

2196 

2197 Args: 

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

2199 to execute RPC handlers. 

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

2201 More handlers may be added by calling add_generic_rpc_handlers any time 

2202 before the server is started. 

2203 interceptors: An optional list of ServerInterceptor objects that observe 

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

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

2206 specified. This is an EXPERIMENTAL API. 

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

2208 to configure the channel. 

2209 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server 

2210 will service before returning RESOURCE_EXHAUSTED status, or None to 

2211 indicate no limit. 

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

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

2214 lifetime of the server unless overridden. 

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

2216 EXPERIMENTAL option. 

2217 

2218 Returns: 

2219 A Server object. 

2220 """ 

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

2222 

2223 return _server.create_server( 

2224 thread_pool, 

2225 () if handlers is None else handlers, 

2226 () if interceptors is None else interceptors, 

2227 () if options is None else options, 

2228 maximum_concurrent_rpcs, 

2229 compression, 

2230 xds, 

2231 ) 

2232 

2233 

2234@contextlib.contextmanager 

2235def _create_servicer_context(rpc_event, state, request_deserializer): 

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

2237 

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

2239 yield context 

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

2241 

2242 

2243@enum.unique 

2244class Compression(enum.IntEnum): 

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

2246 

2247 Attributes: 

2248 NoCompression: Do not use compression algorithm. 

2249 Deflate: Use "Deflate" compression algorithm. 

2250 Gzip: Use "Gzip" compression algorithm. 

2251 """ 

2252 

2253 NoCompression = _compression.NoCompression 

2254 Deflate = _compression.Deflate 

2255 Gzip = _compression.Gzip 

2256 

2257 

2258################################### __all__ ################################# 

2259 

2260__all__ = ( 

2261 "AuthMetadataContext", 

2262 "AuthMetadataPlugin", 

2263 "AuthMetadataPluginCallback", 

2264 "Call", 

2265 "CallCredentials", 

2266 "Channel", 

2267 "ChannelConnectivity", 

2268 "ChannelCredentials", 

2269 "ClientCallDetails", 

2270 "Compression", 

2271 "Future", 

2272 "FutureCancelledError", 

2273 "FutureTimeoutError", 

2274 "GenericRpcHandler", 

2275 "HandlerCallDetails", 

2276 "LocalConnectionType", 

2277 "RpcContext", 

2278 "RpcError", 

2279 "RpcMethodHandler", 

2280 "Server", 

2281 "ServerCertificateConfiguration", 

2282 "ServerCredentials", 

2283 "ServerInterceptor", 

2284 "ServiceRpcHandler", 

2285 "ServicerContext", 

2286 "Status", 

2287 "StatusCode", 

2288 "StreamStreamClientInterceptor", 

2289 "StreamStreamMultiCallable", 

2290 "StreamUnaryClientInterceptor", 

2291 "StreamUnaryMultiCallable", 

2292 "UnaryStreamClientInterceptor", 

2293 "UnaryStreamMultiCallable", 

2294 "UnaryUnaryClientInterceptor", 

2295 "UnaryUnaryMultiCallable", 

2296 "access_token_call_credentials", 

2297 "alts_channel_credentials", 

2298 "alts_server_credentials", 

2299 "channel_ready_future", 

2300 "composite_call_credentials", 

2301 "composite_channel_credentials", 

2302 "compute_engine_channel_credentials", 

2303 "dynamic_ssl_server_credentials", 

2304 "insecure_channel", 

2305 "insecure_server_credentials", 

2306 "intercept_channel", 

2307 "local_channel_credentials", 

2308 "local_server_credentials", 

2309 "metadata_call_credentials", 

2310 "method_handlers_generic_handler", 

2311 "protos", 

2312 "protos_and_services", 

2313 "secure_channel", 

2314 "server", 

2315 "services", 

2316 "ssl_channel_credentials", 

2317 "ssl_server_certificate_configuration", 

2318 "ssl_server_credentials", 

2319 "stream_stream_rpc_method_handler", 

2320 "stream_unary_rpc_method_handler", 

2321 "unary_stream_rpc_method_handler", 

2322 "unary_unary_rpc_method_handler", 

2323 "xds_channel_credentials", 

2324 "xds_server_credentials", 

2325) 

2326 

2327############################### Extension Shims ################################ 

2328 

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

2330try: 

2331 import grpc_tools 

2332 

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

2334except ImportError: 

2335 pass 

2336try: 

2337 import grpc_health 

2338 

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

2340except ImportError: 

2341 pass 

2342try: 

2343 import grpc_reflection 

2344 

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

2346except ImportError: 

2347 pass 

2348 

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

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

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

2352 

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