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

372 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-06 06:03 +0000

1# Copyright 2015-2016 gRPC authors. 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14"""gRPC's Python API.""" 

15 

16import abc 

17import contextlib 

18import enum 

19import logging 

20import sys 

21 

22from grpc import _compression 

23from grpc._cython import cygrpc as _cygrpc 

24from grpc._runtime_protos import protos 

25from grpc._runtime_protos import protos_and_services 

26from grpc._runtime_protos import services 

27 

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

29 

30try: 

31 # pylint: disable=ungrouped-imports 

32 from grpc._grpcio_metadata import __version__ 

33except ImportError: 

34 __version__ = "dev0" 

35 

36############################## Future Interface ############################### 

37 

38 

39class FutureTimeoutError(Exception): 

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

41 

42 

43class FutureCancelledError(Exception): 

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

45 

46 

47class Future(abc.ABC): 

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

49 

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

51 may be ongoing, or may have already completed. 

52 """ 

53 

54 @abc.abstractmethod 

55 def cancel(self): 

56 """Attempts to cancel the computation. 

57 

58 This method does not block. 

59 

60 Returns: 

61 bool: 

62 Returns True if the computation was canceled. 

63 

64 Returns False under all other circumstances, for example: 

65 

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

67 2. computation has finished 

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

69 to determine its state without blocking. 

70 """ 

71 raise NotImplementedError() 

72 

73 @abc.abstractmethod 

74 def cancelled(self): 

75 """Describes whether the computation was cancelled. 

76 

77 This method does not block. 

78 

79 Returns: 

80 bool: 

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

82 available. 

83 

84 Returns False under all other circumstances, for example: 

85 

86 1. computation was not cancelled. 

87 2. computation's result is available. 

88 """ 

89 raise NotImplementedError() 

90 

91 @abc.abstractmethod 

92 def running(self): 

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

94 

95 This method does not block. 

96 

97 Returns: 

98 Returns True if the computation is scheduled for execution or 

99 currently executing. 

100 

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

102 """ 

103 raise NotImplementedError() 

104 

105 @abc.abstractmethod 

106 def done(self): 

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

108 

109 This method does not block. 

110 

111 Returns: 

112 bool: 

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

114 Returns False if the computation is scheduled for execution or 

115 currently executing. 

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

117 """ 

118 raise NotImplementedError() 

119 

120 @abc.abstractmethod 

121 def result(self, timeout=None): 

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

123 

124 This method may return immediately or may block. 

125 

126 Args: 

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

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

129 computations's termination. 

130 

131 Returns: 

132 The return value of the computation. 

133 

134 Raises: 

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

136 does not terminate within the allotted time. 

137 FutureCancelledError: If the computation was cancelled. 

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

139 raise the same exception. 

140 """ 

141 raise NotImplementedError() 

142 

143 @abc.abstractmethod 

144 def exception(self, timeout=None): 

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

146 

147 This method may return immediately or may block. 

148 

149 Args: 

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

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

152 computations's termination. 

153 

154 Returns: 

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

156 did not raise an exception. 

157 

158 Raises: 

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

160 does not terminate within the allotted time. 

161 FutureCancelledError: If the computation was cancelled. 

162 """ 

163 raise NotImplementedError() 

164 

165 @abc.abstractmethod 

166 def traceback(self, timeout=None): 

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

168 

169 This method may return immediately or may block. 

170 

171 Args: 

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

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

174 the computation's termination. 

175 

176 Returns: 

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

178 if the computation did not raise an exception. 

179 

180 Raises: 

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

182 does not terminate within the allotted time. 

183 FutureCancelledError: If the computation was cancelled. 

184 """ 

185 raise NotImplementedError() 

186 

187 @abc.abstractmethod 

188 def add_done_callback(self, fn): 

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

190 

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

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

193 terminated, whether successfully or not. 

194 

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

196 immediately. 

197 

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

199 will not terminate any threads of execution. 

200 

201 Args: 

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

203 """ 

204 raise NotImplementedError() 

205 

206 

207################################ gRPC Enums ################################## 

208 

209 

210@enum.unique 

211class ChannelConnectivity(enum.Enum): 

212 """Mirrors grpc_connectivity_state in the gRPC Core. 

213 

214 Attributes: 

215 IDLE: The channel is idle. 

216 CONNECTING: The channel is connecting. 

217 READY: The channel is ready to conduct RPCs. 

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

219 to recover. 

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

221 """ 

222 IDLE = (_cygrpc.ConnectivityState.idle, 'idle') 

223 CONNECTING = (_cygrpc.ConnectivityState.connecting, 'connecting') 

224 READY = (_cygrpc.ConnectivityState.ready, 'ready') 

225 TRANSIENT_FAILURE = (_cygrpc.ConnectivityState.transient_failure, 

226 'transient failure') 

227 SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, 'shutdown') 

228 

229 

230@enum.unique 

231class StatusCode(enum.Enum): 

232 """Mirrors grpc_status_code in the gRPC Core. 

233 

234 Attributes: 

235 OK: Not an error; returned on success 

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

237 UNKNOWN: Unknown error. 

238 INVALID_ARGUMENT: Client specified an invalid argument. 

239 DEADLINE_EXCEEDED: Deadline expired before operation could complete. 

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

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

242 already exists. 

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

244 operation. 

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

246 operation. 

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

248 perhaps the entire file system is out of space. 

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

250 required for the operation's execution. 

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

252 like sequencer check failures, transaction aborts, etc. 

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

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

255 system has been broken. 

256 UNAVAILABLE: The service is currently unavailable. 

257 DATA_LOSS: Unrecoverable data loss or corruption. 

258 """ 

259 OK = (_cygrpc.StatusCode.ok, 'ok') 

260 CANCELLED = (_cygrpc.StatusCode.cancelled, 'cancelled') 

261 UNKNOWN = (_cygrpc.StatusCode.unknown, 'unknown') 

262 INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, 'invalid argument') 

263 DEADLINE_EXCEEDED = (_cygrpc.StatusCode.deadline_exceeded, 

264 'deadline exceeded') 

265 NOT_FOUND = (_cygrpc.StatusCode.not_found, 'not found') 

266 ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, 'already exists') 

267 PERMISSION_DENIED = (_cygrpc.StatusCode.permission_denied, 

268 'permission denied') 

269 RESOURCE_EXHAUSTED = (_cygrpc.StatusCode.resource_exhausted, 

270 'resource exhausted') 

271 FAILED_PRECONDITION = (_cygrpc.StatusCode.failed_precondition, 

272 'failed precondition') 

273 ABORTED = (_cygrpc.StatusCode.aborted, 'aborted') 

274 OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, 'out of range') 

275 UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, 'unimplemented') 

276 INTERNAL = (_cygrpc.StatusCode.internal, 'internal') 

277 UNAVAILABLE = (_cygrpc.StatusCode.unavailable, 'unavailable') 

278 DATA_LOSS = (_cygrpc.StatusCode.data_loss, 'data loss') 

279 UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, 'unauthenticated') 

280 

281 

282############################# gRPC Status ################################ 

283 

284 

285class Status(abc.ABC): 

286 """Describes the status of an RPC. 

287 

288 This is an EXPERIMENTAL API. 

289 

290 Attributes: 

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

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

293 termination of the RPC. 

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

295 """ 

296 

297 

298############################# gRPC Exceptions ################################ 

299 

300 

301class RpcError(Exception): 

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

303 

304 

305############################## Shared Context ################################ 

306 

307 

308class RpcContext(abc.ABC): 

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

310 

311 @abc.abstractmethod 

312 def is_active(self): 

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

314 

315 Returns: 

316 bool: 

317 True if RPC is active, False otherwise. 

318 """ 

319 raise NotImplementedError() 

320 

321 @abc.abstractmethod 

322 def time_remaining(self): 

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

324 

325 Returns: 

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

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

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

329 """ 

330 raise NotImplementedError() 

331 

332 @abc.abstractmethod 

333 def cancel(self): 

334 """Cancels the RPC. 

335 

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

337 """ 

338 raise NotImplementedError() 

339 

340 @abc.abstractmethod 

341 def add_callback(self, callback): 

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

343 

344 Args: 

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

346 

347 Returns: 

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

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

350 already terminated or some other reason). 

351 """ 

352 raise NotImplementedError() 

353 

354 

355######################### Invocation-Side Context ############################ 

356 

357 

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

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

360 

361 @abc.abstractmethod 

362 def initial_metadata(self): 

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

364 

365 This method blocks until the value is available. 

366 

367 Returns: 

368 The initial :term:`metadata`. 

369 """ 

370 raise NotImplementedError() 

371 

372 @abc.abstractmethod 

373 def trailing_metadata(self): 

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

375 

376 This method blocks until the value is available. 

377 

378 Returns: 

379 The trailing :term:`metadata`. 

380 """ 

381 raise NotImplementedError() 

382 

383 @abc.abstractmethod 

384 def code(self): 

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

386 

387 This method blocks until the value is available. 

388 

389 Returns: 

390 The StatusCode value for the RPC. 

391 """ 

392 raise NotImplementedError() 

393 

394 @abc.abstractmethod 

395 def details(self): 

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

397 

398 This method blocks until the value is available. 

399 

400 Returns: 

401 The details string of the RPC. 

402 """ 

403 raise NotImplementedError() 

404 

405 

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

407 

408 

409class ClientCallDetails(abc.ABC): 

410 """Describes an RPC to be invoked. 

411 

412 Attributes: 

413 method: The method name of the RPC. 

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

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

416 the service-side of the RPC. 

417 credentials: An optional CallCredentials for the RPC. 

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

419 compression: An element of grpc.compression, e.g. 

420 grpc.compression.Gzip. 

421 """ 

422 

423 

424class UnaryUnaryClientInterceptor(abc.ABC): 

425 """Affords intercepting unary-unary invocations.""" 

426 

427 @abc.abstractmethod 

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

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

430 

431 Args: 

432 continuation: A function that proceeds with the invocation by 

433 executing the next interceptor in chain or invoking the 

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

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

436 The interceptor can use 

437 `response_future = continuation(client_call_details, request)` 

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

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

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

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

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

443 will be an RpcError. 

444 client_call_details: A ClientCallDetails object describing the 

445 outgoing RPC. 

446 request: The request value for the RPC. 

447 

448 Returns: 

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

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

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

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

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

454 """ 

455 raise NotImplementedError() 

456 

457 

458class UnaryStreamClientInterceptor(abc.ABC): 

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

460 

461 @abc.abstractmethod 

462 def intercept_unary_stream(self, continuation, client_call_details, 

463 request): 

464 """Intercepts a unary-stream invocation. 

465 

466 Args: 

467 continuation: A function that proceeds with the invocation by 

468 executing the next interceptor in chain or invoking the 

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

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

471 The interceptor can use 

472 `response_iterator = continuation(client_call_details, request)` 

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

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

475 Drawing response values from the returned Call-iterator may 

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

477 status. 

478 client_call_details: A ClientCallDetails object describing the 

479 outgoing RPC. 

480 request: The request value for the RPC. 

481 

482 Returns: 

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

484 response values. Drawing response values from the returned 

485 Call-iterator may raise RpcError indicating termination of 

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

487 Future interface, though it may not. 

488 """ 

489 raise NotImplementedError() 

490 

491 

492class StreamUnaryClientInterceptor(abc.ABC): 

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

494 

495 @abc.abstractmethod 

496 def intercept_stream_unary(self, continuation, client_call_details, 

497 request_iterator): 

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

499 

500 Args: 

501 continuation: A function that proceeds with the invocation by 

502 executing the next interceptor in chain or invoking the 

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

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

505 The interceptor can use 

506 `response_future = continuation(client_call_details, request_iterator)` 

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

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

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

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

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

512 client_call_details: A ClientCallDetails object describing the 

513 outgoing RPC. 

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

515 

516 Returns: 

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

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

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

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

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

522 """ 

523 raise NotImplementedError() 

524 

525 

526class StreamStreamClientInterceptor(abc.ABC): 

527 """Affords intercepting stream-stream invocations.""" 

528 

529 @abc.abstractmethod 

530 def intercept_stream_stream(self, continuation, client_call_details, 

531 request_iterator): 

532 """Intercepts a stream-stream invocation. 

533 

534 Args: 

535 continuation: A function that proceeds with the invocation by 

536 executing the next interceptor in chain or invoking the 

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

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

539 The interceptor can use 

540 `response_iterator = continuation(client_call_details, request_iterator)` 

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

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

543 Drawing response values from the returned Call-iterator may 

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

545 status. 

546 client_call_details: A ClientCallDetails object describing the 

547 outgoing RPC. 

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

549 

550 Returns: 

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

552 response values. Drawing response values from the returned 

553 Call-iterator may raise RpcError indicating termination of 

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

555 Future interface, though it may not. 

556 """ 

557 raise NotImplementedError() 

558 

559 

560############ Authentication & Authorization Interfaces & Classes ############# 

561 

562 

563class ChannelCredentials(object): 

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

565 

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

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

568 example, ssl_channel_credentials returns an instance of this class and 

569 secure_channel requires an instance of this class. 

570 """ 

571 

572 def __init__(self, credentials): 

573 self._credentials = credentials 

574 

575 

576class CallCredentials(object): 

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

578 

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

580 metadata will not be transmitted to the server. 

581 

582 A CallCredentials may be composed with ChannelCredentials to always assert 

583 identity for every call over that Channel. 

584 

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

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

587 """ 

588 

589 def __init__(self, credentials): 

590 self._credentials = credentials 

591 

592 

593class AuthMetadataContext(abc.ABC): 

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

595 

596 Attributes: 

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

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

599 """ 

600 

601 

602class AuthMetadataPluginCallback(abc.ABC): 

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

604 

605 def __call__(self, metadata, error): 

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

607 

608 Args: 

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

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

611 """ 

612 raise NotImplementedError() 

613 

614 

615class AuthMetadataPlugin(abc.ABC): 

616 """A specification for custom authentication.""" 

617 

618 def __call__(self, context, callback): 

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

620 

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

622 

623 Args: 

624 context: An AuthMetadataContext providing information on the RPC that 

625 the plugin is being called to authenticate. 

626 callback: An AuthMetadataPluginCallback to be invoked either 

627 synchronously or asynchronously. 

628 """ 

629 raise NotImplementedError() 

630 

631 

632class ServerCredentials(object): 

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

634 

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

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

637 """ 

638 

639 def __init__(self, credentials): 

640 self._credentials = credentials 

641 

642 

643class ServerCertificateConfiguration(object): 

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

645 

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

647 fetching callback. 

648 

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

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

651 other functions. 

652 """ 

653 

654 def __init__(self, certificate_configuration): 

655 self._certificate_configuration = certificate_configuration 

656 

657 

658######################## Multi-Callable Interfaces ########################### 

659 

660 

661class UnaryUnaryMultiCallable(abc.ABC): 

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

663 

664 @abc.abstractmethod 

665 def __call__(self, 

666 request, 

667 timeout=None, 

668 metadata=None, 

669 credentials=None, 

670 wait_for_ready=None, 

671 compression=None): 

672 """Synchronously invokes the underlying RPC. 

673 

674 Args: 

675 request: The request value for the RPC. 

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

677 for the RPC. 

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

679 service-side of the RPC. 

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

681 secure Channel. 

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

683 compression: An element of grpc.compression, e.g. 

684 grpc.compression.Gzip. 

685 

686 Returns: 

687 The response value for the RPC. 

688 

689 Raises: 

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

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

692 metadata, status code, and details. 

693 """ 

694 raise NotImplementedError() 

695 

696 @abc.abstractmethod 

697 def with_call(self, 

698 request, 

699 timeout=None, 

700 metadata=None, 

701 credentials=None, 

702 wait_for_ready=None, 

703 compression=None): 

704 """Synchronously invokes the underlying RPC. 

705 

706 Args: 

707 request: The request value for the RPC. 

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

709 the RPC. 

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

711 service-side of the RPC. 

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

713 secure Channel. 

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

715 compression: An element of grpc.compression, e.g. 

716 grpc.compression.Gzip. 

717 

718 Returns: 

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

720 

721 Raises: 

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

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

724 metadata, status code, and details. 

725 """ 

726 raise NotImplementedError() 

727 

728 @abc.abstractmethod 

729 def future(self, 

730 request, 

731 timeout=None, 

732 metadata=None, 

733 credentials=None, 

734 wait_for_ready=None, 

735 compression=None): 

736 """Asynchronously invokes the underlying RPC. 

737 

738 Args: 

739 request: The request value for the RPC. 

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

741 the RPC. 

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

743 service-side of the RPC. 

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

745 secure Channel. 

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

747 compression: An element of grpc.compression, e.g. 

748 grpc.compression.Gzip. 

749 

750 Returns: 

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

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

753 value will be the response message of the RPC. 

754 Should the event terminate with non-OK status, 

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

756 """ 

757 raise NotImplementedError() 

758 

759 

760class UnaryStreamMultiCallable(abc.ABC): 

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

762 

763 @abc.abstractmethod 

764 def __call__(self, 

765 request, 

766 timeout=None, 

767 metadata=None, 

768 credentials=None, 

769 wait_for_ready=None, 

770 compression=None): 

771 """Invokes the underlying RPC. 

772 

773 Args: 

774 request: The request value for the RPC. 

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

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

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

778 service-side of the RPC. 

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

780 secure Channel. 

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

782 compression: An element of grpc.compression, e.g. 

783 grpc.compression.Gzip. 

784 

785 Returns: 

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

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

788 returned Call-iterator may raise RpcError indicating termination of 

789 the RPC with non-OK status. 

790 """ 

791 raise NotImplementedError() 

792 

793 

794class StreamUnaryMultiCallable(abc.ABC): 

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

796 

797 @abc.abstractmethod 

798 def __call__(self, 

799 request_iterator, 

800 timeout=None, 

801 metadata=None, 

802 credentials=None, 

803 wait_for_ready=None, 

804 compression=None): 

805 """Synchronously invokes the underlying RPC. 

806 

807 Args: 

808 request_iterator: An iterator that yields request values for 

809 the RPC. 

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

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

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

813 service-side of the RPC. 

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

815 secure Channel. 

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

817 compression: An element of grpc.compression, e.g. 

818 grpc.compression.Gzip. 

819 

820 Returns: 

821 The response value for the RPC. 

822 

823 Raises: 

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

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

826 such as metadata, code, and details. 

827 """ 

828 raise NotImplementedError() 

829 

830 @abc.abstractmethod 

831 def with_call(self, 

832 request_iterator, 

833 timeout=None, 

834 metadata=None, 

835 credentials=None, 

836 wait_for_ready=None, 

837 compression=None): 

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

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 and a Call object for the RPC. 

855 

856 Raises: 

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

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

859 metadata, status code, and details. 

860 """ 

861 raise NotImplementedError() 

862 

863 @abc.abstractmethod 

864 def future(self, 

865 request_iterator, 

866 timeout=None, 

867 metadata=None, 

868 credentials=None, 

869 wait_for_ready=None, 

870 compression=None): 

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

872 

873 Args: 

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

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

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

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

878 service-side of the RPC. 

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

880 secure Channel. 

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

882 compression: An element of grpc.compression, e.g. 

883 grpc.compression.Gzip. 

884 

885 Returns: 

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

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

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

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

890 be an RpcError. 

891 """ 

892 raise NotImplementedError() 

893 

894 

895class StreamStreamMultiCallable(abc.ABC): 

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

897 

898 @abc.abstractmethod 

899 def __call__(self, 

900 request_iterator, 

901 timeout=None, 

902 metadata=None, 

903 credentials=None, 

904 wait_for_ready=None, 

905 compression=None): 

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

907 

908 Args: 

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

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

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

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

913 service-side of the RPC. 

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

915 secure Channel. 

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

917 compression: An element of grpc.compression, e.g. 

918 grpc.compression.Gzip. 

919 

920 Returns: 

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

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

923 returned Call-iterator may raise RpcError indicating termination of 

924 the RPC with non-OK status. 

925 """ 

926 raise NotImplementedError() 

927 

928 

929############################# Channel Interface ############################## 

930 

931 

932class Channel(abc.ABC): 

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

934 

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

936 support being entered and exited multiple times. 

937 """ 

938 

939 @abc.abstractmethod 

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

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

942 

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

944 This method allows application to monitor the state transitions. 

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

946 runtime's state. 

947 

948 Args: 

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

950 ChannelConnectivity describes current state of the channel. 

951 The callable will be invoked immediately upon subscription 

952 and again for every change to ChannelConnectivity until it 

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

954 try_to_connect: A boolean indicating whether or not this Channel 

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

956 runtime decides when to connect. 

957 """ 

958 raise NotImplementedError() 

959 

960 @abc.abstractmethod 

961 def unsubscribe(self, callback): 

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

963 

964 Args: 

965 callback: A callable previously registered with this Channel from 

966 having been passed to its "subscribe" method. 

967 """ 

968 raise NotImplementedError() 

969 

970 @abc.abstractmethod 

971 def unary_unary(self, 

972 method, 

973 request_serializer=None, 

974 response_deserializer=None): 

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

976 

977 Args: 

978 method: The name of the RPC method. 

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

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

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

982 response message. Response goes undeserialized in case None 

983 is passed. 

984 

985 Returns: 

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

987 """ 

988 raise NotImplementedError() 

989 

990 @abc.abstractmethod 

991 def unary_stream(self, 

992 method, 

993 request_serializer=None, 

994 response_deserializer=None): 

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

996 

997 Args: 

998 method: The name of the RPC method. 

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

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

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

1002 response message. Response goes undeserialized in case None is 

1003 passed. 

1004 

1005 Returns: 

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

1007 """ 

1008 raise NotImplementedError() 

1009 

1010 @abc.abstractmethod 

1011 def stream_unary(self, 

1012 method, 

1013 request_serializer=None, 

1014 response_deserializer=None): 

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

1016 

1017 Args: 

1018 method: The name of the RPC method. 

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

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

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

1022 response message. Response goes undeserialized in case None is 

1023 passed. 

1024 

1025 Returns: 

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

1027 """ 

1028 raise NotImplementedError() 

1029 

1030 @abc.abstractmethod 

1031 def stream_stream(self, 

1032 method, 

1033 request_serializer=None, 

1034 response_deserializer=None): 

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

1036 

1037 Args: 

1038 method: The name of the RPC method. 

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

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

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

1042 response message. Response goes undeserialized in case None 

1043 is passed. 

1044 

1045 Returns: 

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

1047 """ 

1048 raise NotImplementedError() 

1049 

1050 @abc.abstractmethod 

1051 def close(self): 

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

1053 

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

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

1056 

1057 This method is idempotent. 

1058 """ 

1059 raise NotImplementedError() 

1060 

1061 def __enter__(self): 

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

1063 raise NotImplementedError() 

1064 

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

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

1067 raise NotImplementedError() 

1068 

1069 

1070########################## Service-Side Context ############################## 

1071 

1072 

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

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

1075 

1076 @abc.abstractmethod 

1077 def invocation_metadata(self): 

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

1079 

1080 Returns: 

1081 The invocation :term:`metadata`. 

1082 """ 

1083 raise NotImplementedError() 

1084 

1085 @abc.abstractmethod 

1086 def peer(self): 

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

1088 

1089 Returns: 

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

1091 The string format is determined by gRPC runtime. 

1092 """ 

1093 raise NotImplementedError() 

1094 

1095 @abc.abstractmethod 

1096 def peer_identities(self): 

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

1098 

1099 Equivalent to 

1100 servicer_context.auth_context().get(servicer_context.peer_identity_key()) 

1101 

1102 Returns: 

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

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

1105 """ 

1106 raise NotImplementedError() 

1107 

1108 @abc.abstractmethod 

1109 def peer_identity_key(self): 

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

1111 

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

1113 used to identify an SSL peer. 

1114 

1115 Returns: 

1116 The auth property (string) that indicates the 

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

1118 """ 

1119 raise NotImplementedError() 

1120 

1121 @abc.abstractmethod 

1122 def auth_context(self): 

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

1124 

1125 Returns: 

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

1127 """ 

1128 raise NotImplementedError() 

1129 

1130 def set_compression(self, compression): 

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

1132 

1133 Args: 

1134 compression: An element of grpc.compression, e.g. 

1135 grpc.compression.Gzip. 

1136 """ 

1137 raise NotImplementedError() 

1138 

1139 @abc.abstractmethod 

1140 def send_initial_metadata(self, initial_metadata): 

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

1142 

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

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

1145 

1146 Args: 

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

1148 """ 

1149 raise NotImplementedError() 

1150 

1151 @abc.abstractmethod 

1152 def set_trailing_metadata(self, trailing_metadata): 

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

1154 

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

1156 

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

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

1159 over the wire. 

1160 

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

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

1163 

1164 Args: 

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

1166 """ 

1167 raise NotImplementedError() 

1168 

1169 def trailing_metadata(self): 

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

1171 

1172 This is an EXPERIMENTAL API. 

1173 

1174 Returns: 

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

1176 """ 

1177 raise NotImplementedError() 

1178 

1179 @abc.abstractmethod 

1180 def abort(self, code, details): 

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

1182 

1183 The code and details passed as arguments will supercede any existing 

1184 ones. 

1185 

1186 Args: 

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

1188 It must not be StatusCode.OK. 

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

1190 termination of the RPC. 

1191 

1192 Raises: 

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

1194 RPC to the gRPC runtime. 

1195 """ 

1196 raise NotImplementedError() 

1197 

1198 @abc.abstractmethod 

1199 def abort_with_status(self, status): 

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

1201 

1202 The status passed as argument will supercede any existing status code, 

1203 status message and trailing metadata. 

1204 

1205 This is an EXPERIMENTAL API. 

1206 

1207 Args: 

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

1209 StatusCode.OK. 

1210 

1211 Raises: 

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

1213 RPC to the gRPC runtime. 

1214 """ 

1215 raise NotImplementedError() 

1216 

1217 @abc.abstractmethod 

1218 def set_code(self, code): 

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

1220 

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

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

1223 

1224 Args: 

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

1226 """ 

1227 raise NotImplementedError() 

1228 

1229 @abc.abstractmethod 

1230 def set_details(self, details): 

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

1232 

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

1234 no details to transmit. 

1235 

1236 Args: 

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

1238 termination of the RPC. 

1239 """ 

1240 raise NotImplementedError() 

1241 

1242 def code(self): 

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

1244 

1245 This is an EXPERIMENTAL API. 

1246 

1247 Returns: 

1248 The StatusCode value for the RPC. 

1249 """ 

1250 raise NotImplementedError() 

1251 

1252 def details(self): 

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

1254 

1255 This is an EXPERIMENTAL API. 

1256 

1257 Returns: 

1258 The details string of the RPC. 

1259 """ 

1260 raise NotImplementedError() 

1261 

1262 def disable_next_message_compression(self): 

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

1264 

1265 This method will override any compression configuration set during 

1266 server creation or set on the call. 

1267 """ 

1268 raise NotImplementedError() 

1269 

1270 

1271##################### Service-Side Handler Interfaces ######################## 

1272 

1273 

1274class RpcMethodHandler(abc.ABC): 

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

1276 

1277 Attributes: 

1278 request_streaming: Whether the RPC supports exactly one request message 

1279 or any arbitrary number of request messages. 

1280 response_streaming: Whether the RPC supports exactly one response message 

1281 or any arbitrary number of response messages. 

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

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

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

1285 passed the raw request bytes. 

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

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

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

1289 should be transmitted on the wire as they are. 

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

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

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

1293 and response_streaming are False. 

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

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

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

1297 request_streaming is False and response_streaming is True. 

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

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

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

1301 request_streaming is True and response_streaming is False. 

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

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

1304 ServicerContext object and returns an iterator of response values. 

1305 Only non-None if request_streaming and response_streaming are both 

1306 True. 

1307 """ 

1308 

1309 

1310class HandlerCallDetails(abc.ABC): 

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

1312 

1313 Attributes: 

1314 method: The method name of the RPC. 

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

1316 """ 

1317 

1318 

1319class GenericRpcHandler(abc.ABC): 

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

1321 

1322 @abc.abstractmethod 

1323 def service(self, handler_call_details): 

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

1325 

1326 Args: 

1327 handler_call_details: A HandlerCallDetails describing the RPC. 

1328 

1329 Returns: 

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

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

1332 """ 

1333 raise NotImplementedError() 

1334 

1335 

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

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

1338 

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

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

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

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

1343 service name. 

1344 """ 

1345 

1346 @abc.abstractmethod 

1347 def service_name(self): 

1348 """Returns this service's name. 

1349 

1350 Returns: 

1351 The service name. 

1352 """ 

1353 raise NotImplementedError() 

1354 

1355 

1356#################### Service-Side Interceptor Interfaces ##################### 

1357 

1358 

1359class ServerInterceptor(abc.ABC): 

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

1361 

1362 @abc.abstractmethod 

1363 def intercept_service(self, continuation, handler_call_details): 

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

1365 

1366 Args: 

1367 continuation: A function that takes a HandlerCallDetails and 

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

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

1370 as an argument, and returns an RpcMethodHandler instance if 

1371 the RPC is considered serviced, or None otherwise. 

1372 handler_call_details: A HandlerCallDetails describing the RPC. 

1373 

1374 Returns: 

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

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

1377 """ 

1378 raise NotImplementedError() 

1379 

1380 

1381############################# Server Interface ############################### 

1382 

1383 

1384class Server(abc.ABC): 

1385 """Services RPCs.""" 

1386 

1387 @abc.abstractmethod 

1388 def add_generic_rpc_handlers(self, generic_rpc_handlers): 

1389 """Registers GenericRpcHandlers with this Server. 

1390 

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

1392 

1393 Args: 

1394 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be 

1395 used to service RPCs. 

1396 """ 

1397 raise NotImplementedError() 

1398 

1399 @abc.abstractmethod 

1400 def add_insecure_port(self, address): 

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

1402 

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

1404 

1405 Args: 

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

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

1408 

1409 Returns: 

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

1411 """ 

1412 raise NotImplementedError() 

1413 

1414 @abc.abstractmethod 

1415 def add_secure_port(self, address, server_credentials): 

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

1417 

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

1419 

1420 Args: 

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

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

1423 runtime will choose a port. 

1424 server_credentials: A ServerCredentials object. 

1425 

1426 Returns: 

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

1428 """ 

1429 raise NotImplementedError() 

1430 

1431 @abc.abstractmethod 

1432 def start(self): 

1433 """Starts this Server. 

1434 

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

1436 """ 

1437 raise NotImplementedError() 

1438 

1439 @abc.abstractmethod 

1440 def stop(self, grace): 

1441 """Stops this Server. 

1442 

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

1444 

1445 If a grace period is specified, this method returns immediately 

1446 and all RPCs active at the end of the grace period are aborted. 

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

1448 all existing RPCs are aborted immediately and this method 

1449 blocks until the last RPC handler terminates. 

1450 

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

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

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

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

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

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

1457 grace value is used). 

1458 

1459 Args: 

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

1461 

1462 Returns: 

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

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

1465 all handlers have terminated. 

1466 """ 

1467 raise NotImplementedError() 

1468 

1469 def wait_for_termination(self, timeout=None): 

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

1471 

1472 This is an EXPERIMENTAL API. 

1473 

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

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

1476 

1477 1) The server is stopped or terminated; 

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

1479 

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

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

1482 

1483 Args: 

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

1485 operation in seconds. 

1486 

1487 Returns: 

1488 A bool indicates if the operation times out. 

1489 """ 

1490 raise NotImplementedError() 

1491 

1492 

1493################################# Functions ################################ 

1494 

1495 

1496def unary_unary_rpc_method_handler(behavior, 

1497 request_deserializer=None, 

1498 response_serializer=None): 

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

1500 

1501 Args: 

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

1503 and returns one response. 

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

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

1506 

1507 Returns: 

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

1509 """ 

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

1511 return _utilities.RpcMethodHandler(False, False, request_deserializer, 

1512 response_serializer, behavior, None, 

1513 None, None) 

1514 

1515 

1516def unary_stream_rpc_method_handler(behavior, 

1517 request_deserializer=None, 

1518 response_serializer=None): 

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

1520 

1521 Args: 

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

1523 and returns an iterator of response values. 

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

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

1526 

1527 Returns: 

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

1529 """ 

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

1531 return _utilities.RpcMethodHandler(False, True, request_deserializer, 

1532 response_serializer, None, behavior, 

1533 None, None) 

1534 

1535 

1536def stream_unary_rpc_method_handler(behavior, 

1537 request_deserializer=None, 

1538 response_serializer=None): 

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

1540 

1541 Args: 

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

1543 request values and returns a single response value. 

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

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

1546 

1547 Returns: 

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

1549 """ 

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

1551 return _utilities.RpcMethodHandler(True, False, request_deserializer, 

1552 response_serializer, None, None, 

1553 behavior, None) 

1554 

1555 

1556def stream_stream_rpc_method_handler(behavior, 

1557 request_deserializer=None, 

1558 response_serializer=None): 

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

1560 

1561 Args: 

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

1563 request values and returns an iterator of response values. 

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

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

1566 

1567 Returns: 

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

1569 """ 

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

1571 return _utilities.RpcMethodHandler(True, True, request_deserializer, 

1572 response_serializer, None, None, None, 

1573 behavior) 

1574 

1575 

1576def method_handlers_generic_handler(service, method_handlers): 

1577 """Creates a GenericRpcHandler from RpcMethodHandlers. 

1578 

1579 Args: 

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

1581 method_handlers. 

1582 method_handlers: A dictionary that maps method names to corresponding 

1583 RpcMethodHandler. 

1584 

1585 Returns: 

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

1587 with add_generic_rpc_handlers() before starting the server. 

1588 """ 

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

1590 return _utilities.DictionaryGenericHandler(service, method_handlers) 

1591 

1592 

1593def ssl_channel_credentials(root_certificates=None, 

1594 private_key=None, 

1595 certificate_chain=None): 

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

1597 

1598 Args: 

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

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

1601 runtime. 

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

1603 private key should be used. 

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

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

1606 

1607 Returns: 

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

1609 """ 

1610 return ChannelCredentials( 

1611 _cygrpc.SSLChannelCredentials(root_certificates, private_key, 

1612 certificate_chain)) 

1613 

1614 

1615def xds_channel_credentials(fallback_credentials=None): 

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

1617 API. 

1618 

1619 Args: 

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

1621 establish a secure connection via xDS. If no fallback_credentials 

1622 argument is supplied, a default SSLChannelCredentials is used. 

1623 """ 

1624 fallback_credentials = ssl_channel_credentials( 

1625 ) if fallback_credentials is None else fallback_credentials 

1626 return ChannelCredentials( 

1627 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials)) 

1628 

1629 

1630def metadata_call_credentials(metadata_plugin, name=None): 

1631 """Construct CallCredentials from an AuthMetadataPlugin. 

1632 

1633 Args: 

1634 metadata_plugin: An AuthMetadataPlugin to use for authentication. 

1635 name: An optional name for the plugin. 

1636 

1637 Returns: 

1638 A CallCredentials. 

1639 """ 

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

1641 return _plugin_wrapping.metadata_plugin_call_credentials( 

1642 metadata_plugin, name) 

1643 

1644 

1645def access_token_call_credentials(access_token): 

1646 """Construct CallCredentials from an access token. 

1647 

1648 Args: 

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

1650 authorization header, for example 

1651 "authorization: Bearer <access_token>". 

1652 

1653 Returns: 

1654 A CallCredentials. 

1655 """ 

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

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

1658 return _plugin_wrapping.metadata_plugin_call_credentials( 

1659 _auth.AccessTokenAuthMetadataPlugin(access_token), None) 

1660 

1661 

1662def composite_call_credentials(*call_credentials): 

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

1664 

1665 Args: 

1666 *call_credentials: At least two CallCredentials objects. 

1667 

1668 Returns: 

1669 A CallCredentials object composed of the given CallCredentials objects. 

1670 """ 

1671 return CallCredentials( 

1672 _cygrpc.CompositeCallCredentials( 

1673 tuple(single_call_credentials._credentials 

1674 for single_call_credentials in call_credentials))) 

1675 

1676 

1677def composite_channel_credentials(channel_credentials, *call_credentials): 

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

1679 

1680 Args: 

1681 channel_credentials: A ChannelCredentials object. 

1682 *call_credentials: One or more CallCredentials objects. 

1683 

1684 Returns: 

1685 A ChannelCredentials composed of the given ChannelCredentials and 

1686 CallCredentials objects. 

1687 """ 

1688 return ChannelCredentials( 

1689 _cygrpc.CompositeChannelCredentials( 

1690 tuple(single_call_credentials._credentials 

1691 for single_call_credentials in call_credentials), 

1692 channel_credentials._credentials)) 

1693 

1694 

1695def ssl_server_credentials(private_key_certificate_chain_pairs, 

1696 root_certificates=None, 

1697 require_client_auth=False): 

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

1699 

1700 Args: 

1701 private_key_certificate_chain_pairs: A list of pairs of the form 

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

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

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

1705 If omitted, require_client_auth must also be False. 

1706 require_client_auth: A boolean indicating whether or not to require 

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

1708 is not None. 

1709 

1710 Returns: 

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

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

1713 """ 

1714 if not private_key_certificate_chain_pairs: 

1715 raise ValueError( 

1716 'At least one private key-certificate chain pair is required!') 

1717 elif require_client_auth and root_certificates is None: 

1718 raise ValueError( 

1719 'Illegal to require client auth without providing root certificates!' 

1720 ) 

1721 else: 

1722 return ServerCredentials( 

1723 _cygrpc.server_credentials_ssl(root_certificates, [ 

1724 _cygrpc.SslPemKeyCertPair(key, pem) 

1725 for key, pem in private_key_certificate_chain_pairs 

1726 ], require_client_auth)) 

1727 

1728 

1729def xds_server_credentials(fallback_credentials): 

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

1731 API. 

1732 

1733 Args: 

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

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

1736 """ 

1737 return ServerCredentials( 

1738 _cygrpc.xds_server_credentials(fallback_credentials._credentials)) 

1739 

1740 

1741def insecure_server_credentials(): 

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

1743 This is an EXPERIMENTAL API. 

1744 

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

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

1747 with xds_server_credentials. 

1748 """ 

1749 return ServerCredentials(_cygrpc.insecure_server_credentials()) 

1750 

1751 

1752def ssl_server_certificate_configuration(private_key_certificate_chain_pairs, 

1753 root_certificates=None): 

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

1755 

1756 Args: 

1757 private_key_certificate_chain_pairs: A collection of pairs of 

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

1759 chain]. 

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

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

1762 

1763 Returns: 

1764 A ServerCertificateConfiguration that can be returned in the certificate 

1765 configuration fetching callback. 

1766 """ 

1767 if private_key_certificate_chain_pairs: 

1768 return ServerCertificateConfiguration( 

1769 _cygrpc.server_certificate_config_ssl(root_certificates, [ 

1770 _cygrpc.SslPemKeyCertPair(key, pem) 

1771 for key, pem in private_key_certificate_chain_pairs 

1772 ])) 

1773 else: 

1774 raise ValueError( 

1775 'At least one private key-certificate chain pair is required!') 

1776 

1777 

1778def dynamic_ssl_server_credentials(initial_certificate_configuration, 

1779 certificate_configuration_fetcher, 

1780 require_client_authentication=False): 

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

1782 

1783 Args: 

1784 initial_certificate_configuration (ServerCertificateConfiguration): The 

1785 certificate configuration with which the server will be initialized. 

1786 certificate_configuration_fetcher (callable): A callable that takes no 

1787 arguments and should return a ServerCertificateConfiguration to 

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

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

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

1791 client connection before starting the TLS handshake with the 

1792 client, thus allowing the user application to optionally 

1793 return a new ServerCertificateConfiguration that the server will then 

1794 use for the handshake. 

1795 require_client_authentication: A boolean indicating whether or not to 

1796 require clients to be authenticated. 

1797 

1798 Returns: 

1799 A ServerCredentials. 

1800 """ 

1801 return ServerCredentials( 

1802 _cygrpc.server_credentials_ssl_dynamic_cert_config( 

1803 initial_certificate_configuration, 

1804 certificate_configuration_fetcher, require_client_authentication)) 

1805 

1806 

1807@enum.unique 

1808class LocalConnectionType(enum.Enum): 

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

1810 

1811 Attributes: 

1812 UDS: Unix domain socket connections 

1813 LOCAL_TCP: Local TCP connections. 

1814 """ 

1815 UDS = _cygrpc.LocalConnectionType.uds 

1816 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp 

1817 

1818 

1819def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 

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

1821 

1822 This is an EXPERIMENTAL API. 

1823 

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

1825 also UDS connections. 

1826 

1827 The connections created by local channel credentials are not 

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

1829 The UDS connections are considered secure by providing peer authentication 

1830 and data confidentiality while TCP connections are considered insecure. 

1831 

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

1833 local channel credentials. 

1834 

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

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

1837 

1838 Args: 

1839 local_connect_type: Local connection type (either 

1840 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 

1841 

1842 Returns: 

1843 A ChannelCredentials for use with a local Channel 

1844 """ 

1845 return ChannelCredentials( 

1846 _cygrpc.channel_credentials_local(local_connect_type.value)) 

1847 

1848 

1849def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 

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

1851 

1852 This is an EXPERIMENTAL API. 

1853 

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

1855 also UDS connections. 

1856 

1857 The connections created by local server credentials are not 

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

1859 The UDS connections are considered secure by providing peer authentication 

1860 and data confidentiality while TCP connections are considered insecure. 

1861 

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

1863 server credentials. 

1864 

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

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

1867 

1868 Args: 

1869 local_connect_type: Local connection type (either 

1870 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 

1871 

1872 Returns: 

1873 A ServerCredentials for use with a local Server 

1874 """ 

1875 return ServerCredentials( 

1876 _cygrpc.server_credentials_local(local_connect_type.value)) 

1877 

1878 

1879def alts_channel_credentials(service_accounts=None): 

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

1881 

1882 This is an EXPERIMENTAL API. 

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

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

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

1886 

1887 Args: 

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

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

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

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

1892 identity. 

1893 Returns: 

1894 A ChannelCredentials for use with an ALTS-enabled Channel 

1895 """ 

1896 return ChannelCredentials( 

1897 _cygrpc.channel_credentials_alts(service_accounts or [])) 

1898 

1899 

1900def alts_server_credentials(): 

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

1902 

1903 This is an EXPERIMENTAL API. 

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

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

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

1907 

1908 Returns: 

1909 A ServerCredentials for use with an ALTS-enabled Server 

1910 """ 

1911 return ServerCredentials(_cygrpc.server_credentials_alts()) 

1912 

1913 

1914def compute_engine_channel_credentials(call_credentials): 

1915 """Creates a compute engine channel credential. 

1916 

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

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

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

1920 

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

1922 credential in conjunction with a call credentials that authenticates the 

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

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

1925 """ 

1926 return ChannelCredentials( 

1927 _cygrpc.channel_credentials_compute_engine( 

1928 call_credentials._credentials)) 

1929 

1930 

1931def channel_ready_future(channel): 

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

1933 

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

1935 It merely decouples the Future from channel state machine. 

1936 

1937 Args: 

1938 channel: A Channel object. 

1939 

1940 Returns: 

1941 A Future object that matures when the channel connectivity is 

1942 ChannelConnectivity.READY. 

1943 """ 

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

1945 return _utilities.channel_ready_future(channel) 

1946 

1947 

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

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

1950 

1951 The returned Channel is thread-safe. 

1952 

1953 Args: 

1954 target: The server address 

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

1956 in gRPC Core runtime) to configure the channel. 

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

1958 used over the lifetime of the channel. 

1959 

1960 Returns: 

1961 A Channel. 

1962 """ 

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

1964 return _channel.Channel(target, () if options is None else options, None, 

1965 compression) 

1966 

1967 

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

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

1970 

1971 The returned Channel is thread-safe. 

1972 

1973 Args: 

1974 target: The server address. 

1975 credentials: A ChannelCredentials instance. 

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

1977 in gRPC Core runtime) to configure the channel. 

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

1979 used over the lifetime of the channel. 

1980 

1981 Returns: 

1982 A Channel. 

1983 """ 

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

1985 from grpc.experimental import _insecure_channel_credentials 

1986 if credentials._credentials is _insecure_channel_credentials: 

1987 raise ValueError( 

1988 "secure_channel cannot be called with insecure credentials." + 

1989 " Call insecure_channel instead.") 

1990 return _channel.Channel(target, () if options is None else options, 

1991 credentials._credentials, compression) 

1992 

1993 

1994def intercept_channel(channel, *interceptors): 

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

1996 

1997 Args: 

1998 channel: A Channel. 

1999 interceptors: Zero or more objects of type 

2000 UnaryUnaryClientInterceptor, 

2001 UnaryStreamClientInterceptor, 

2002 StreamUnaryClientInterceptor, or 

2003 StreamStreamClientInterceptor. 

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

2005 

2006 Returns: 

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

2008 

2009 Raises: 

2010 TypeError: If interceptor does not derive from any of 

2011 UnaryUnaryClientInterceptor, 

2012 UnaryStreamClientInterceptor, 

2013 StreamUnaryClientInterceptor, or 

2014 StreamStreamClientInterceptor. 

2015 """ 

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

2017 return _interceptor.intercept_channel(channel, *interceptors) 

2018 

2019 

2020def server(thread_pool, 

2021 handlers=None, 

2022 interceptors=None, 

2023 options=None, 

2024 maximum_concurrent_rpcs=None, 

2025 compression=None, 

2026 xds=False): 

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

2028 

2029 Args: 

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

2031 to execute RPC handlers. 

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

2033 More handlers may be added by calling add_generic_rpc_handlers any time 

2034 before the server is started. 

2035 interceptors: An optional list of ServerInterceptor objects that observe 

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

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

2038 specified. This is an EXPERIMENTAL API. 

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

2040 to configure the channel. 

2041 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server 

2042 will service before returning RESOURCE_EXHAUSTED status, or None to 

2043 indicate no limit. 

2044 compression: An element of grpc.compression, e.g. 

2045 grpc.compression.Gzip. This compression algorithm will be used for the 

2046 lifetime of the server unless overridden. 

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

2048 EXPERIMENTAL option. 

2049 

2050 Returns: 

2051 A Server object. 

2052 """ 

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

2054 return _server.create_server(thread_pool, 

2055 () if handlers is None else handlers, 

2056 () if interceptors is None else interceptors, 

2057 () if options is None else options, 

2058 maximum_concurrent_rpcs, compression, xds) 

2059 

2060 

2061@contextlib.contextmanager 

2062def _create_servicer_context(rpc_event, state, request_deserializer): 

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

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

2065 yield context 

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

2067 

2068 

2069@enum.unique 

2070class Compression(enum.IntEnum): 

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

2072 

2073 Attributes: 

2074 NoCompression: Do not use compression algorithm. 

2075 Deflate: Use "Deflate" compression algorithm. 

2076 Gzip: Use "Gzip" compression algorithm. 

2077 """ 

2078 NoCompression = _compression.NoCompression 

2079 Deflate = _compression.Deflate 

2080 Gzip = _compression.Gzip 

2081 

2082 

2083################################### __all__ ################################# 

2084 

2085__all__ = ( 

2086 'FutureTimeoutError', 

2087 'FutureCancelledError', 

2088 'Future', 

2089 'ChannelConnectivity', 

2090 'StatusCode', 

2091 'Status', 

2092 'RpcError', 

2093 'RpcContext', 

2094 'Call', 

2095 'ChannelCredentials', 

2096 'CallCredentials', 

2097 'AuthMetadataContext', 

2098 'AuthMetadataPluginCallback', 

2099 'AuthMetadataPlugin', 

2100 'Compression', 

2101 'ClientCallDetails', 

2102 'ServerCertificateConfiguration', 

2103 'ServerCredentials', 

2104 'LocalConnectionType', 

2105 'UnaryUnaryMultiCallable', 

2106 'UnaryStreamMultiCallable', 

2107 'StreamUnaryMultiCallable', 

2108 'StreamStreamMultiCallable', 

2109 'UnaryUnaryClientInterceptor', 

2110 'UnaryStreamClientInterceptor', 

2111 'StreamUnaryClientInterceptor', 

2112 'StreamStreamClientInterceptor', 

2113 'Channel', 

2114 'ServicerContext', 

2115 'RpcMethodHandler', 

2116 'HandlerCallDetails', 

2117 'GenericRpcHandler', 

2118 'ServiceRpcHandler', 

2119 'Server', 

2120 'ServerInterceptor', 

2121 'unary_unary_rpc_method_handler', 

2122 'unary_stream_rpc_method_handler', 

2123 'stream_unary_rpc_method_handler', 

2124 'stream_stream_rpc_method_handler', 

2125 'method_handlers_generic_handler', 

2126 'ssl_channel_credentials', 

2127 'metadata_call_credentials', 

2128 'access_token_call_credentials', 

2129 'composite_call_credentials', 

2130 'composite_channel_credentials', 

2131 'compute_engine_channel_credentials', 

2132 'local_channel_credentials', 

2133 'local_server_credentials', 

2134 'alts_channel_credentials', 

2135 'alts_server_credentials', 

2136 'ssl_server_credentials', 

2137 'ssl_server_certificate_configuration', 

2138 'dynamic_ssl_server_credentials', 

2139 'channel_ready_future', 

2140 'insecure_channel', 

2141 'secure_channel', 

2142 'intercept_channel', 

2143 'server', 

2144 'protos', 

2145 'services', 

2146 'protos_and_services', 

2147 'xds_channel_credentials', 

2148 'xds_server_credentials', 

2149 'insecure_server_credentials', 

2150) 

2151 

2152############################### Extension Shims ################################ 

2153 

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

2155try: 

2156 import grpc_tools 

2157 sys.modules.update({'grpc.tools': grpc_tools}) 

2158except ImportError: 

2159 pass 

2160try: 

2161 import grpc_health 

2162 sys.modules.update({'grpc.health': grpc_health}) 

2163except ImportError: 

2164 pass 

2165try: 

2166 import grpc_reflection 

2167 sys.modules.update({'grpc.reflection': grpc_reflection}) 

2168except ImportError: 

2169 pass 

2170 

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

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

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

2174 sys.modules.update({'grpc.aio': aio})