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

372 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-26 07:30 +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: This is an EXPERIMENTAL argument. An optional 

419 flag to enable :term:`wait_for_ready` mechanism. 

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

421 grpc.compression.Gzip. This is an EXPERIMENTAL option. 

422 """ 

423 

424 

425class UnaryUnaryClientInterceptor(abc.ABC): 

426 """Affords intercepting unary-unary invocations.""" 

427 

428 @abc.abstractmethod 

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

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

431 

432 Args: 

433 continuation: A function that proceeds with the invocation by 

434 executing the next interceptor in chain or invoking the 

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

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

437 The interceptor can use 

438 `response_future = continuation(client_call_details, request)` 

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

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

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

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

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

444 will be an RpcError. 

445 client_call_details: A ClientCallDetails object describing the 

446 outgoing RPC. 

447 request: The request value for the RPC. 

448 

449 Returns: 

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

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

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

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

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

455 """ 

456 raise NotImplementedError() 

457 

458 

459class UnaryStreamClientInterceptor(abc.ABC): 

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

461 

462 @abc.abstractmethod 

463 def intercept_unary_stream(self, continuation, client_call_details, 

464 request): 

465 """Intercepts a unary-stream invocation. 

466 

467 Args: 

468 continuation: A function that proceeds with the invocation by 

469 executing the next interceptor in chain or invoking the 

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

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

472 The interceptor can use 

473 `response_iterator = continuation(client_call_details, request)` 

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

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

476 Drawing response values from the returned Call-iterator may 

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

478 status. 

479 client_call_details: A ClientCallDetails object describing the 

480 outgoing RPC. 

481 request: The request value for the RPC. 

482 

483 Returns: 

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

485 response values. Drawing response values from the returned 

486 Call-iterator may raise RpcError indicating termination of 

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

488 Future interface, though it may not. 

489 """ 

490 raise NotImplementedError() 

491 

492 

493class StreamUnaryClientInterceptor(abc.ABC): 

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

495 

496 @abc.abstractmethod 

497 def intercept_stream_unary(self, continuation, client_call_details, 

498 request_iterator): 

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

500 

501 Args: 

502 continuation: A function that proceeds with the invocation by 

503 executing the next interceptor in chain or invoking the 

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

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

506 The interceptor can use 

507 `response_future = continuation(client_call_details, request_iterator)` 

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

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

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

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

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

513 client_call_details: A ClientCallDetails object describing the 

514 outgoing RPC. 

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

516 

517 Returns: 

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

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

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

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

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

523 """ 

524 raise NotImplementedError() 

525 

526 

527class StreamStreamClientInterceptor(abc.ABC): 

528 """Affords intercepting stream-stream invocations.""" 

529 

530 @abc.abstractmethod 

531 def intercept_stream_stream(self, continuation, client_call_details, 

532 request_iterator): 

533 """Intercepts a stream-stream invocation. 

534 

535 Args: 

536 continuation: A function that proceeds with the invocation by 

537 executing the next interceptor in chain or invoking the 

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

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

540 The interceptor can use 

541 `response_iterator = continuation(client_call_details, request_iterator)` 

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

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

544 Drawing response values from the returned Call-iterator may 

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

546 status. 

547 client_call_details: A ClientCallDetails object describing the 

548 outgoing RPC. 

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

550 

551 Returns: 

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

553 response values. Drawing response values from the returned 

554 Call-iterator may raise RpcError indicating termination of 

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

556 Future interface, though it may not. 

557 """ 

558 raise NotImplementedError() 

559 

560 

561############ Authentication & Authorization Interfaces & Classes ############# 

562 

563 

564class ChannelCredentials(object): 

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

566 

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

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

569 example, ssl_channel_credentials returns an instance of this class and 

570 secure_channel requires an instance of this class. 

571 """ 

572 

573 def __init__(self, credentials): 

574 self._credentials = credentials 

575 

576 

577class CallCredentials(object): 

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

579 

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

581 metadata will not be transmitted to the server. 

582 

583 A CallCredentials may be composed with ChannelCredentials to always assert 

584 identity for every call over that Channel. 

585 

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

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

588 """ 

589 

590 def __init__(self, credentials): 

591 self._credentials = credentials 

592 

593 

594class AuthMetadataContext(abc.ABC): 

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

596 

597 Attributes: 

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

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

600 """ 

601 

602 

603class AuthMetadataPluginCallback(abc.ABC): 

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

605 

606 def __call__(self, metadata, error): 

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

608 

609 Args: 

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

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

612 """ 

613 raise NotImplementedError() 

614 

615 

616class AuthMetadataPlugin(abc.ABC): 

617 """A specification for custom authentication.""" 

618 

619 def __call__(self, context, callback): 

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

621 

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

623 

624 Args: 

625 context: An AuthMetadataContext providing information on the RPC that 

626 the plugin is being called to authenticate. 

627 callback: An AuthMetadataPluginCallback to be invoked either 

628 synchronously or asynchronously. 

629 """ 

630 raise NotImplementedError() 

631 

632 

633class ServerCredentials(object): 

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

635 

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

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

638 """ 

639 

640 def __init__(self, credentials): 

641 self._credentials = credentials 

642 

643 

644class ServerCertificateConfiguration(object): 

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

646 

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

648 fetching callback. 

649 

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

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

652 other functions. 

653 """ 

654 

655 def __init__(self, certificate_configuration): 

656 self._certificate_configuration = certificate_configuration 

657 

658 

659######################## Multi-Callable Interfaces ########################### 

660 

661 

662class UnaryUnaryMultiCallable(abc.ABC): 

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

664 

665 @abc.abstractmethod 

666 def __call__(self, 

667 request, 

668 timeout=None, 

669 metadata=None, 

670 credentials=None, 

671 wait_for_ready=None, 

672 compression=None): 

673 """Synchronously invokes the underlying RPC. 

674 

675 Args: 

676 request: The request value for the RPC. 

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

678 for the RPC. 

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

680 service-side of the RPC. 

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

682 secure Channel. 

683 wait_for_ready: This is an EXPERIMENTAL argument. An optional 

684 flag to enable :term:`wait_for_ready` mechanism. 

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

686 grpc.compression.Gzip. This is an EXPERIMENTAL option. 

687 

688 Returns: 

689 The response value for the RPC. 

690 

691 Raises: 

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

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

694 metadata, status code, and details. 

695 """ 

696 raise NotImplementedError() 

697 

698 @abc.abstractmethod 

699 def with_call(self, 

700 request, 

701 timeout=None, 

702 metadata=None, 

703 credentials=None, 

704 wait_for_ready=None, 

705 compression=None): 

706 """Synchronously invokes the underlying RPC. 

707 

708 Args: 

709 request: The request value for the RPC. 

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

711 the RPC. 

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

713 service-side of the RPC. 

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

715 secure Channel. 

716 wait_for_ready: This is an EXPERIMENTAL argument. An optional 

717 flag to enable :term:`wait_for_ready` mechanism. 

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

719 grpc.compression.Gzip. This is an EXPERIMENTAL option. 

720 

721 Returns: 

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

723 

724 Raises: 

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

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

727 metadata, status code, and details. 

728 """ 

729 raise NotImplementedError() 

730 

731 @abc.abstractmethod 

732 def future(self, 

733 request, 

734 timeout=None, 

735 metadata=None, 

736 credentials=None, 

737 wait_for_ready=None, 

738 compression=None): 

739 """Asynchronously invokes the underlying RPC. 

740 

741 Args: 

742 request: The request value for the RPC. 

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

744 the RPC. 

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

746 service-side of the RPC. 

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

748 secure Channel. 

749 wait_for_ready: This is an EXPERIMENTAL argument. An optional 

750 flag to enable :term:`wait_for_ready` mechanism. 

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

752 grpc.compression.Gzip. This is an EXPERIMENTAL option. 

753 

754 Returns: 

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

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

757 value will be the response message of the RPC. 

758 Should the event terminate with non-OK status, 

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

760 """ 

761 raise NotImplementedError() 

762 

763 

764class UnaryStreamMultiCallable(abc.ABC): 

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

766 

767 @abc.abstractmethod 

768 def __call__(self, 

769 request, 

770 timeout=None, 

771 metadata=None, 

772 credentials=None, 

773 wait_for_ready=None, 

774 compression=None): 

775 """Invokes the underlying RPC. 

776 

777 Args: 

778 request: The request value for the RPC. 

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

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

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

782 service-side of the RPC. 

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

784 secure Channel. 

785 wait_for_ready: This is an EXPERIMENTAL argument. An optional 

786 flag to enable :term:`wait_for_ready` mechanism. 

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

788 grpc.compression.Gzip. This is an EXPERIMENTAL option. 

789 

790 Returns: 

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

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

793 returned Call-iterator may raise RpcError indicating termination of 

794 the RPC with non-OK status. 

795 """ 

796 raise NotImplementedError() 

797 

798 

799class StreamUnaryMultiCallable(abc.ABC): 

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

801 

802 @abc.abstractmethod 

803 def __call__(self, 

804 request_iterator, 

805 timeout=None, 

806 metadata=None, 

807 credentials=None, 

808 wait_for_ready=None, 

809 compression=None): 

810 """Synchronously invokes the underlying RPC. 

811 

812 Args: 

813 request_iterator: An iterator that yields request values for 

814 the RPC. 

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

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

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

818 service-side of the RPC. 

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

820 secure Channel. 

821 wait_for_ready: This is an EXPERIMENTAL argument. An optional 

822 flag to enable :term:`wait_for_ready` mechanism. 

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

824 grpc.compression.Gzip. This is an EXPERIMENTAL option. 

825 

826 Returns: 

827 The response value for the RPC. 

828 

829 Raises: 

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

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

832 such as metadata, code, and details. 

833 """ 

834 raise NotImplementedError() 

835 

836 @abc.abstractmethod 

837 def with_call(self, 

838 request_iterator, 

839 timeout=None, 

840 metadata=None, 

841 credentials=None, 

842 wait_for_ready=None, 

843 compression=None): 

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

845 

846 Args: 

847 request_iterator: An iterator that yields request values for 

848 the RPC. 

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

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

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

852 service-side of the RPC. 

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

854 secure Channel. 

855 wait_for_ready: This is an EXPERIMENTAL argument. An optional 

856 flag to enable :term:`wait_for_ready` mechanism. 

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

858 grpc.compression.Gzip. This is an EXPERIMENTAL option. 

859 

860 Returns: 

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

862 

863 Raises: 

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

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

866 metadata, status code, and details. 

867 """ 

868 raise NotImplementedError() 

869 

870 @abc.abstractmethod 

871 def future(self, 

872 request_iterator, 

873 timeout=None, 

874 metadata=None, 

875 credentials=None, 

876 wait_for_ready=None, 

877 compression=None): 

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

879 

880 Args: 

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

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

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

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

885 service-side of the RPC. 

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

887 secure Channel. 

888 wait_for_ready: This is an EXPERIMENTAL argument. An optional 

889 flag to enable :term:`wait_for_ready` mechanism. 

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

891 grpc.compression.Gzip. This is an EXPERIMENTAL option. 

892 

893 Returns: 

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

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

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

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

898 be an RpcError. 

899 """ 

900 raise NotImplementedError() 

901 

902 

903class StreamStreamMultiCallable(abc.ABC): 

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

905 

906 @abc.abstractmethod 

907 def __call__(self, 

908 request_iterator, 

909 timeout=None, 

910 metadata=None, 

911 credentials=None, 

912 wait_for_ready=None, 

913 compression=None): 

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

915 

916 Args: 

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

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

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

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

921 service-side of the RPC. 

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

923 secure Channel. 

924 wait_for_ready: This is an EXPERIMENTAL argument. An optional 

925 flag to enable :term:`wait_for_ready` mechanism. 

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

927 grpc.compression.Gzip. This is an EXPERIMENTAL option. 

928 

929 Returns: 

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

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

932 returned Call-iterator may raise RpcError indicating termination of 

933 the RPC with non-OK status. 

934 """ 

935 raise NotImplementedError() 

936 

937 

938############################# Channel Interface ############################## 

939 

940 

941class Channel(abc.ABC): 

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

943 

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

945 support being entered and exited multiple times. 

946 """ 

947 

948 @abc.abstractmethod 

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

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

951 

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

953 This method allows application to monitor the state transitions. 

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

955 runtime's state. 

956 

957 Args: 

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

959 ChannelConnectivity describes current state of the channel. 

960 The callable will be invoked immediately upon subscription 

961 and again for every change to ChannelConnectivity until it 

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

963 try_to_connect: A boolean indicating whether or not this Channel 

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

965 runtime decides when to connect. 

966 """ 

967 raise NotImplementedError() 

968 

969 @abc.abstractmethod 

970 def unsubscribe(self, callback): 

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

972 

973 Args: 

974 callback: A callable previously registered with this Channel from 

975 having been passed to its "subscribe" method. 

976 """ 

977 raise NotImplementedError() 

978 

979 @abc.abstractmethod 

980 def unary_unary(self, 

981 method, 

982 request_serializer=None, 

983 response_deserializer=None): 

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

985 

986 Args: 

987 method: The name of the RPC method. 

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

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

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

991 response message. Response goes undeserialized in case None 

992 is passed. 

993 

994 Returns: 

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

996 """ 

997 raise NotImplementedError() 

998 

999 @abc.abstractmethod 

1000 def unary_stream(self, 

1001 method, 

1002 request_serializer=None, 

1003 response_deserializer=None): 

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

1005 

1006 Args: 

1007 method: The name of the RPC method. 

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

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

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

1011 response message. Response goes undeserialized in case None is 

1012 passed. 

1013 

1014 Returns: 

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

1016 """ 

1017 raise NotImplementedError() 

1018 

1019 @abc.abstractmethod 

1020 def stream_unary(self, 

1021 method, 

1022 request_serializer=None, 

1023 response_deserializer=None): 

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

1025 

1026 Args: 

1027 method: The name of the RPC method. 

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

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

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

1031 response message. Response goes undeserialized in case None is 

1032 passed. 

1033 

1034 Returns: 

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

1036 """ 

1037 raise NotImplementedError() 

1038 

1039 @abc.abstractmethod 

1040 def stream_stream(self, 

1041 method, 

1042 request_serializer=None, 

1043 response_deserializer=None): 

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

1045 

1046 Args: 

1047 method: The name of the RPC method. 

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

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

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

1051 response message. Response goes undeserialized in case None 

1052 is passed. 

1053 

1054 Returns: 

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

1056 """ 

1057 raise NotImplementedError() 

1058 

1059 @abc.abstractmethod 

1060 def close(self): 

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

1062 

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

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

1065 

1066 This method is idempotent. 

1067 """ 

1068 raise NotImplementedError() 

1069 

1070 def __enter__(self): 

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

1072 raise NotImplementedError() 

1073 

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

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

1076 raise NotImplementedError() 

1077 

1078 

1079########################## Service-Side Context ############################## 

1080 

1081 

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

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

1084 

1085 @abc.abstractmethod 

1086 def invocation_metadata(self): 

1087 """Accesses the metadata from the sent by the client. 

1088 

1089 Returns: 

1090 The invocation :term:`metadata`. 

1091 """ 

1092 raise NotImplementedError() 

1093 

1094 @abc.abstractmethod 

1095 def peer(self): 

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

1097 

1098 Returns: 

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

1100 The string format is determined by gRPC runtime. 

1101 """ 

1102 raise NotImplementedError() 

1103 

1104 @abc.abstractmethod 

1105 def peer_identities(self): 

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

1107 

1108 Equivalent to 

1109 servicer_context.auth_context().get(servicer_context.peer_identity_key()) 

1110 

1111 Returns: 

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

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

1114 """ 

1115 raise NotImplementedError() 

1116 

1117 @abc.abstractmethod 

1118 def peer_identity_key(self): 

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

1120 

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

1122 used to identify an SSL peer. 

1123 

1124 Returns: 

1125 The auth property (string) that indicates the 

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

1127 """ 

1128 raise NotImplementedError() 

1129 

1130 @abc.abstractmethod 

1131 def auth_context(self): 

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

1133 

1134 Returns: 

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

1136 """ 

1137 raise NotImplementedError() 

1138 

1139 def set_compression(self, compression): 

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

1141 

1142 This is an EXPERIMENTAL method. 

1143 

1144 Args: 

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

1146 grpc.compression.Gzip. 

1147 """ 

1148 raise NotImplementedError() 

1149 

1150 @abc.abstractmethod 

1151 def send_initial_metadata(self, initial_metadata): 

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

1153 

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

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

1156 

1157 Args: 

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

1159 """ 

1160 raise NotImplementedError() 

1161 

1162 @abc.abstractmethod 

1163 def set_trailing_metadata(self, trailing_metadata): 

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

1165 

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

1167 

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

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

1170 over the wire. 

1171 

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

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

1174 

1175 Args: 

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

1177 """ 

1178 raise NotImplementedError() 

1179 

1180 def trailing_metadata(self): 

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

1182 

1183 This is an EXPERIMENTAL API. 

1184 

1185 Returns: 

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

1187 """ 

1188 raise NotImplementedError() 

1189 

1190 @abc.abstractmethod 

1191 def abort(self, code, details): 

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

1193 

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

1195 ones. 

1196 

1197 Args: 

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

1199 It must not be StatusCode.OK. 

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

1201 termination of the RPC. 

1202 

1203 Raises: 

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

1205 RPC to the gRPC runtime. 

1206 """ 

1207 raise NotImplementedError() 

1208 

1209 @abc.abstractmethod 

1210 def abort_with_status(self, status): 

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

1212 

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

1214 status message and trailing metadata. 

1215 

1216 This is an EXPERIMENTAL API. 

1217 

1218 Args: 

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

1220 StatusCode.OK. 

1221 

1222 Raises: 

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

1224 RPC to the gRPC runtime. 

1225 """ 

1226 raise NotImplementedError() 

1227 

1228 @abc.abstractmethod 

1229 def set_code(self, code): 

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

1231 

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

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

1234 

1235 Args: 

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

1237 """ 

1238 raise NotImplementedError() 

1239 

1240 @abc.abstractmethod 

1241 def set_details(self, details): 

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

1243 

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

1245 no details to transmit. 

1246 

1247 Args: 

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

1249 termination of the RPC. 

1250 """ 

1251 raise NotImplementedError() 

1252 

1253 def code(self): 

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

1255 

1256 This is an EXPERIMENTAL API. 

1257 

1258 Returns: 

1259 The StatusCode value for the RPC. 

1260 """ 

1261 raise NotImplementedError() 

1262 

1263 def details(self): 

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

1265 

1266 This is an EXPERIMENTAL API. 

1267 

1268 Returns: 

1269 The details string of the RPC. 

1270 """ 

1271 raise NotImplementedError() 

1272 

1273 def disable_next_message_compression(self): 

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

1275 

1276 This is an EXPERIMENTAL method. 

1277 

1278 This method will override any compression configuration set during 

1279 server creation or set on the call. 

1280 """ 

1281 raise NotImplementedError() 

1282 

1283 

1284##################### Service-Side Handler Interfaces ######################## 

1285 

1286 

1287class RpcMethodHandler(abc.ABC): 

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

1289 

1290 Attributes: 

1291 request_streaming: Whether the RPC supports exactly one request message 

1292 or any arbitrary number of request messages. 

1293 response_streaming: Whether the RPC supports exactly one response message 

1294 or any arbitrary number of response messages. 

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

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

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

1298 passed the raw request bytes. 

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

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

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

1302 should be transmitted on the wire as they are. 

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

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

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

1306 and response_streaming are False. 

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

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

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

1310 request_streaming is False and response_streaming is True. 

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

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

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

1314 request_streaming is True and response_streaming is False. 

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

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

1317 ServicerContext object and returns an iterator of response values. 

1318 Only non-None if request_streaming and response_streaming are both 

1319 True. 

1320 """ 

1321 

1322 

1323class HandlerCallDetails(abc.ABC): 

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

1325 

1326 Attributes: 

1327 method: The method name of the RPC. 

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

1329 """ 

1330 

1331 

1332class GenericRpcHandler(abc.ABC): 

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

1334 

1335 @abc.abstractmethod 

1336 def service(self, handler_call_details): 

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

1338 

1339 Args: 

1340 handler_call_details: A HandlerCallDetails describing the RPC. 

1341 

1342 Returns: 

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

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

1345 """ 

1346 raise NotImplementedError() 

1347 

1348 

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

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

1351 

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

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

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

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

1356 service name. 

1357 """ 

1358 

1359 @abc.abstractmethod 

1360 def service_name(self): 

1361 """Returns this service's name. 

1362 

1363 Returns: 

1364 The service name. 

1365 """ 

1366 raise NotImplementedError() 

1367 

1368 

1369#################### Service-Side Interceptor Interfaces ##################### 

1370 

1371 

1372class ServerInterceptor(abc.ABC): 

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

1374 

1375 @abc.abstractmethod 

1376 def intercept_service(self, continuation, handler_call_details): 

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

1378 

1379 Args: 

1380 continuation: A function that takes a HandlerCallDetails and 

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

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

1383 as an argument, and returns an RpcMethodHandler instance if 

1384 the RPC is considered serviced, or None otherwise. 

1385 handler_call_details: A HandlerCallDetails describing the RPC. 

1386 

1387 Returns: 

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

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

1390 """ 

1391 raise NotImplementedError() 

1392 

1393 

1394############################# Server Interface ############################### 

1395 

1396 

1397class Server(abc.ABC): 

1398 """Services RPCs.""" 

1399 

1400 @abc.abstractmethod 

1401 def add_generic_rpc_handlers(self, generic_rpc_handlers): 

1402 """Registers GenericRpcHandlers with this Server. 

1403 

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

1405 

1406 Args: 

1407 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be 

1408 used to service RPCs. 

1409 """ 

1410 raise NotImplementedError() 

1411 

1412 @abc.abstractmethod 

1413 def add_insecure_port(self, address): 

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

1415 

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

1417 

1418 Args: 

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

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

1421 

1422 Returns: 

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

1424 """ 

1425 raise NotImplementedError() 

1426 

1427 @abc.abstractmethod 

1428 def add_secure_port(self, address, server_credentials): 

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

1430 

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

1432 

1433 Args: 

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

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

1436 runtime will choose a port. 

1437 server_credentials: A ServerCredentials object. 

1438 

1439 Returns: 

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

1441 """ 

1442 raise NotImplementedError() 

1443 

1444 @abc.abstractmethod 

1445 def start(self): 

1446 """Starts this Server. 

1447 

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

1449 """ 

1450 raise NotImplementedError() 

1451 

1452 @abc.abstractmethod 

1453 def stop(self, grace): 

1454 """Stops this Server. 

1455 

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

1457 

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

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

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

1461 all existing RPCs are aborted immediately and this method 

1462 blocks until the last RPC handler terminates. 

1463 

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

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

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

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

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

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

1470 grace value is used). 

1471 

1472 Args: 

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

1474 

1475 Returns: 

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

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

1478 all handlers have terminated. 

1479 """ 

1480 raise NotImplementedError() 

1481 

1482 def wait_for_termination(self, timeout=None): 

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

1484 

1485 This is an EXPERIMENTAL API. 

1486 

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

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

1489 

1490 1) The server is stopped or terminated; 

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

1492 

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

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

1495 

1496 Args: 

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

1498 operation in seconds. 

1499 

1500 Returns: 

1501 A bool indicates if the operation times out. 

1502 """ 

1503 raise NotImplementedError() 

1504 

1505 

1506################################# Functions ################################ 

1507 

1508 

1509def unary_unary_rpc_method_handler(behavior, 

1510 request_deserializer=None, 

1511 response_serializer=None): 

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

1513 

1514 Args: 

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

1516 and returns one response. 

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

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

1519 

1520 Returns: 

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

1522 """ 

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

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

1525 response_serializer, behavior, None, 

1526 None, None) 

1527 

1528 

1529def unary_stream_rpc_method_handler(behavior, 

1530 request_deserializer=None, 

1531 response_serializer=None): 

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

1533 

1534 Args: 

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

1536 and returns an iterator of response values. 

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

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

1539 

1540 Returns: 

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

1542 """ 

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

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

1545 response_serializer, None, behavior, 

1546 None, None) 

1547 

1548 

1549def stream_unary_rpc_method_handler(behavior, 

1550 request_deserializer=None, 

1551 response_serializer=None): 

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

1553 

1554 Args: 

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

1556 request values and returns a single response value. 

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

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

1559 

1560 Returns: 

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

1562 """ 

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

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

1565 response_serializer, None, None, 

1566 behavior, None) 

1567 

1568 

1569def stream_stream_rpc_method_handler(behavior, 

1570 request_deserializer=None, 

1571 response_serializer=None): 

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

1573 

1574 Args: 

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

1576 request values and returns an iterator of response values. 

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

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

1579 

1580 Returns: 

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

1582 """ 

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

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

1585 response_serializer, None, None, None, 

1586 behavior) 

1587 

1588 

1589def method_handlers_generic_handler(service, method_handlers): 

1590 """Creates a GenericRpcHandler from RpcMethodHandlers. 

1591 

1592 Args: 

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

1594 method_handlers. 

1595 method_handlers: A dictionary that maps method names to corresponding 

1596 RpcMethodHandler. 

1597 

1598 Returns: 

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

1600 with add_generic_rpc_handlers() before starting the server. 

1601 """ 

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

1603 return _utilities.DictionaryGenericHandler(service, method_handlers) 

1604 

1605 

1606def ssl_channel_credentials(root_certificates=None, 

1607 private_key=None, 

1608 certificate_chain=None): 

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

1610 

1611 Args: 

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

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

1614 runtime. 

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

1616 private key should be used. 

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

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

1619 

1620 Returns: 

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

1622 """ 

1623 return ChannelCredentials( 

1624 _cygrpc.SSLChannelCredentials(root_certificates, private_key, 

1625 certificate_chain)) 

1626 

1627 

1628def xds_channel_credentials(fallback_credentials=None): 

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

1630 API. 

1631 

1632 Args: 

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

1634 establish a secure connection via xDS. If no fallback_credentials 

1635 argument is supplied, a default SSLChannelCredentials is used. 

1636 """ 

1637 fallback_credentials = ssl_channel_credentials( 

1638 ) if fallback_credentials is None else fallback_credentials 

1639 return ChannelCredentials( 

1640 _cygrpc.XDSChannelCredentials(fallback_credentials._credentials)) 

1641 

1642 

1643def metadata_call_credentials(metadata_plugin, name=None): 

1644 """Construct CallCredentials from an AuthMetadataPlugin. 

1645 

1646 Args: 

1647 metadata_plugin: An AuthMetadataPlugin to use for authentication. 

1648 name: An optional name for the plugin. 

1649 

1650 Returns: 

1651 A CallCredentials. 

1652 """ 

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

1654 return _plugin_wrapping.metadata_plugin_call_credentials( 

1655 metadata_plugin, name) 

1656 

1657 

1658def access_token_call_credentials(access_token): 

1659 """Construct CallCredentials from an access token. 

1660 

1661 Args: 

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

1663 authorization header, for example 

1664 "authorization: Bearer <access_token>". 

1665 

1666 Returns: 

1667 A CallCredentials. 

1668 """ 

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

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

1671 return _plugin_wrapping.metadata_plugin_call_credentials( 

1672 _auth.AccessTokenAuthMetadataPlugin(access_token), None) 

1673 

1674 

1675def composite_call_credentials(*call_credentials): 

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

1677 

1678 Args: 

1679 *call_credentials: At least two CallCredentials objects. 

1680 

1681 Returns: 

1682 A CallCredentials object composed of the given CallCredentials objects. 

1683 """ 

1684 return CallCredentials( 

1685 _cygrpc.CompositeCallCredentials( 

1686 tuple(single_call_credentials._credentials 

1687 for single_call_credentials in call_credentials))) 

1688 

1689 

1690def composite_channel_credentials(channel_credentials, *call_credentials): 

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

1692 

1693 Args: 

1694 channel_credentials: A ChannelCredentials object. 

1695 *call_credentials: One or more CallCredentials objects. 

1696 

1697 Returns: 

1698 A ChannelCredentials composed of the given ChannelCredentials and 

1699 CallCredentials objects. 

1700 """ 

1701 return ChannelCredentials( 

1702 _cygrpc.CompositeChannelCredentials( 

1703 tuple(single_call_credentials._credentials 

1704 for single_call_credentials in call_credentials), 

1705 channel_credentials._credentials)) 

1706 

1707 

1708def ssl_server_credentials(private_key_certificate_chain_pairs, 

1709 root_certificates=None, 

1710 require_client_auth=False): 

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

1712 

1713 Args: 

1714 private_key_certificate_chain_pairs: A list of pairs of the form 

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

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

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

1718 If omitted, require_client_auth must also be False. 

1719 require_client_auth: A boolean indicating whether or not to require 

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

1721 is not None. 

1722 

1723 Returns: 

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

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

1726 """ 

1727 if not private_key_certificate_chain_pairs: 

1728 raise ValueError( 

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

1730 elif require_client_auth and root_certificates is None: 

1731 raise ValueError( 

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

1733 ) 

1734 else: 

1735 return ServerCredentials( 

1736 _cygrpc.server_credentials_ssl(root_certificates, [ 

1737 _cygrpc.SslPemKeyCertPair(key, pem) 

1738 for key, pem in private_key_certificate_chain_pairs 

1739 ], require_client_auth)) 

1740 

1741 

1742def xds_server_credentials(fallback_credentials): 

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

1744 API. 

1745 

1746 Args: 

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

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

1749 """ 

1750 return ServerCredentials( 

1751 _cygrpc.xds_server_credentials(fallback_credentials._credentials)) 

1752 

1753 

1754def insecure_server_credentials(): 

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

1756 This is an EXPERIMENTAL API. 

1757 

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

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

1760 with xds_server_credentials. 

1761 """ 

1762 return ServerCredentials(_cygrpc.insecure_server_credentials()) 

1763 

1764 

1765def ssl_server_certificate_configuration(private_key_certificate_chain_pairs, 

1766 root_certificates=None): 

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

1768 

1769 Args: 

1770 private_key_certificate_chain_pairs: A collection of pairs of 

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

1772 chain]. 

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

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

1775 

1776 Returns: 

1777 A ServerCertificateConfiguration that can be returned in the certificate 

1778 configuration fetching callback. 

1779 """ 

1780 if private_key_certificate_chain_pairs: 

1781 return ServerCertificateConfiguration( 

1782 _cygrpc.server_certificate_config_ssl(root_certificates, [ 

1783 _cygrpc.SslPemKeyCertPair(key, pem) 

1784 for key, pem in private_key_certificate_chain_pairs 

1785 ])) 

1786 else: 

1787 raise ValueError( 

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

1789 

1790 

1791def dynamic_ssl_server_credentials(initial_certificate_configuration, 

1792 certificate_configuration_fetcher, 

1793 require_client_authentication=False): 

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

1795 

1796 Args: 

1797 initial_certificate_configuration (ServerCertificateConfiguration): The 

1798 certificate configuration with which the server will be initialized. 

1799 certificate_configuration_fetcher (callable): A callable that takes no 

1800 arguments and should return a ServerCertificateConfiguration to 

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

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

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

1804 client connection before starting the TLS handshake with the 

1805 client, thus allowing the user application to optionally 

1806 return a new ServerCertificateConfiguration that the server will then 

1807 use for the handshake. 

1808 require_client_authentication: A boolean indicating whether or not to 

1809 require clients to be authenticated. 

1810 

1811 Returns: 

1812 A ServerCredentials. 

1813 """ 

1814 return ServerCredentials( 

1815 _cygrpc.server_credentials_ssl_dynamic_cert_config( 

1816 initial_certificate_configuration, 

1817 certificate_configuration_fetcher, require_client_authentication)) 

1818 

1819 

1820@enum.unique 

1821class LocalConnectionType(enum.Enum): 

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

1823 

1824 Attributes: 

1825 UDS: Unix domain socket connections 

1826 LOCAL_TCP: Local TCP connections. 

1827 """ 

1828 UDS = _cygrpc.LocalConnectionType.uds 

1829 LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp 

1830 

1831 

1832def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 

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

1834 

1835 This is an EXPERIMENTAL API. 

1836 

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

1838 also UDS connections. 

1839 

1840 The connections created by local channel credentials are not 

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

1842 The UDS connections are considered secure by providing peer authentication 

1843 and data confidentiality while TCP connections are considered insecure. 

1844 

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

1846 local channel credentials. 

1847 

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

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

1850 

1851 Args: 

1852 local_connect_type: Local connection type (either 

1853 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 

1854 

1855 Returns: 

1856 A ChannelCredentials for use with a local Channel 

1857 """ 

1858 return ChannelCredentials( 

1859 _cygrpc.channel_credentials_local(local_connect_type.value)) 

1860 

1861 

1862def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): 

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

1864 

1865 This is an EXPERIMENTAL API. 

1866 

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

1868 also UDS connections. 

1869 

1870 The connections created by local server credentials are not 

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

1872 The UDS connections are considered secure by providing peer authentication 

1873 and data confidentiality while TCP connections are considered insecure. 

1874 

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

1876 server credentials. 

1877 

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

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

1880 

1881 Args: 

1882 local_connect_type: Local connection type (either 

1883 grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) 

1884 

1885 Returns: 

1886 A ServerCredentials for use with a local Server 

1887 """ 

1888 return ServerCredentials( 

1889 _cygrpc.server_credentials_local(local_connect_type.value)) 

1890 

1891 

1892def alts_channel_credentials(service_accounts=None): 

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

1894 

1895 This is an EXPERIMENTAL API. 

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

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

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

1899 

1900 Args: 

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

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

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

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

1905 identity. 

1906 Returns: 

1907 A ChannelCredentials for use with an ALTS-enabled Channel 

1908 """ 

1909 return ChannelCredentials( 

1910 _cygrpc.channel_credentials_alts(service_accounts or [])) 

1911 

1912 

1913def alts_server_credentials(): 

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

1915 

1916 This is an EXPERIMENTAL API. 

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

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

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

1920 

1921 Returns: 

1922 A ServerCredentials for use with an ALTS-enabled Server 

1923 """ 

1924 return ServerCredentials(_cygrpc.server_credentials_alts()) 

1925 

1926 

1927def compute_engine_channel_credentials(call_credentials): 

1928 """Creates a compute engine channel credential. 

1929 

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

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

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

1933 

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

1935 credential in conjunction with a call credentials that authenticates the 

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

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

1938 """ 

1939 return ChannelCredentials( 

1940 _cygrpc.channel_credentials_compute_engine( 

1941 call_credentials._credentials)) 

1942 

1943 

1944def channel_ready_future(channel): 

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

1946 

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

1948 It merely decouples the Future from channel state machine. 

1949 

1950 Args: 

1951 channel: A Channel object. 

1952 

1953 Returns: 

1954 A Future object that matures when the channel connectivity is 

1955 ChannelConnectivity.READY. 

1956 """ 

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

1958 return _utilities.channel_ready_future(channel) 

1959 

1960 

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

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

1963 

1964 The returned Channel is thread-safe. 

1965 

1966 Args: 

1967 target: The server address 

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

1969 in gRPC Core runtime) to configure the channel. 

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

1971 used over the lifetime of the channel. This is an EXPERIMENTAL option. 

1972 

1973 Returns: 

1974 A Channel. 

1975 """ 

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

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

1978 compression) 

1979 

1980 

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

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

1983 

1984 The returned Channel is thread-safe. 

1985 

1986 Args: 

1987 target: The server address. 

1988 credentials: A ChannelCredentials instance. 

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

1990 in gRPC Core runtime) to configure the channel. 

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

1992 used over the lifetime of the channel. This is an EXPERIMENTAL option. 

1993 

1994 Returns: 

1995 A Channel. 

1996 """ 

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

1998 from grpc.experimental import _insecure_channel_credentials 

1999 if credentials._credentials is _insecure_channel_credentials: 

2000 raise ValueError( 

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

2002 " Call insecure_channel instead.") 

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

2004 credentials._credentials, compression) 

2005 

2006 

2007def intercept_channel(channel, *interceptors): 

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

2009 

2010 Args: 

2011 channel: A Channel. 

2012 interceptors: Zero or more objects of type 

2013 UnaryUnaryClientInterceptor, 

2014 UnaryStreamClientInterceptor, 

2015 StreamUnaryClientInterceptor, or 

2016 StreamStreamClientInterceptor. 

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

2018 

2019 Returns: 

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

2021 

2022 Raises: 

2023 TypeError: If interceptor does not derive from any of 

2024 UnaryUnaryClientInterceptor, 

2025 UnaryStreamClientInterceptor, 

2026 StreamUnaryClientInterceptor, or 

2027 StreamStreamClientInterceptor. 

2028 """ 

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

2030 return _interceptor.intercept_channel(channel, *interceptors) 

2031 

2032 

2033def server(thread_pool, 

2034 handlers=None, 

2035 interceptors=None, 

2036 options=None, 

2037 maximum_concurrent_rpcs=None, 

2038 compression=None, 

2039 xds=False): 

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

2041 

2042 Args: 

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

2044 to execute RPC handlers. 

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

2046 More handlers may be added by calling add_generic_rpc_handlers any time 

2047 before the server is started. 

2048 interceptors: An optional list of ServerInterceptor objects that observe 

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

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

2051 specified. This is an EXPERIMENTAL API. 

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

2053 to configure the channel. 

2054 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server 

2055 will service before returning RESOURCE_EXHAUSTED status, or None to 

2056 indicate no limit. 

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

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

2059 lifetime of the server unless overridden. This is an EXPERIMENTAL option. 

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

2061 EXPERIMENTAL option. 

2062 

2063 Returns: 

2064 A Server object. 

2065 """ 

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

2067 return _server.create_server(thread_pool, 

2068 () if handlers is None else handlers, 

2069 () if interceptors is None else interceptors, 

2070 () if options is None else options, 

2071 maximum_concurrent_rpcs, compression, xds) 

2072 

2073 

2074@contextlib.contextmanager 

2075def _create_servicer_context(rpc_event, state, request_deserializer): 

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

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

2078 yield context 

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

2080 

2081 

2082@enum.unique 

2083class Compression(enum.IntEnum): 

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

2085 

2086 This enumeration is part of an EXPERIMENTAL API. 

2087 

2088 Attributes: 

2089 NoCompression: Do not use compression algorithm. 

2090 Deflate: Use "Deflate" compression algorithm. 

2091 Gzip: Use "Gzip" compression algorithm. 

2092 """ 

2093 NoCompression = _compression.NoCompression 

2094 Deflate = _compression.Deflate 

2095 Gzip = _compression.Gzip 

2096 

2097 

2098################################### __all__ ################################# 

2099 

2100__all__ = ( 

2101 'FutureTimeoutError', 

2102 'FutureCancelledError', 

2103 'Future', 

2104 'ChannelConnectivity', 

2105 'StatusCode', 

2106 'Status', 

2107 'RpcError', 

2108 'RpcContext', 

2109 'Call', 

2110 'ChannelCredentials', 

2111 'CallCredentials', 

2112 'AuthMetadataContext', 

2113 'AuthMetadataPluginCallback', 

2114 'AuthMetadataPlugin', 

2115 'Compression', 

2116 'ClientCallDetails', 

2117 'ServerCertificateConfiguration', 

2118 'ServerCredentials', 

2119 'LocalConnectionType', 

2120 'UnaryUnaryMultiCallable', 

2121 'UnaryStreamMultiCallable', 

2122 'StreamUnaryMultiCallable', 

2123 'StreamStreamMultiCallable', 

2124 'UnaryUnaryClientInterceptor', 

2125 'UnaryStreamClientInterceptor', 

2126 'StreamUnaryClientInterceptor', 

2127 'StreamStreamClientInterceptor', 

2128 'Channel', 

2129 'ServicerContext', 

2130 'RpcMethodHandler', 

2131 'HandlerCallDetails', 

2132 'GenericRpcHandler', 

2133 'ServiceRpcHandler', 

2134 'Server', 

2135 'ServerInterceptor', 

2136 'unary_unary_rpc_method_handler', 

2137 'unary_stream_rpc_method_handler', 

2138 'stream_unary_rpc_method_handler', 

2139 'stream_stream_rpc_method_handler', 

2140 'method_handlers_generic_handler', 

2141 'ssl_channel_credentials', 

2142 'metadata_call_credentials', 

2143 'access_token_call_credentials', 

2144 'composite_call_credentials', 

2145 'composite_channel_credentials', 

2146 'compute_engine_channel_credentials', 

2147 'local_channel_credentials', 

2148 'local_server_credentials', 

2149 'alts_channel_credentials', 

2150 'alts_server_credentials', 

2151 'ssl_server_credentials', 

2152 'ssl_server_certificate_configuration', 

2153 'dynamic_ssl_server_credentials', 

2154 'channel_ready_future', 

2155 'insecure_channel', 

2156 'secure_channel', 

2157 'intercept_channel', 

2158 'server', 

2159 'protos', 

2160 'services', 

2161 'protos_and_services', 

2162 'xds_channel_credentials', 

2163 'xds_server_credentials', 

2164 'insecure_server_credentials', 

2165) 

2166 

2167############################### Extension Shims ################################ 

2168 

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

2170try: 

2171 import grpc_tools 

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

2173except ImportError: 

2174 pass 

2175try: 

2176 import grpc_health 

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

2178except ImportError: 

2179 pass 

2180try: 

2181 import grpc_reflection 

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

2183except ImportError: 

2184 pass 

2185 

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

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

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

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