grpcio-fips 1.44.0__4-cp310-cp310-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. grpc/__init__.py +2190 -0
  2. grpc/_auth.py +58 -0
  3. grpc/_channel.py +1581 -0
  4. grpc/_common.py +168 -0
  5. grpc/_compression.py +55 -0
  6. grpc/_cython/__init__.py +13 -0
  7. grpc/_cython/_credentials/roots.pem +4337 -0
  8. grpc/_cython/_cygrpc/__init__.py +13 -0
  9. grpc/_cython/ayx-crypto-library.dll +0 -0
  10. grpc/_cython/cygrpc.cp310-win_amd64.pyd +0 -0
  11. grpc/_cython/libcrypto-3-x64.dll +0 -0
  12. grpc/_cython/libssl-3-x64.dll +0 -0
  13. grpc/_grpcio_metadata.py +1 -0
  14. grpc/_interceptor.py +562 -0
  15. grpc/_plugin_wrapping.py +113 -0
  16. grpc/_runtime_protos.py +155 -0
  17. grpc/_server.py +1003 -0
  18. grpc/_simple_stubs.py +486 -0
  19. grpc/_utilities.py +168 -0
  20. grpc/aio/__init__.py +95 -0
  21. grpc/aio/_base_call.py +248 -0
  22. grpc/aio/_base_channel.py +352 -0
  23. grpc/aio/_base_server.py +373 -0
  24. grpc/aio/_call.py +648 -0
  25. grpc/aio/_channel.py +484 -0
  26. grpc/aio/_interceptor.py +1004 -0
  27. grpc/aio/_metadata.py +120 -0
  28. grpc/aio/_server.py +210 -0
  29. grpc/aio/_typing.py +35 -0
  30. grpc/aio/_utils.py +22 -0
  31. grpc/beta/__init__.py +13 -0
  32. grpc/beta/_client_adaptations.py +706 -0
  33. grpc/beta/_metadata.py +52 -0
  34. grpc/beta/_server_adaptations.py +385 -0
  35. grpc/beta/implementations.py +311 -0
  36. grpc/beta/interfaces.py +164 -0
  37. grpc/beta/utilities.py +149 -0
  38. grpc/experimental/__init__.py +128 -0
  39. grpc/experimental/aio/__init__.py +16 -0
  40. grpc/experimental/gevent.py +27 -0
  41. grpc/experimental/session_cache.py +45 -0
  42. grpc/framework/__init__.py +13 -0
  43. grpc/framework/common/__init__.py +13 -0
  44. grpc/framework/common/cardinality.py +26 -0
  45. grpc/framework/common/style.py +24 -0
  46. grpc/framework/foundation/__init__.py +13 -0
  47. grpc/framework/foundation/abandonment.py +22 -0
  48. grpc/framework/foundation/callable_util.py +96 -0
  49. grpc/framework/foundation/future.py +221 -0
  50. grpc/framework/foundation/logging_pool.py +71 -0
  51. grpc/framework/foundation/stream.py +45 -0
  52. grpc/framework/foundation/stream_util.py +148 -0
  53. grpc/framework/interfaces/__init__.py +13 -0
  54. grpc/framework/interfaces/base/__init__.py +13 -0
  55. grpc/framework/interfaces/base/base.py +327 -0
  56. grpc/framework/interfaces/base/utilities.py +71 -0
  57. grpc/framework/interfaces/face/__init__.py +13 -0
  58. grpc/framework/interfaces/face/face.py +1050 -0
  59. grpc/framework/interfaces/face/utilities.py +168 -0
  60. grpcio_fips-1.44.0.dist-info/LICENSE +242 -0
  61. grpcio_fips-1.44.0.dist-info/METADATA +141 -0
  62. grpcio_fips-1.44.0.dist-info/RECORD +64 -0
  63. grpcio_fips-1.44.0.dist-info/WHEEL +5 -0
  64. grpcio_fips-1.44.0.dist-info/top_level.txt +1 -0
grpc/__init__.py ADDED
@@ -0,0 +1,2190 @@
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
+
16
+ import abc
17
+ import contextlib
18
+ import enum
19
+ import logging
20
+ import sys
21
+
22
+ from grpc import _compression
23
+ from grpc._cython import cygrpc as _cygrpc
24
+ from grpc._runtime_protos import protos
25
+ from grpc._runtime_protos import protos_and_services
26
+ from grpc._runtime_protos import services
27
+ import six
28
+
29
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
30
+
31
+ try:
32
+ # pylint: disable=ungrouped-imports
33
+ from grpc._grpcio_metadata import __version__
34
+ except ImportError:
35
+ __version__ = "dev0"
36
+
37
+ ############################## Future Interface ###############################
38
+
39
+
40
+ class FutureTimeoutError(Exception):
41
+ """Indicates that a method call on a Future timed out."""
42
+
43
+
44
+ class FutureCancelledError(Exception):
45
+ """Indicates that the computation underlying a Future was cancelled."""
46
+
47
+
48
+ class Future(six.with_metaclass(abc.ABCMeta)):
49
+ """A representation of a computation in another control flow.
50
+
51
+ Computations represented by a Future may be yet to be begun,
52
+ may be ongoing, or may have already completed.
53
+ """
54
+
55
+ @abc.abstractmethod
56
+ def cancel(self):
57
+ """Attempts to cancel the computation.
58
+
59
+ This method does not block.
60
+
61
+ Returns:
62
+ bool:
63
+ Returns True if the computation was canceled.
64
+
65
+ Returns False under all other circumstances, for example:
66
+
67
+ 1. computation has begun and could not be canceled.
68
+ 2. computation has finished
69
+ 3. computation is scheduled for execution and it is impossible
70
+ to determine its state without blocking.
71
+ """
72
+ raise NotImplementedError()
73
+
74
+ @abc.abstractmethod
75
+ def cancelled(self):
76
+ """Describes whether the computation was cancelled.
77
+
78
+ This method does not block.
79
+
80
+ Returns:
81
+ bool:
82
+ Returns True if the computation was cancelled before its result became
83
+ available.
84
+
85
+ Returns False under all other circumstances, for example:
86
+
87
+ 1. computation was not cancelled.
88
+ 2. computation's result is available.
89
+ """
90
+ raise NotImplementedError()
91
+
92
+ @abc.abstractmethod
93
+ def running(self):
94
+ """Describes whether the computation is taking place.
95
+
96
+ This method does not block.
97
+
98
+ Returns:
99
+ Returns True if the computation is scheduled for execution or
100
+ currently executing.
101
+
102
+ Returns False if the computation already executed or was cancelled.
103
+ """
104
+ raise NotImplementedError()
105
+
106
+ @abc.abstractmethod
107
+ def done(self):
108
+ """Describes whether the computation has taken place.
109
+
110
+ This method does not block.
111
+
112
+ Returns:
113
+ bool:
114
+ Returns True if the computation already executed or was cancelled.
115
+ Returns False if the computation is scheduled for execution or
116
+ currently executing.
117
+ This is exactly opposite of the running() method's result.
118
+ """
119
+ raise NotImplementedError()
120
+
121
+ @abc.abstractmethod
122
+ def result(self, timeout=None):
123
+ """Returns the result of the computation or raises its exception.
124
+
125
+ This method may return immediately or may block.
126
+
127
+ Args:
128
+ timeout: The length of time in seconds to wait for the computation to
129
+ finish or be cancelled. If None, the call will block until the
130
+ computations's termination.
131
+
132
+ Returns:
133
+ The return value of the computation.
134
+
135
+ Raises:
136
+ FutureTimeoutError: If a timeout value is passed and the computation
137
+ does not terminate within the allotted time.
138
+ FutureCancelledError: If the computation was cancelled.
139
+ Exception: If the computation raised an exception, this call will
140
+ raise the same exception.
141
+ """
142
+ raise NotImplementedError()
143
+
144
+ @abc.abstractmethod
145
+ def exception(self, timeout=None):
146
+ """Return the exception raised by the computation.
147
+
148
+ This method may return immediately or may block.
149
+
150
+ Args:
151
+ timeout: The length of time in seconds to wait for the computation to
152
+ terminate or be cancelled. If None, the call will block until the
153
+ computations's termination.
154
+
155
+ Returns:
156
+ The exception raised by the computation, or None if the computation
157
+ did not raise an exception.
158
+
159
+ Raises:
160
+ FutureTimeoutError: If a timeout value is passed and the computation
161
+ does not terminate within the allotted time.
162
+ FutureCancelledError: If the computation was cancelled.
163
+ """
164
+ raise NotImplementedError()
165
+
166
+ @abc.abstractmethod
167
+ def traceback(self, timeout=None):
168
+ """Access the traceback of the exception raised by the computation.
169
+
170
+ This method may return immediately or may block.
171
+
172
+ Args:
173
+ timeout: The length of time in seconds to wait for the computation
174
+ to terminate or be cancelled. If None, the call will block until
175
+ the computation's termination.
176
+
177
+ Returns:
178
+ The traceback of the exception raised by the computation, or None
179
+ if the computation did not raise an exception.
180
+
181
+ Raises:
182
+ FutureTimeoutError: If a timeout value is passed and the computation
183
+ does not terminate within the allotted time.
184
+ FutureCancelledError: If the computation was cancelled.
185
+ """
186
+ raise NotImplementedError()
187
+
188
+ @abc.abstractmethod
189
+ def add_done_callback(self, fn):
190
+ """Adds a function to be called at completion of the computation.
191
+
192
+ The callback will be passed this Future object describing the outcome
193
+ of the computation. Callbacks will be invoked after the future is
194
+ terminated, whether successfully or not.
195
+
196
+ If the computation has already completed, the callback will be called
197
+ immediately.
198
+
199
+ Exceptions raised in the callback will be logged at ERROR level, but
200
+ will not terminate any threads of execution.
201
+
202
+ Args:
203
+ fn: A callable taking this Future object as its single parameter.
204
+ """
205
+ raise NotImplementedError()
206
+
207
+
208
+ ################################ gRPC Enums ##################################
209
+
210
+
211
+ @enum.unique
212
+ class ChannelConnectivity(enum.Enum):
213
+ """Mirrors grpc_connectivity_state in the gRPC Core.
214
+
215
+ Attributes:
216
+ IDLE: The channel is idle.
217
+ CONNECTING: The channel is connecting.
218
+ READY: The channel is ready to conduct RPCs.
219
+ TRANSIENT_FAILURE: The channel has seen a failure from which it expects
220
+ to recover.
221
+ SHUTDOWN: The channel has seen a failure from which it cannot recover.
222
+ """
223
+ IDLE = (_cygrpc.ConnectivityState.idle, 'idle')
224
+ CONNECTING = (_cygrpc.ConnectivityState.connecting, 'connecting')
225
+ READY = (_cygrpc.ConnectivityState.ready, 'ready')
226
+ TRANSIENT_FAILURE = (_cygrpc.ConnectivityState.transient_failure,
227
+ 'transient failure')
228
+ SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, 'shutdown')
229
+
230
+
231
+ @enum.unique
232
+ class StatusCode(enum.Enum):
233
+ """Mirrors grpc_status_code in the gRPC Core.
234
+
235
+ Attributes:
236
+ OK: Not an error; returned on success
237
+ CANCELLED: The operation was cancelled (typically by the caller).
238
+ UNKNOWN: Unknown error.
239
+ INVALID_ARGUMENT: Client specified an invalid argument.
240
+ DEADLINE_EXCEEDED: Deadline expired before operation could complete.
241
+ NOT_FOUND: Some requested entity (e.g., file or directory) was not found.
242
+ ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory)
243
+ already exists.
244
+ PERMISSION_DENIED: The caller does not have permission to execute the specified
245
+ operation.
246
+ UNAUTHENTICATED: The request does not have valid authentication credentials for the
247
+ operation.
248
+ RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or
249
+ perhaps the entire file system is out of space.
250
+ FAILED_PRECONDITION: Operation was rejected because the system is not in a state
251
+ required for the operation's execution.
252
+ ABORTED: The operation was aborted, typically due to a concurrency issue
253
+ like sequencer check failures, transaction aborts, etc.
254
+ UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service.
255
+ INTERNAL: Internal errors. Means some invariants expected by underlying
256
+ system has been broken.
257
+ UNAVAILABLE: The service is currently unavailable.
258
+ DATA_LOSS: Unrecoverable data loss or corruption.
259
+ """
260
+ OK = (_cygrpc.StatusCode.ok, 'ok')
261
+ CANCELLED = (_cygrpc.StatusCode.cancelled, 'cancelled')
262
+ UNKNOWN = (_cygrpc.StatusCode.unknown, 'unknown')
263
+ INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, 'invalid argument')
264
+ DEADLINE_EXCEEDED = (_cygrpc.StatusCode.deadline_exceeded,
265
+ 'deadline exceeded')
266
+ NOT_FOUND = (_cygrpc.StatusCode.not_found, 'not found')
267
+ ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, 'already exists')
268
+ PERMISSION_DENIED = (_cygrpc.StatusCode.permission_denied,
269
+ 'permission denied')
270
+ RESOURCE_EXHAUSTED = (_cygrpc.StatusCode.resource_exhausted,
271
+ 'resource exhausted')
272
+ FAILED_PRECONDITION = (_cygrpc.StatusCode.failed_precondition,
273
+ 'failed precondition')
274
+ ABORTED = (_cygrpc.StatusCode.aborted, 'aborted')
275
+ OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, 'out of range')
276
+ UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, 'unimplemented')
277
+ INTERNAL = (_cygrpc.StatusCode.internal, 'internal')
278
+ UNAVAILABLE = (_cygrpc.StatusCode.unavailable, 'unavailable')
279
+ DATA_LOSS = (_cygrpc.StatusCode.data_loss, 'data loss')
280
+ UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, 'unauthenticated')
281
+
282
+
283
+ ############################# gRPC Status ################################
284
+
285
+
286
+ class Status(six.with_metaclass(abc.ABCMeta)):
287
+ """Describes the status of an RPC.
288
+
289
+ This is an EXPERIMENTAL API.
290
+
291
+ Attributes:
292
+ code: A StatusCode object to be sent to the client.
293
+ details: A UTF-8-encodable string to be sent to the client upon
294
+ termination of the RPC.
295
+ trailing_metadata: The trailing :term:`metadata` in the RPC.
296
+ """
297
+
298
+
299
+ ############################# gRPC Exceptions ################################
300
+
301
+
302
+ class RpcError(Exception):
303
+ """Raised by the gRPC library to indicate non-OK-status RPC termination."""
304
+
305
+
306
+ ############################## Shared Context ################################
307
+
308
+
309
+ class RpcContext(six.with_metaclass(abc.ABCMeta)):
310
+ """Provides RPC-related information and action."""
311
+
312
+ @abc.abstractmethod
313
+ def is_active(self):
314
+ """Describes whether the RPC is active or has terminated.
315
+
316
+ Returns:
317
+ bool:
318
+ True if RPC is active, False otherwise.
319
+ """
320
+ raise NotImplementedError()
321
+
322
+ @abc.abstractmethod
323
+ def time_remaining(self):
324
+ """Describes the length of allowed time remaining for the RPC.
325
+
326
+ Returns:
327
+ A nonnegative float indicating the length of allowed time in seconds
328
+ remaining for the RPC to complete before it is considered to have
329
+ timed out, or None if no deadline was specified for the RPC.
330
+ """
331
+ raise NotImplementedError()
332
+
333
+ @abc.abstractmethod
334
+ def cancel(self):
335
+ """Cancels the RPC.
336
+
337
+ Idempotent and has no effect if the RPC has already terminated.
338
+ """
339
+ raise NotImplementedError()
340
+
341
+ @abc.abstractmethod
342
+ def add_callback(self, callback):
343
+ """Registers a callback to be called on RPC termination.
344
+
345
+ Args:
346
+ callback: A no-parameter callable to be called on RPC termination.
347
+
348
+ Returns:
349
+ True if the callback was added and will be called later; False if
350
+ the callback was not added and will not be called (because the RPC
351
+ already terminated or some other reason).
352
+ """
353
+ raise NotImplementedError()
354
+
355
+
356
+ ######################### Invocation-Side Context ############################
357
+
358
+
359
+ class Call(six.with_metaclass(abc.ABCMeta, RpcContext)):
360
+ """Invocation-side utility object for an RPC."""
361
+
362
+ @abc.abstractmethod
363
+ def initial_metadata(self):
364
+ """Accesses the initial metadata sent by the server.
365
+
366
+ This method blocks until the value is available.
367
+
368
+ Returns:
369
+ The initial :term:`metadata`.
370
+ """
371
+ raise NotImplementedError()
372
+
373
+ @abc.abstractmethod
374
+ def trailing_metadata(self):
375
+ """Accesses the trailing metadata sent by the server.
376
+
377
+ This method blocks until the value is available.
378
+
379
+ Returns:
380
+ The trailing :term:`metadata`.
381
+ """
382
+ raise NotImplementedError()
383
+
384
+ @abc.abstractmethod
385
+ def code(self):
386
+ """Accesses the status code sent by the server.
387
+
388
+ This method blocks until the value is available.
389
+
390
+ Returns:
391
+ The StatusCode value for the RPC.
392
+ """
393
+ raise NotImplementedError()
394
+
395
+ @abc.abstractmethod
396
+ def details(self):
397
+ """Accesses the details sent by the server.
398
+
399
+ This method blocks until the value is available.
400
+
401
+ Returns:
402
+ The details string of the RPC.
403
+ """
404
+ raise NotImplementedError()
405
+
406
+
407
+ ############## Invocation-Side Interceptor Interfaces & Classes ##############
408
+
409
+
410
+ class ClientCallDetails(six.with_metaclass(abc.ABCMeta)):
411
+ """Describes an RPC to be invoked.
412
+
413
+ Attributes:
414
+ method: The method name of the RPC.
415
+ timeout: An optional duration of time in seconds to allow for the RPC.
416
+ metadata: Optional :term:`metadata` to be transmitted to
417
+ the service-side of the RPC.
418
+ credentials: An optional CallCredentials for the RPC.
419
+ wait_for_ready: This is an EXPERIMENTAL argument. An optional
420
+ flag to enable :term:`wait_for_ready` mechanism.
421
+ compression: An element of grpc.compression, e.g.
422
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
423
+ """
424
+
425
+
426
+ class UnaryUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
427
+ """Affords intercepting unary-unary invocations."""
428
+
429
+ @abc.abstractmethod
430
+ def intercept_unary_unary(self, continuation, client_call_details, request):
431
+ """Intercepts a unary-unary invocation asynchronously.
432
+
433
+ Args:
434
+ continuation: A function that proceeds with the invocation by
435
+ executing the next interceptor in chain or invoking the
436
+ actual RPC on the underlying Channel. It is the interceptor's
437
+ responsibility to call it if it decides to move the RPC forward.
438
+ The interceptor can use
439
+ `response_future = continuation(client_call_details, request)`
440
+ to continue with the RPC. `continuation` returns an object that is
441
+ both a Call for the RPC and a Future. In the event of RPC
442
+ completion, the return Call-Future's result value will be
443
+ the response message of the RPC. Should the event terminate
444
+ with non-OK status, the returned Call-Future's exception value
445
+ will be an RpcError.
446
+ client_call_details: A ClientCallDetails object describing the
447
+ outgoing RPC.
448
+ request: The request value for the RPC.
449
+
450
+ Returns:
451
+ An object that is both a Call for the RPC and a Future.
452
+ In the event of RPC completion, the return Call-Future's
453
+ result value will be the response message of the RPC.
454
+ Should the event terminate with non-OK status, the returned
455
+ Call-Future's exception value will be an RpcError.
456
+ """
457
+ raise NotImplementedError()
458
+
459
+
460
+ class UnaryStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
461
+ """Affords intercepting unary-stream invocations."""
462
+
463
+ @abc.abstractmethod
464
+ def intercept_unary_stream(self, continuation, client_call_details,
465
+ request):
466
+ """Intercepts a unary-stream invocation.
467
+
468
+ Args:
469
+ continuation: A function that proceeds with the invocation by
470
+ executing the next interceptor in chain or invoking the
471
+ actual RPC on the underlying Channel. It is the interceptor's
472
+ responsibility to call it if it decides to move the RPC forward.
473
+ The interceptor can use
474
+ `response_iterator = continuation(client_call_details, request)`
475
+ to continue with the RPC. `continuation` returns an object that is
476
+ both a Call for the RPC and an iterator for response values.
477
+ Drawing response values from the returned Call-iterator may
478
+ raise RpcError indicating termination of the RPC with non-OK
479
+ status.
480
+ client_call_details: A ClientCallDetails object describing the
481
+ outgoing RPC.
482
+ request: The request value for the RPC.
483
+
484
+ Returns:
485
+ An object that is both a Call for the RPC and an iterator of
486
+ response values. Drawing response values from the returned
487
+ Call-iterator may raise RpcError indicating termination of
488
+ the RPC with non-OK status. This object *should* also fulfill the
489
+ Future interface, though it may not.
490
+ """
491
+ raise NotImplementedError()
492
+
493
+
494
+ class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
495
+ """Affords intercepting stream-unary invocations."""
496
+
497
+ @abc.abstractmethod
498
+ def intercept_stream_unary(self, continuation, client_call_details,
499
+ request_iterator):
500
+ """Intercepts a stream-unary invocation asynchronously.
501
+
502
+ Args:
503
+ continuation: A function that proceeds with the invocation by
504
+ executing the next interceptor in chain or invoking the
505
+ actual RPC on the underlying Channel. It is the interceptor's
506
+ responsibility to call it if it decides to move the RPC forward.
507
+ The interceptor can use
508
+ `response_future = continuation(client_call_details, request_iterator)`
509
+ to continue with the RPC. `continuation` returns an object that is
510
+ both a Call for the RPC and a Future. In the event of RPC completion,
511
+ the return Call-Future's result value will be the response message
512
+ of the RPC. Should the event terminate with non-OK status, the
513
+ returned Call-Future's exception value will be an RpcError.
514
+ client_call_details: A ClientCallDetails object describing the
515
+ outgoing RPC.
516
+ request_iterator: An iterator that yields request values for the RPC.
517
+
518
+ Returns:
519
+ An object that is both a Call for the RPC and a Future.
520
+ In the event of RPC completion, the return Call-Future's
521
+ result value will be the response message of the RPC.
522
+ Should the event terminate with non-OK status, the returned
523
+ Call-Future's exception value will be an RpcError.
524
+ """
525
+ raise NotImplementedError()
526
+
527
+
528
+ class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
529
+ """Affords intercepting stream-stream invocations."""
530
+
531
+ @abc.abstractmethod
532
+ def intercept_stream_stream(self, continuation, client_call_details,
533
+ request_iterator):
534
+ """Intercepts a stream-stream invocation.
535
+
536
+ Args:
537
+ continuation: A function that proceeds with the invocation by
538
+ executing the next interceptor in chain or invoking the
539
+ actual RPC on the underlying Channel. It is the interceptor's
540
+ responsibility to call it if it decides to move the RPC forward.
541
+ The interceptor can use
542
+ `response_iterator = continuation(client_call_details, request_iterator)`
543
+ to continue with the RPC. `continuation` returns an object that is
544
+ both a Call for the RPC and an iterator for response values.
545
+ Drawing response values from the returned Call-iterator may
546
+ raise RpcError indicating termination of the RPC with non-OK
547
+ status.
548
+ client_call_details: A ClientCallDetails object describing the
549
+ outgoing RPC.
550
+ request_iterator: An iterator that yields request values for the RPC.
551
+
552
+ Returns:
553
+ An object that is both a Call for the RPC and an iterator of
554
+ response values. Drawing response values from the returned
555
+ Call-iterator may raise RpcError indicating termination of
556
+ the RPC with non-OK status. This object *should* also fulfill the
557
+ Future interface, though it may not.
558
+ """
559
+ raise NotImplementedError()
560
+
561
+
562
+ ############ Authentication & Authorization Interfaces & Classes #############
563
+
564
+
565
+ class ChannelCredentials(object):
566
+ """An encapsulation of the data required to create a secure Channel.
567
+
568
+ This class has no supported interface - it exists to define the type of its
569
+ instances and its instances exist to be passed to other functions. For
570
+ example, ssl_channel_credentials returns an instance of this class and
571
+ secure_channel requires an instance of this class.
572
+ """
573
+
574
+ def __init__(self, credentials):
575
+ self._credentials = credentials
576
+
577
+
578
+ class CallCredentials(object):
579
+ """An encapsulation of the data required to assert an identity over a call.
580
+
581
+ A CallCredentials has to be used with secure Channel, otherwise the
582
+ metadata will not be transmitted to the server.
583
+
584
+ A CallCredentials may be composed with ChannelCredentials to always assert
585
+ identity for every call over that Channel.
586
+
587
+ This class has no supported interface - it exists to define the type of its
588
+ instances and its instances exist to be passed to other functions.
589
+ """
590
+
591
+ def __init__(self, credentials):
592
+ self._credentials = credentials
593
+
594
+
595
+ class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
596
+ """Provides information to call credentials metadata plugins.
597
+
598
+ Attributes:
599
+ service_url: A string URL of the service being called into.
600
+ method_name: A string of the fully qualified method name being called.
601
+ """
602
+
603
+
604
+ class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)):
605
+ """Callback object received by a metadata plugin."""
606
+
607
+ def __call__(self, metadata, error):
608
+ """Passes to the gRPC runtime authentication metadata for an RPC.
609
+
610
+ Args:
611
+ metadata: The :term:`metadata` used to construct the CallCredentials.
612
+ error: An Exception to indicate error or None to indicate success.
613
+ """
614
+ raise NotImplementedError()
615
+
616
+
617
+ class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
618
+ """A specification for custom authentication."""
619
+
620
+ def __call__(self, context, callback):
621
+ """Implements authentication by passing metadata to a callback.
622
+
623
+ This method will be invoked asynchronously in a separate thread.
624
+
625
+ Args:
626
+ context: An AuthMetadataContext providing information on the RPC that
627
+ the plugin is being called to authenticate.
628
+ callback: An AuthMetadataPluginCallback to be invoked either
629
+ synchronously or asynchronously.
630
+ """
631
+ raise NotImplementedError()
632
+
633
+
634
+ class ServerCredentials(object):
635
+ """An encapsulation of the data required to open a secure port on a Server.
636
+
637
+ This class has no supported interface - it exists to define the type of its
638
+ instances and its instances exist to be passed to other functions.
639
+ """
640
+
641
+ def __init__(self, credentials):
642
+ self._credentials = credentials
643
+
644
+
645
+ class ServerCertificateConfiguration(object):
646
+ """A certificate configuration for use with an SSL-enabled Server.
647
+
648
+ Instances of this class can be returned in the certificate configuration
649
+ fetching callback.
650
+
651
+ This class has no supported interface -- it exists to define the
652
+ type of its instances and its instances exist to be passed to
653
+ other functions.
654
+ """
655
+
656
+ def __init__(self, certificate_configuration):
657
+ self._certificate_configuration = certificate_configuration
658
+
659
+
660
+ ######################## Multi-Callable Interfaces ###########################
661
+
662
+
663
+ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
664
+ """Affords invoking a unary-unary RPC from client-side."""
665
+
666
+ @abc.abstractmethod
667
+ def __call__(self,
668
+ request,
669
+ timeout=None,
670
+ metadata=None,
671
+ credentials=None,
672
+ wait_for_ready=None,
673
+ compression=None):
674
+ """Synchronously invokes the underlying RPC.
675
+
676
+ Args:
677
+ request: The request value for the RPC.
678
+ timeout: An optional duration of time in seconds to allow
679
+ for the RPC.
680
+ metadata: Optional :term:`metadata` to be transmitted to the
681
+ service-side of the RPC.
682
+ credentials: An optional CallCredentials for the RPC. Only valid for
683
+ secure Channel.
684
+ wait_for_ready: This is an EXPERIMENTAL argument. An optional
685
+ flag to enable :term:`wait_for_ready` mechanism.
686
+ compression: An element of grpc.compression, e.g.
687
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
688
+
689
+ Returns:
690
+ The response value for the RPC.
691
+
692
+ Raises:
693
+ RpcError: Indicating that the RPC terminated with non-OK status. The
694
+ raised RpcError will also be a Call for the RPC affording the RPC's
695
+ metadata, status code, and details.
696
+ """
697
+ raise NotImplementedError()
698
+
699
+ @abc.abstractmethod
700
+ def with_call(self,
701
+ request,
702
+ timeout=None,
703
+ metadata=None,
704
+ credentials=None,
705
+ wait_for_ready=None,
706
+ compression=None):
707
+ """Synchronously invokes the underlying RPC.
708
+
709
+ Args:
710
+ request: The request value for the RPC.
711
+ timeout: An optional durating of time in seconds to allow for
712
+ the RPC.
713
+ metadata: Optional :term:`metadata` to be transmitted to the
714
+ service-side of the RPC.
715
+ credentials: An optional CallCredentials for the RPC. Only valid for
716
+ secure Channel.
717
+ wait_for_ready: This is an EXPERIMENTAL argument. An optional
718
+ flag to enable :term:`wait_for_ready` mechanism.
719
+ compression: An element of grpc.compression, e.g.
720
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
721
+
722
+ Returns:
723
+ The response value for the RPC and a Call value for the RPC.
724
+
725
+ Raises:
726
+ RpcError: Indicating that the RPC terminated with non-OK status. The
727
+ raised RpcError will also be a Call for the RPC affording the RPC's
728
+ metadata, status code, and details.
729
+ """
730
+ raise NotImplementedError()
731
+
732
+ @abc.abstractmethod
733
+ def future(self,
734
+ request,
735
+ timeout=None,
736
+ metadata=None,
737
+ credentials=None,
738
+ wait_for_ready=None,
739
+ compression=None):
740
+ """Asynchronously invokes the underlying RPC.
741
+
742
+ Args:
743
+ request: The request value for the RPC.
744
+ timeout: An optional duration of time in seconds to allow for
745
+ the RPC.
746
+ metadata: Optional :term:`metadata` to be transmitted to the
747
+ service-side of the RPC.
748
+ credentials: An optional CallCredentials for the RPC. Only valid for
749
+ secure Channel.
750
+ wait_for_ready: This is an EXPERIMENTAL argument. An optional
751
+ flag to enable :term:`wait_for_ready` mechanism.
752
+ compression: An element of grpc.compression, e.g.
753
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
754
+
755
+ Returns:
756
+ An object that is both a Call for the RPC and a Future.
757
+ In the event of RPC completion, the return Call-Future's result
758
+ value will be the response message of the RPC.
759
+ Should the event terminate with non-OK status,
760
+ the returned Call-Future's exception value will be an RpcError.
761
+ """
762
+ raise NotImplementedError()
763
+
764
+
765
+ class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
766
+ """Affords invoking a unary-stream RPC from client-side."""
767
+
768
+ @abc.abstractmethod
769
+ def __call__(self,
770
+ request,
771
+ timeout=None,
772
+ metadata=None,
773
+ credentials=None,
774
+ wait_for_ready=None,
775
+ compression=None):
776
+ """Invokes the underlying RPC.
777
+
778
+ Args:
779
+ request: The request value for the RPC.
780
+ timeout: An optional duration of time in seconds to allow for
781
+ the RPC. If None, the timeout is considered infinite.
782
+ metadata: An optional :term:`metadata` to be transmitted to the
783
+ service-side of the RPC.
784
+ credentials: An optional CallCredentials for the RPC. Only valid for
785
+ secure Channel.
786
+ wait_for_ready: This is an EXPERIMENTAL argument. An optional
787
+ flag to enable :term:`wait_for_ready` mechanism.
788
+ compression: An element of grpc.compression, e.g.
789
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
790
+
791
+ Returns:
792
+ An object that is a Call for the RPC, an iterator of response
793
+ values, and a Future for the RPC. Drawing response values from the
794
+ returned Call-iterator may raise RpcError indicating termination of
795
+ the RPC with non-OK status.
796
+ """
797
+ raise NotImplementedError()
798
+
799
+
800
+ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
801
+ """Affords invoking a stream-unary RPC from client-side."""
802
+
803
+ @abc.abstractmethod
804
+ def __call__(self,
805
+ request_iterator,
806
+ timeout=None,
807
+ metadata=None,
808
+ credentials=None,
809
+ wait_for_ready=None,
810
+ compression=None):
811
+ """Synchronously invokes the underlying RPC.
812
+
813
+ Args:
814
+ request_iterator: An iterator that yields request values for
815
+ the RPC.
816
+ timeout: An optional duration of time in seconds to allow for
817
+ the RPC. If None, the timeout is considered infinite.
818
+ metadata: Optional :term:`metadata` to be transmitted to the
819
+ service-side of the RPC.
820
+ credentials: An optional CallCredentials for the RPC. Only valid for
821
+ secure Channel.
822
+ wait_for_ready: This is an EXPERIMENTAL argument. An optional
823
+ flag to enable :term:`wait_for_ready` mechanism.
824
+ compression: An element of grpc.compression, e.g.
825
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
826
+
827
+ Returns:
828
+ The response value for the RPC.
829
+
830
+ Raises:
831
+ RpcError: Indicating that the RPC terminated with non-OK status. The
832
+ raised RpcError will also implement grpc.Call, affording methods
833
+ such as metadata, code, and details.
834
+ """
835
+ raise NotImplementedError()
836
+
837
+ @abc.abstractmethod
838
+ def with_call(self,
839
+ request_iterator,
840
+ timeout=None,
841
+ metadata=None,
842
+ credentials=None,
843
+ wait_for_ready=None,
844
+ compression=None):
845
+ """Synchronously invokes the underlying RPC on the client.
846
+
847
+ Args:
848
+ request_iterator: An iterator that yields request values for
849
+ the RPC.
850
+ timeout: An optional duration of time in seconds to allow for
851
+ the RPC. If None, the timeout is considered infinite.
852
+ metadata: Optional :term:`metadata` to be transmitted to the
853
+ service-side of the RPC.
854
+ credentials: An optional CallCredentials for the RPC. Only valid for
855
+ secure Channel.
856
+ wait_for_ready: This is an EXPERIMENTAL argument. An optional
857
+ flag to enable :term:`wait_for_ready` mechanism.
858
+ compression: An element of grpc.compression, e.g.
859
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
860
+
861
+ Returns:
862
+ The response value for the RPC and a Call object for the RPC.
863
+
864
+ Raises:
865
+ RpcError: Indicating that the RPC terminated with non-OK status. The
866
+ raised RpcError will also be a Call for the RPC affording the RPC's
867
+ metadata, status code, and details.
868
+ """
869
+ raise NotImplementedError()
870
+
871
+ @abc.abstractmethod
872
+ def future(self,
873
+ request_iterator,
874
+ timeout=None,
875
+ metadata=None,
876
+ credentials=None,
877
+ wait_for_ready=None,
878
+ compression=None):
879
+ """Asynchronously invokes the underlying RPC on the client.
880
+
881
+ Args:
882
+ request_iterator: An iterator that yields request values for the RPC.
883
+ timeout: An optional duration of time in seconds to allow for
884
+ the RPC. If None, the timeout is considered infinite.
885
+ metadata: Optional :term:`metadata` to be transmitted to the
886
+ service-side of the RPC.
887
+ credentials: An optional CallCredentials for the RPC. Only valid for
888
+ secure Channel.
889
+ wait_for_ready: This is an EXPERIMENTAL argument. An optional
890
+ flag to enable :term:`wait_for_ready` mechanism.
891
+ compression: An element of grpc.compression, e.g.
892
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
893
+
894
+ Returns:
895
+ An object that is both a Call for the RPC and a Future.
896
+ In the event of RPC completion, the return Call-Future's result value
897
+ will be the response message of the RPC. Should the event terminate
898
+ with non-OK status, the returned Call-Future's exception value will
899
+ be an RpcError.
900
+ """
901
+ raise NotImplementedError()
902
+
903
+
904
+ class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
905
+ """Affords invoking a stream-stream RPC on client-side."""
906
+
907
+ @abc.abstractmethod
908
+ def __call__(self,
909
+ request_iterator,
910
+ timeout=None,
911
+ metadata=None,
912
+ credentials=None,
913
+ wait_for_ready=None,
914
+ compression=None):
915
+ """Invokes the underlying RPC on the client.
916
+
917
+ Args:
918
+ request_iterator: An iterator that yields request values for the RPC.
919
+ timeout: An optional duration of time in seconds to allow for
920
+ the RPC. If not specified, the timeout is considered infinite.
921
+ metadata: Optional :term:`metadata` to be transmitted to the
922
+ service-side of the RPC.
923
+ credentials: An optional CallCredentials for the RPC. Only valid for
924
+ secure Channel.
925
+ wait_for_ready: This is an EXPERIMENTAL argument. An optional
926
+ flag to enable :term:`wait_for_ready` mechanism.
927
+ compression: An element of grpc.compression, e.g.
928
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
929
+
930
+ Returns:
931
+ An object that is a Call for the RPC, an iterator of response
932
+ values, and a Future for the RPC. Drawing response values from the
933
+ returned Call-iterator may raise RpcError indicating termination of
934
+ the RPC with non-OK status.
935
+ """
936
+ raise NotImplementedError()
937
+
938
+
939
+ ############################# Channel Interface ##############################
940
+
941
+
942
+ class Channel(six.with_metaclass(abc.ABCMeta)):
943
+ """Affords RPC invocation via generic methods on client-side.
944
+
945
+ Channel objects implement the Context Manager type, although they need not
946
+ support being entered and exited multiple times.
947
+ """
948
+
949
+ @abc.abstractmethod
950
+ def subscribe(self, callback, try_to_connect=False):
951
+ """Subscribe to this Channel's connectivity state machine.
952
+
953
+ A Channel may be in any of the states described by ChannelConnectivity.
954
+ This method allows application to monitor the state transitions.
955
+ The typical use case is to debug or gain better visibility into gRPC
956
+ runtime's state.
957
+
958
+ Args:
959
+ callback: A callable to be invoked with ChannelConnectivity argument.
960
+ ChannelConnectivity describes current state of the channel.
961
+ The callable will be invoked immediately upon subscription
962
+ and again for every change to ChannelConnectivity until it
963
+ is unsubscribed or this Channel object goes out of scope.
964
+ try_to_connect: A boolean indicating whether or not this Channel
965
+ should attempt to connect immediately. If set to False, gRPC
966
+ runtime decides when to connect.
967
+ """
968
+ raise NotImplementedError()
969
+
970
+ @abc.abstractmethod
971
+ def unsubscribe(self, callback):
972
+ """Unsubscribes a subscribed callback from this Channel's connectivity.
973
+
974
+ Args:
975
+ callback: A callable previously registered with this Channel from
976
+ having been passed to its "subscribe" method.
977
+ """
978
+ raise NotImplementedError()
979
+
980
+ @abc.abstractmethod
981
+ def unary_unary(self,
982
+ method,
983
+ request_serializer=None,
984
+ response_deserializer=None):
985
+ """Creates a UnaryUnaryMultiCallable for a unary-unary method.
986
+
987
+ Args:
988
+ method: The name of the RPC method.
989
+ request_serializer: Optional :term:`serializer` for serializing the request
990
+ message. Request goes unserialized in case None is passed.
991
+ response_deserializer: Optional :term:`deserializer` for deserializing the
992
+ response message. Response goes undeserialized in case None
993
+ is passed.
994
+
995
+ Returns:
996
+ A UnaryUnaryMultiCallable value for the named unary-unary method.
997
+ """
998
+ raise NotImplementedError()
999
+
1000
+ @abc.abstractmethod
1001
+ def unary_stream(self,
1002
+ method,
1003
+ request_serializer=None,
1004
+ response_deserializer=None):
1005
+ """Creates a UnaryStreamMultiCallable for a unary-stream method.
1006
+
1007
+ Args:
1008
+ method: The name of the RPC method.
1009
+ request_serializer: Optional :term:`serializer` for serializing the request
1010
+ message. Request goes unserialized in case None is passed.
1011
+ response_deserializer: Optional :term:`deserializer` for deserializing the
1012
+ response message. Response goes undeserialized in case None is
1013
+ passed.
1014
+
1015
+ Returns:
1016
+ A UnaryStreamMultiCallable value for the name unary-stream method.
1017
+ """
1018
+ raise NotImplementedError()
1019
+
1020
+ @abc.abstractmethod
1021
+ def stream_unary(self,
1022
+ method,
1023
+ request_serializer=None,
1024
+ response_deserializer=None):
1025
+ """Creates a StreamUnaryMultiCallable for a stream-unary method.
1026
+
1027
+ Args:
1028
+ method: The name of the RPC method.
1029
+ request_serializer: Optional :term:`serializer` for serializing the request
1030
+ message. Request goes unserialized in case None is passed.
1031
+ response_deserializer: Optional :term:`deserializer` for deserializing the
1032
+ response message. Response goes undeserialized in case None is
1033
+ passed.
1034
+
1035
+ Returns:
1036
+ A StreamUnaryMultiCallable value for the named stream-unary method.
1037
+ """
1038
+ raise NotImplementedError()
1039
+
1040
+ @abc.abstractmethod
1041
+ def stream_stream(self,
1042
+ method,
1043
+ request_serializer=None,
1044
+ response_deserializer=None):
1045
+ """Creates a StreamStreamMultiCallable for a stream-stream method.
1046
+
1047
+ Args:
1048
+ method: The name of the RPC method.
1049
+ request_serializer: Optional :term:`serializer` for serializing the request
1050
+ message. Request goes unserialized in case None is passed.
1051
+ response_deserializer: Optional :term:`deserializer` for deserializing the
1052
+ response message. Response goes undeserialized in case None
1053
+ is passed.
1054
+
1055
+ Returns:
1056
+ A StreamStreamMultiCallable value for the named stream-stream method.
1057
+ """
1058
+ raise NotImplementedError()
1059
+
1060
+ @abc.abstractmethod
1061
+ def close(self):
1062
+ """Closes this Channel and releases all resources held by it.
1063
+
1064
+ Closing the Channel will immediately terminate all RPCs active with the
1065
+ Channel and it is not valid to invoke new RPCs with the Channel.
1066
+
1067
+ This method is idempotent.
1068
+ """
1069
+ raise NotImplementedError()
1070
+
1071
+ def __enter__(self):
1072
+ """Enters the runtime context related to the channel object."""
1073
+ raise NotImplementedError()
1074
+
1075
+ def __exit__(self, exc_type, exc_val, exc_tb):
1076
+ """Exits the runtime context related to the channel object."""
1077
+ raise NotImplementedError()
1078
+
1079
+
1080
+ ########################## Service-Side Context ##############################
1081
+
1082
+
1083
+ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
1084
+ """A context object passed to method implementations."""
1085
+
1086
+ @abc.abstractmethod
1087
+ def invocation_metadata(self):
1088
+ """Accesses the metadata from the sent by the client.
1089
+
1090
+ Returns:
1091
+ The invocation :term:`metadata`.
1092
+ """
1093
+ raise NotImplementedError()
1094
+
1095
+ @abc.abstractmethod
1096
+ def peer(self):
1097
+ """Identifies the peer that invoked the RPC being serviced.
1098
+
1099
+ Returns:
1100
+ A string identifying the peer that invoked the RPC being serviced.
1101
+ The string format is determined by gRPC runtime.
1102
+ """
1103
+ raise NotImplementedError()
1104
+
1105
+ @abc.abstractmethod
1106
+ def peer_identities(self):
1107
+ """Gets one or more peer identity(s).
1108
+
1109
+ Equivalent to
1110
+ servicer_context.auth_context().get(servicer_context.peer_identity_key())
1111
+
1112
+ Returns:
1113
+ An iterable of the identities, or None if the call is not
1114
+ authenticated. Each identity is returned as a raw bytes type.
1115
+ """
1116
+ raise NotImplementedError()
1117
+
1118
+ @abc.abstractmethod
1119
+ def peer_identity_key(self):
1120
+ """The auth property used to identify the peer.
1121
+
1122
+ For example, "x509_common_name" or "x509_subject_alternative_name" are
1123
+ used to identify an SSL peer.
1124
+
1125
+ Returns:
1126
+ The auth property (string) that indicates the
1127
+ peer identity, or None if the call is not authenticated.
1128
+ """
1129
+ raise NotImplementedError()
1130
+
1131
+ @abc.abstractmethod
1132
+ def auth_context(self):
1133
+ """Gets the auth context for the call.
1134
+
1135
+ Returns:
1136
+ A map of strings to an iterable of bytes for each auth property.
1137
+ """
1138
+ raise NotImplementedError()
1139
+
1140
+ def set_compression(self, compression):
1141
+ """Set the compression algorithm to be used for the entire call.
1142
+
1143
+ This is an EXPERIMENTAL method.
1144
+
1145
+ Args:
1146
+ compression: An element of grpc.compression, e.g.
1147
+ grpc.compression.Gzip.
1148
+ """
1149
+ raise NotImplementedError()
1150
+
1151
+ @abc.abstractmethod
1152
+ def send_initial_metadata(self, initial_metadata):
1153
+ """Sends the initial metadata value to the client.
1154
+
1155
+ This method need not be called by implementations if they have no
1156
+ metadata to add to what the gRPC runtime will transmit.
1157
+
1158
+ Args:
1159
+ initial_metadata: The initial :term:`metadata`.
1160
+ """
1161
+ raise NotImplementedError()
1162
+
1163
+ @abc.abstractmethod
1164
+ def set_trailing_metadata(self, trailing_metadata):
1165
+ """Sets the trailing metadata for the RPC.
1166
+
1167
+ Sets the trailing metadata to be sent upon completion of the RPC.
1168
+
1169
+ If this method is invoked multiple times throughout the lifetime of an
1170
+ RPC, the value supplied in the final invocation will be the value sent
1171
+ over the wire.
1172
+
1173
+ This method need not be called by implementations if they have no
1174
+ metadata to add to what the gRPC runtime will transmit.
1175
+
1176
+ Args:
1177
+ trailing_metadata: The trailing :term:`metadata`.
1178
+ """
1179
+ raise NotImplementedError()
1180
+
1181
+ def trailing_metadata(self):
1182
+ """Access value to be used as trailing metadata upon RPC completion.
1183
+
1184
+ This is an EXPERIMENTAL API.
1185
+
1186
+ Returns:
1187
+ The trailing :term:`metadata` for the RPC.
1188
+ """
1189
+ raise NotImplementedError()
1190
+
1191
+ @abc.abstractmethod
1192
+ def abort(self, code, details):
1193
+ """Raises an exception to terminate the RPC with a non-OK status.
1194
+
1195
+ The code and details passed as arguments will supercede any existing
1196
+ ones.
1197
+
1198
+ Args:
1199
+ code: A StatusCode object to be sent to the client.
1200
+ It must not be StatusCode.OK.
1201
+ details: A UTF-8-encodable string to be sent to the client upon
1202
+ termination of the RPC.
1203
+
1204
+ Raises:
1205
+ Exception: An exception is always raised to signal the abortion the
1206
+ RPC to the gRPC runtime.
1207
+ """
1208
+ raise NotImplementedError()
1209
+
1210
+ @abc.abstractmethod
1211
+ def abort_with_status(self, status):
1212
+ """Raises an exception to terminate the RPC with a non-OK status.
1213
+
1214
+ The status passed as argument will supercede any existing status code,
1215
+ status message and trailing metadata.
1216
+
1217
+ This is an EXPERIMENTAL API.
1218
+
1219
+ Args:
1220
+ status: A grpc.Status object. The status code in it must not be
1221
+ StatusCode.OK.
1222
+
1223
+ Raises:
1224
+ Exception: An exception is always raised to signal the abortion the
1225
+ RPC to the gRPC runtime.
1226
+ """
1227
+ raise NotImplementedError()
1228
+
1229
+ @abc.abstractmethod
1230
+ def set_code(self, code):
1231
+ """Sets the value to be used as status code upon RPC completion.
1232
+
1233
+ This method need not be called by method implementations if they wish
1234
+ the gRPC runtime to determine the status code of the RPC.
1235
+
1236
+ Args:
1237
+ code: A StatusCode object to be sent to the client.
1238
+ """
1239
+ raise NotImplementedError()
1240
+
1241
+ @abc.abstractmethod
1242
+ def set_details(self, details):
1243
+ """Sets the value to be used as detail string upon RPC completion.
1244
+
1245
+ This method need not be called by method implementations if they have
1246
+ no details to transmit.
1247
+
1248
+ Args:
1249
+ details: A UTF-8-encodable string to be sent to the client upon
1250
+ termination of the RPC.
1251
+ """
1252
+ raise NotImplementedError()
1253
+
1254
+ def code(self):
1255
+ """Accesses the value to be used as status code upon RPC completion.
1256
+
1257
+ This is an EXPERIMENTAL API.
1258
+
1259
+ Returns:
1260
+ The StatusCode value for the RPC.
1261
+ """
1262
+ raise NotImplementedError()
1263
+
1264
+ def details(self):
1265
+ """Accesses the value to be used as detail string upon RPC completion.
1266
+
1267
+ This is an EXPERIMENTAL API.
1268
+
1269
+ Returns:
1270
+ The details string of the RPC.
1271
+ """
1272
+ raise NotImplementedError()
1273
+
1274
+ def disable_next_message_compression(self):
1275
+ """Disables compression for the next response message.
1276
+
1277
+ This is an EXPERIMENTAL method.
1278
+
1279
+ This method will override any compression configuration set during
1280
+ server creation or set on the call.
1281
+ """
1282
+ raise NotImplementedError()
1283
+
1284
+
1285
+ ##################### Service-Side Handler Interfaces ########################
1286
+
1287
+
1288
+ class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
1289
+ """An implementation of a single RPC method.
1290
+
1291
+ Attributes:
1292
+ request_streaming: Whether the RPC supports exactly one request message
1293
+ or any arbitrary number of request messages.
1294
+ response_streaming: Whether the RPC supports exactly one response message
1295
+ or any arbitrary number of response messages.
1296
+ request_deserializer: A callable :term:`deserializer` that accepts a byte string and
1297
+ returns an object suitable to be passed to this object's business
1298
+ logic, or None to indicate that this object's business logic should be
1299
+ passed the raw request bytes.
1300
+ response_serializer: A callable :term:`serializer` that accepts an object produced
1301
+ by this object's business logic and returns a byte string, or None to
1302
+ indicate that the byte strings produced by this object's business logic
1303
+ should be transmitted on the wire as they are.
1304
+ unary_unary: This object's application-specific business logic as a
1305
+ callable value that takes a request value and a ServicerContext object
1306
+ and returns a response value. Only non-None if both request_streaming
1307
+ and response_streaming are False.
1308
+ unary_stream: This object's application-specific business logic as a
1309
+ callable value that takes a request value and a ServicerContext object
1310
+ and returns an iterator of response values. Only non-None if
1311
+ request_streaming is False and response_streaming is True.
1312
+ stream_unary: This object's application-specific business logic as a
1313
+ callable value that takes an iterator of request values and a
1314
+ ServicerContext object and returns a response value. Only non-None if
1315
+ request_streaming is True and response_streaming is False.
1316
+ stream_stream: This object's application-specific business logic as a
1317
+ callable value that takes an iterator of request values and a
1318
+ ServicerContext object and returns an iterator of response values.
1319
+ Only non-None if request_streaming and response_streaming are both
1320
+ True.
1321
+ """
1322
+
1323
+
1324
+ class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
1325
+ """Describes an RPC that has just arrived for service.
1326
+
1327
+ Attributes:
1328
+ method: The method name of the RPC.
1329
+ invocation_metadata: The :term:`metadata` sent by the client.
1330
+ """
1331
+
1332
+
1333
+ class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
1334
+ """An implementation of arbitrarily many RPC methods."""
1335
+
1336
+ @abc.abstractmethod
1337
+ def service(self, handler_call_details):
1338
+ """Returns the handler for servicing the RPC.
1339
+
1340
+ Args:
1341
+ handler_call_details: A HandlerCallDetails describing the RPC.
1342
+
1343
+ Returns:
1344
+ An RpcMethodHandler with which the RPC may be serviced if the
1345
+ implementation chooses to service this RPC, or None otherwise.
1346
+ """
1347
+ raise NotImplementedError()
1348
+
1349
+
1350
+ class ServiceRpcHandler(six.with_metaclass(abc.ABCMeta, GenericRpcHandler)):
1351
+ """An implementation of RPC methods belonging to a service.
1352
+
1353
+ A service handles RPC methods with structured names of the form
1354
+ '/Service.Name/Service.Method', where 'Service.Name' is the value
1355
+ returned by service_name(), and 'Service.Method' is the method
1356
+ name. A service can have multiple method names, but only a single
1357
+ service name.
1358
+ """
1359
+
1360
+ @abc.abstractmethod
1361
+ def service_name(self):
1362
+ """Returns this service's name.
1363
+
1364
+ Returns:
1365
+ The service name.
1366
+ """
1367
+ raise NotImplementedError()
1368
+
1369
+
1370
+ #################### Service-Side Interceptor Interfaces #####################
1371
+
1372
+
1373
+ class ServerInterceptor(six.with_metaclass(abc.ABCMeta)):
1374
+ """Affords intercepting incoming RPCs on the service-side."""
1375
+
1376
+ @abc.abstractmethod
1377
+ def intercept_service(self, continuation, handler_call_details):
1378
+ """Intercepts incoming RPCs before handing them over to a handler.
1379
+
1380
+ Args:
1381
+ continuation: A function that takes a HandlerCallDetails and
1382
+ proceeds to invoke the next interceptor in the chain, if any,
1383
+ or the RPC handler lookup logic, with the call details passed
1384
+ as an argument, and returns an RpcMethodHandler instance if
1385
+ the RPC is considered serviced, or None otherwise.
1386
+ handler_call_details: A HandlerCallDetails describing the RPC.
1387
+
1388
+ Returns:
1389
+ An RpcMethodHandler with which the RPC may be serviced if the
1390
+ interceptor chooses to service this RPC, or None otherwise.
1391
+ """
1392
+ raise NotImplementedError()
1393
+
1394
+
1395
+ ############################# Server Interface ###############################
1396
+
1397
+
1398
+ class Server(six.with_metaclass(abc.ABCMeta)):
1399
+ """Services RPCs."""
1400
+
1401
+ @abc.abstractmethod
1402
+ def add_generic_rpc_handlers(self, generic_rpc_handlers):
1403
+ """Registers GenericRpcHandlers with this Server.
1404
+
1405
+ This method is only safe to call before the server is started.
1406
+
1407
+ Args:
1408
+ generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1409
+ used to service RPCs.
1410
+ """
1411
+ raise NotImplementedError()
1412
+
1413
+ @abc.abstractmethod
1414
+ def add_insecure_port(self, address):
1415
+ """Opens an insecure port for accepting RPCs.
1416
+
1417
+ This method may only be called before starting the server.
1418
+
1419
+ Args:
1420
+ address: The address for which to open a port. If the port is 0,
1421
+ or not specified in the address, then gRPC runtime will choose a port.
1422
+
1423
+ Returns:
1424
+ An integer port on which server will accept RPC requests.
1425
+ """
1426
+ raise NotImplementedError()
1427
+
1428
+ @abc.abstractmethod
1429
+ def add_secure_port(self, address, server_credentials):
1430
+ """Opens a secure port for accepting RPCs.
1431
+
1432
+ This method may only be called before starting the server.
1433
+
1434
+ Args:
1435
+ address: The address for which to open a port.
1436
+ if the port is 0, or not specified in the address, then gRPC
1437
+ runtime will choose a port.
1438
+ server_credentials: A ServerCredentials object.
1439
+
1440
+ Returns:
1441
+ An integer port on which server will accept RPC requests.
1442
+ """
1443
+ raise NotImplementedError()
1444
+
1445
+ @abc.abstractmethod
1446
+ def start(self):
1447
+ """Starts this Server.
1448
+
1449
+ This method may only be called once. (i.e. it is not idempotent).
1450
+ """
1451
+ raise NotImplementedError()
1452
+
1453
+ @abc.abstractmethod
1454
+ def stop(self, grace):
1455
+ """Stops this Server.
1456
+
1457
+ This method immediately stop service of new RPCs in all cases.
1458
+
1459
+ If a grace period is specified, this method returns immediately
1460
+ and all RPCs active at the end of the grace period are aborted.
1461
+ If a grace period is not specified (by passing None for `grace`),
1462
+ all existing RPCs are aborted immediately and this method
1463
+ blocks until the last RPC handler terminates.
1464
+
1465
+ This method is idempotent and may be called at any time.
1466
+ Passing a smaller grace value in a subsequent call will have
1467
+ the effect of stopping the Server sooner (passing None will
1468
+ have the effect of stopping the server immediately). Passing
1469
+ a larger grace value in a subsequent call *will not* have the
1470
+ effect of stopping the server later (i.e. the most restrictive
1471
+ grace value is used).
1472
+
1473
+ Args:
1474
+ grace: A duration of time in seconds or None.
1475
+
1476
+ Returns:
1477
+ A threading.Event that will be set when this Server has completely
1478
+ stopped, i.e. when running RPCs either complete or are aborted and
1479
+ all handlers have terminated.
1480
+ """
1481
+ raise NotImplementedError()
1482
+
1483
+ def wait_for_termination(self, timeout=None):
1484
+ """Block current thread until the server stops.
1485
+
1486
+ This is an EXPERIMENTAL API.
1487
+
1488
+ The wait will not consume computational resources during blocking, and
1489
+ it will block until one of the two following conditions are met:
1490
+
1491
+ 1) The server is stopped or terminated;
1492
+ 2) A timeout occurs if timeout is not `None`.
1493
+
1494
+ The timeout argument works in the same way as `threading.Event.wait()`.
1495
+ https://docs.python.org/3/library/threading.html#threading.Event.wait
1496
+
1497
+ Args:
1498
+ timeout: A floating point number specifying a timeout for the
1499
+ operation in seconds.
1500
+
1501
+ Returns:
1502
+ A bool indicates if the operation times out.
1503
+ """
1504
+ raise NotImplementedError()
1505
+
1506
+
1507
+ ################################# Functions ################################
1508
+
1509
+
1510
+ def unary_unary_rpc_method_handler(behavior,
1511
+ request_deserializer=None,
1512
+ response_serializer=None):
1513
+ """Creates an RpcMethodHandler for a unary-unary RPC method.
1514
+
1515
+ Args:
1516
+ behavior: The implementation of an RPC that accepts one request
1517
+ and returns one response.
1518
+ request_deserializer: An optional :term:`deserializer` for request deserialization.
1519
+ response_serializer: An optional :term:`serializer` for response serialization.
1520
+
1521
+ Returns:
1522
+ An RpcMethodHandler object that is typically used by grpc.Server.
1523
+ """
1524
+ from grpc import _utilities # pylint: disable=cyclic-import
1525
+ return _utilities.RpcMethodHandler(False, False, request_deserializer,
1526
+ response_serializer, behavior, None,
1527
+ None, None)
1528
+
1529
+
1530
+ def unary_stream_rpc_method_handler(behavior,
1531
+ request_deserializer=None,
1532
+ response_serializer=None):
1533
+ """Creates an RpcMethodHandler for a unary-stream RPC method.
1534
+
1535
+ Args:
1536
+ behavior: The implementation of an RPC that accepts one request
1537
+ and returns an iterator of response values.
1538
+ request_deserializer: An optional :term:`deserializer` for request deserialization.
1539
+ response_serializer: An optional :term:`serializer` for response serialization.
1540
+
1541
+ Returns:
1542
+ An RpcMethodHandler object that is typically used by grpc.Server.
1543
+ """
1544
+ from grpc import _utilities # pylint: disable=cyclic-import
1545
+ return _utilities.RpcMethodHandler(False, True, request_deserializer,
1546
+ response_serializer, None, behavior,
1547
+ None, None)
1548
+
1549
+
1550
+ def stream_unary_rpc_method_handler(behavior,
1551
+ request_deserializer=None,
1552
+ response_serializer=None):
1553
+ """Creates an RpcMethodHandler for a stream-unary RPC method.
1554
+
1555
+ Args:
1556
+ behavior: The implementation of an RPC that accepts an iterator of
1557
+ request values and returns a single response value.
1558
+ request_deserializer: An optional :term:`deserializer` for request deserialization.
1559
+ response_serializer: An optional :term:`serializer` for response serialization.
1560
+
1561
+ Returns:
1562
+ An RpcMethodHandler object that is typically used by grpc.Server.
1563
+ """
1564
+ from grpc import _utilities # pylint: disable=cyclic-import
1565
+ return _utilities.RpcMethodHandler(True, False, request_deserializer,
1566
+ response_serializer, None, None,
1567
+ behavior, None)
1568
+
1569
+
1570
+ def stream_stream_rpc_method_handler(behavior,
1571
+ request_deserializer=None,
1572
+ response_serializer=None):
1573
+ """Creates an RpcMethodHandler for a stream-stream RPC method.
1574
+
1575
+ Args:
1576
+ behavior: The implementation of an RPC that accepts an iterator of
1577
+ request values and returns an iterator of response values.
1578
+ request_deserializer: An optional :term:`deserializer` for request deserialization.
1579
+ response_serializer: An optional :term:`serializer` for response serialization.
1580
+
1581
+ Returns:
1582
+ An RpcMethodHandler object that is typically used by grpc.Server.
1583
+ """
1584
+ from grpc import _utilities # pylint: disable=cyclic-import
1585
+ return _utilities.RpcMethodHandler(True, True, request_deserializer,
1586
+ response_serializer, None, None, None,
1587
+ behavior)
1588
+
1589
+
1590
+ def method_handlers_generic_handler(service, method_handlers):
1591
+ """Creates a GenericRpcHandler from RpcMethodHandlers.
1592
+
1593
+ Args:
1594
+ service: The name of the service that is implemented by the
1595
+ method_handlers.
1596
+ method_handlers: A dictionary that maps method names to corresponding
1597
+ RpcMethodHandler.
1598
+
1599
+ Returns:
1600
+ A GenericRpcHandler. This is typically added to the grpc.Server object
1601
+ with add_generic_rpc_handlers() before starting the server.
1602
+ """
1603
+ from grpc import _utilities # pylint: disable=cyclic-import
1604
+ return _utilities.DictionaryGenericHandler(service, method_handlers)
1605
+
1606
+
1607
+ def ssl_channel_credentials(root_certificates=None,
1608
+ private_key=None,
1609
+ certificate_chain=None):
1610
+ """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1611
+
1612
+ Args:
1613
+ root_certificates: The PEM-encoded root certificates as a byte string,
1614
+ or None to retrieve them from a default location chosen by gRPC
1615
+ runtime.
1616
+ private_key: The PEM-encoded private key as a byte string, or None if no
1617
+ private key should be used.
1618
+ certificate_chain: The PEM-encoded certificate chain as a byte string
1619
+ to use or None if no certificate chain should be used.
1620
+
1621
+ Returns:
1622
+ A ChannelCredentials for use with an SSL-enabled Channel.
1623
+ """
1624
+ return ChannelCredentials(
1625
+ _cygrpc.SSLChannelCredentials(root_certificates, private_key,
1626
+ certificate_chain))
1627
+
1628
+
1629
+ def xds_channel_credentials(fallback_credentials=None):
1630
+ """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL
1631
+ API.
1632
+
1633
+ Args:
1634
+ fallback_credentials: Credentials to use in case it is not possible to
1635
+ establish a secure connection via xDS. If no fallback_credentials
1636
+ argument is supplied, a default SSLChannelCredentials is used.
1637
+ """
1638
+ fallback_credentials = ssl_channel_credentials(
1639
+ ) if fallback_credentials is None else fallback_credentials
1640
+ return ChannelCredentials(
1641
+ _cygrpc.XDSChannelCredentials(fallback_credentials._credentials))
1642
+
1643
+
1644
+ def metadata_call_credentials(metadata_plugin, name=None):
1645
+ """Construct CallCredentials from an AuthMetadataPlugin.
1646
+
1647
+ Args:
1648
+ metadata_plugin: An AuthMetadataPlugin to use for authentication.
1649
+ name: An optional name for the plugin.
1650
+
1651
+ Returns:
1652
+ A CallCredentials.
1653
+ """
1654
+ from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1655
+ return _plugin_wrapping.metadata_plugin_call_credentials(
1656
+ metadata_plugin, name)
1657
+
1658
+
1659
+ def access_token_call_credentials(access_token):
1660
+ """Construct CallCredentials from an access token.
1661
+
1662
+ Args:
1663
+ access_token: A string to place directly in the http request
1664
+ authorization header, for example
1665
+ "authorization: Bearer <access_token>".
1666
+
1667
+ Returns:
1668
+ A CallCredentials.
1669
+ """
1670
+ from grpc import _auth # pylint: disable=cyclic-import
1671
+ from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1672
+ return _plugin_wrapping.metadata_plugin_call_credentials(
1673
+ _auth.AccessTokenAuthMetadataPlugin(access_token), None)
1674
+
1675
+
1676
+ def composite_call_credentials(*call_credentials):
1677
+ """Compose multiple CallCredentials to make a new CallCredentials.
1678
+
1679
+ Args:
1680
+ *call_credentials: At least two CallCredentials objects.
1681
+
1682
+ Returns:
1683
+ A CallCredentials object composed of the given CallCredentials objects.
1684
+ """
1685
+ return CallCredentials(
1686
+ _cygrpc.CompositeCallCredentials(
1687
+ tuple(single_call_credentials._credentials
1688
+ for single_call_credentials in call_credentials)))
1689
+
1690
+
1691
+ def composite_channel_credentials(channel_credentials, *call_credentials):
1692
+ """Compose a ChannelCredentials and one or more CallCredentials objects.
1693
+
1694
+ Args:
1695
+ channel_credentials: A ChannelCredentials object.
1696
+ *call_credentials: One or more CallCredentials objects.
1697
+
1698
+ Returns:
1699
+ A ChannelCredentials composed of the given ChannelCredentials and
1700
+ CallCredentials objects.
1701
+ """
1702
+ return ChannelCredentials(
1703
+ _cygrpc.CompositeChannelCredentials(
1704
+ tuple(single_call_credentials._credentials
1705
+ for single_call_credentials in call_credentials),
1706
+ channel_credentials._credentials))
1707
+
1708
+
1709
+ def ssl_server_credentials(private_key_certificate_chain_pairs,
1710
+ root_certificates=None,
1711
+ require_client_auth=False):
1712
+ """Creates a ServerCredentials for use with an SSL-enabled Server.
1713
+
1714
+ Args:
1715
+ private_key_certificate_chain_pairs: A list of pairs of the form
1716
+ [PEM-encoded private key, PEM-encoded certificate chain].
1717
+ root_certificates: An optional byte string of PEM-encoded client root
1718
+ certificates that the server will use to verify client authentication.
1719
+ If omitted, require_client_auth must also be False.
1720
+ require_client_auth: A boolean indicating whether or not to require
1721
+ clients to be authenticated. May only be True if root_certificates
1722
+ is not None.
1723
+
1724
+ Returns:
1725
+ A ServerCredentials for use with an SSL-enabled Server. Typically, this
1726
+ object is an argument to add_secure_port() method during server setup.
1727
+ """
1728
+ if not private_key_certificate_chain_pairs:
1729
+ raise ValueError(
1730
+ 'At least one private key-certificate chain pair is required!')
1731
+ elif require_client_auth and root_certificates is None:
1732
+ raise ValueError(
1733
+ 'Illegal to require client auth without providing root certificates!'
1734
+ )
1735
+ else:
1736
+ return ServerCredentials(
1737
+ _cygrpc.server_credentials_ssl(root_certificates, [
1738
+ _cygrpc.SslPemKeyCertPair(key, pem)
1739
+ for key, pem in private_key_certificate_chain_pairs
1740
+ ], require_client_auth))
1741
+
1742
+
1743
+ def xds_server_credentials(fallback_credentials):
1744
+ """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL
1745
+ API.
1746
+
1747
+ Args:
1748
+ fallback_credentials: Credentials to use in case it is not possible to
1749
+ establish a secure connection via xDS. No default value is provided.
1750
+ """
1751
+ return ServerCredentials(
1752
+ _cygrpc.xds_server_credentials(fallback_credentials._credentials))
1753
+
1754
+
1755
+ def insecure_server_credentials():
1756
+ """Creates a credentials object directing the server to use no credentials.
1757
+ This is an EXPERIMENTAL API.
1758
+
1759
+ This object cannot be used directly in a call to `add_secure_port`.
1760
+ Instead, it should be used to construct other credentials objects, e.g.
1761
+ with xds_server_credentials.
1762
+ """
1763
+ return ServerCredentials(_cygrpc.insecure_server_credentials())
1764
+
1765
+
1766
+ def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
1767
+ root_certificates=None):
1768
+ """Creates a ServerCertificateConfiguration for use with a Server.
1769
+
1770
+ Args:
1771
+ private_key_certificate_chain_pairs: A collection of pairs of
1772
+ the form [PEM-encoded private key, PEM-encoded certificate
1773
+ chain].
1774
+ root_certificates: An optional byte string of PEM-encoded client root
1775
+ certificates that the server will use to verify client authentication.
1776
+
1777
+ Returns:
1778
+ A ServerCertificateConfiguration that can be returned in the certificate
1779
+ configuration fetching callback.
1780
+ """
1781
+ if private_key_certificate_chain_pairs:
1782
+ return ServerCertificateConfiguration(
1783
+ _cygrpc.server_certificate_config_ssl(root_certificates, [
1784
+ _cygrpc.SslPemKeyCertPair(key, pem)
1785
+ for key, pem in private_key_certificate_chain_pairs
1786
+ ]))
1787
+ else:
1788
+ raise ValueError(
1789
+ 'At least one private key-certificate chain pair is required!')
1790
+
1791
+
1792
+ def dynamic_ssl_server_credentials(initial_certificate_configuration,
1793
+ certificate_configuration_fetcher,
1794
+ require_client_authentication=False):
1795
+ """Creates a ServerCredentials for use with an SSL-enabled Server.
1796
+
1797
+ Args:
1798
+ initial_certificate_configuration (ServerCertificateConfiguration): The
1799
+ certificate configuration with which the server will be initialized.
1800
+ certificate_configuration_fetcher (callable): A callable that takes no
1801
+ arguments and should return a ServerCertificateConfiguration to
1802
+ replace the server's current certificate, or None for no change
1803
+ (i.e., the server will continue its current certificate
1804
+ config). The library will call this callback on *every* new
1805
+ client connection before starting the TLS handshake with the
1806
+ client, thus allowing the user application to optionally
1807
+ return a new ServerCertificateConfiguration that the server will then
1808
+ use for the handshake.
1809
+ require_client_authentication: A boolean indicating whether or not to
1810
+ require clients to be authenticated.
1811
+
1812
+ Returns:
1813
+ A ServerCredentials.
1814
+ """
1815
+ return ServerCredentials(
1816
+ _cygrpc.server_credentials_ssl_dynamic_cert_config(
1817
+ initial_certificate_configuration,
1818
+ certificate_configuration_fetcher, require_client_authentication))
1819
+
1820
+
1821
+ @enum.unique
1822
+ class LocalConnectionType(enum.Enum):
1823
+ """Types of local connection for local credential creation.
1824
+
1825
+ Attributes:
1826
+ UDS: Unix domain socket connections
1827
+ LOCAL_TCP: Local TCP connections.
1828
+ """
1829
+ UDS = _cygrpc.LocalConnectionType.uds
1830
+ LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
1831
+
1832
+
1833
+ def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1834
+ """Creates a local ChannelCredentials used for local connections.
1835
+
1836
+ This is an EXPERIMENTAL API.
1837
+
1838
+ Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1839
+ also UDS connections.
1840
+
1841
+ The connections created by local channel credentials are not
1842
+ encrypted, but will be checked if they are local or not.
1843
+ The UDS connections are considered secure by providing peer authentication
1844
+ and data confidentiality while TCP connections are considered insecure.
1845
+
1846
+ It is allowed to transmit call credentials over connections created by
1847
+ local channel credentials.
1848
+
1849
+ Local channel credentials are useful for 1) eliminating insecure_channel usage;
1850
+ 2) enable unit testing for call credentials without setting up secrets.
1851
+
1852
+ Args:
1853
+ local_connect_type: Local connection type (either
1854
+ grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1855
+
1856
+ Returns:
1857
+ A ChannelCredentials for use with a local Channel
1858
+ """
1859
+ return ChannelCredentials(
1860
+ _cygrpc.channel_credentials_local(local_connect_type.value))
1861
+
1862
+
1863
+ def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1864
+ """Creates a local ServerCredentials used for local connections.
1865
+
1866
+ This is an EXPERIMENTAL API.
1867
+
1868
+ Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1869
+ also UDS connections.
1870
+
1871
+ The connections created by local server credentials are not
1872
+ encrypted, but will be checked if they are local or not.
1873
+ The UDS connections are considered secure by providing peer authentication
1874
+ and data confidentiality while TCP connections are considered insecure.
1875
+
1876
+ It is allowed to transmit call credentials over connections created by local
1877
+ server credentials.
1878
+
1879
+ Local server credentials are useful for 1) eliminating insecure_channel usage;
1880
+ 2) enable unit testing for call credentials without setting up secrets.
1881
+
1882
+ Args:
1883
+ local_connect_type: Local connection type (either
1884
+ grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1885
+
1886
+ Returns:
1887
+ A ServerCredentials for use with a local Server
1888
+ """
1889
+ return ServerCredentials(
1890
+ _cygrpc.server_credentials_local(local_connect_type.value))
1891
+
1892
+
1893
+ def alts_channel_credentials(service_accounts=None):
1894
+ """Creates a ChannelCredentials for use with an ALTS-enabled Channel.
1895
+
1896
+ This is an EXPERIMENTAL API.
1897
+ ALTS credentials API can only be used in GCP environment as it relies on
1898
+ handshaker service being available. For more info about ALTS see
1899
+ https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1900
+
1901
+ Args:
1902
+ service_accounts: A list of server identities accepted by the client.
1903
+ If target service accounts are provided and none of them matches the
1904
+ peer identity of the server, handshake will fail. The arg can be empty
1905
+ if the client does not have any information about trusted server
1906
+ identity.
1907
+ Returns:
1908
+ A ChannelCredentials for use with an ALTS-enabled Channel
1909
+ """
1910
+ return ChannelCredentials(
1911
+ _cygrpc.channel_credentials_alts(service_accounts or []))
1912
+
1913
+
1914
+ def alts_server_credentials():
1915
+ """Creates a ServerCredentials for use with an ALTS-enabled connection.
1916
+
1917
+ This is an EXPERIMENTAL API.
1918
+ ALTS credentials API can only be used in GCP environment as it relies on
1919
+ handshaker service being available. For more info about ALTS see
1920
+ https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1921
+
1922
+ Returns:
1923
+ A ServerCredentials for use with an ALTS-enabled Server
1924
+ """
1925
+ return ServerCredentials(_cygrpc.server_credentials_alts())
1926
+
1927
+
1928
+ def compute_engine_channel_credentials(call_credentials):
1929
+ """Creates a compute engine channel credential.
1930
+
1931
+ This credential can only be used in a GCP environment as it relies on
1932
+ a handshaker service. For more info about ALTS, see
1933
+ https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
1934
+
1935
+ This channel credential is expected to be used as part of a composite
1936
+ credential in conjunction with a call credentials that authenticates the
1937
+ VM's default service account. If used with any other sort of call
1938
+ credential, the connection may suddenly and unexpectedly begin failing RPCs.
1939
+ """
1940
+ return ChannelCredentials(
1941
+ _cygrpc.channel_credentials_compute_engine(
1942
+ call_credentials._credentials))
1943
+
1944
+
1945
+ def channel_ready_future(channel):
1946
+ """Creates a Future that tracks when a Channel is ready.
1947
+
1948
+ Cancelling the Future does not affect the channel's state machine.
1949
+ It merely decouples the Future from channel state machine.
1950
+
1951
+ Args:
1952
+ channel: A Channel object.
1953
+
1954
+ Returns:
1955
+ A Future object that matures when the channel connectivity is
1956
+ ChannelConnectivity.READY.
1957
+ """
1958
+ from grpc import _utilities # pylint: disable=cyclic-import
1959
+ return _utilities.channel_ready_future(channel)
1960
+
1961
+
1962
+ def insecure_channel(target, options=None, compression=None):
1963
+ """Creates an insecure Channel to a server.
1964
+
1965
+ The returned Channel is thread-safe.
1966
+
1967
+ Args:
1968
+ target: The server address
1969
+ options: An optional list of key-value pairs (:term:`channel_arguments`
1970
+ in gRPC Core runtime) to configure the channel.
1971
+ compression: An optional value indicating the compression method to be
1972
+ used over the lifetime of the channel. This is an EXPERIMENTAL option.
1973
+
1974
+ Returns:
1975
+ A Channel.
1976
+ """
1977
+ from grpc import _channel # pylint: disable=cyclic-import
1978
+ return _channel.Channel(target, () if options is None else options, None,
1979
+ compression)
1980
+
1981
+
1982
+ def secure_channel(target, credentials, options=None, compression=None):
1983
+ """Creates a secure Channel to a server.
1984
+
1985
+ The returned Channel is thread-safe.
1986
+
1987
+ Args:
1988
+ target: The server address.
1989
+ credentials: A ChannelCredentials instance.
1990
+ options: An optional list of key-value pairs (:term:`channel_arguments`
1991
+ in gRPC Core runtime) to configure the channel.
1992
+ compression: An optional value indicating the compression method to be
1993
+ used over the lifetime of the channel. This is an EXPERIMENTAL option.
1994
+
1995
+ Returns:
1996
+ A Channel.
1997
+ """
1998
+ from grpc import _channel # pylint: disable=cyclic-import
1999
+ from grpc.experimental import _insecure_channel_credentials
2000
+ if credentials._credentials is _insecure_channel_credentials:
2001
+ raise ValueError(
2002
+ "secure_channel cannot be called with insecure credentials." +
2003
+ " Call insecure_channel instead.")
2004
+ return _channel.Channel(target, () if options is None else options,
2005
+ credentials._credentials, compression)
2006
+
2007
+
2008
+ def intercept_channel(channel, *interceptors):
2009
+ """Intercepts a channel through a set of interceptors.
2010
+
2011
+ Args:
2012
+ channel: A Channel.
2013
+ interceptors: Zero or more objects of type
2014
+ UnaryUnaryClientInterceptor,
2015
+ UnaryStreamClientInterceptor,
2016
+ StreamUnaryClientInterceptor, or
2017
+ StreamStreamClientInterceptor.
2018
+ Interceptors are given control in the order they are listed.
2019
+
2020
+ Returns:
2021
+ A Channel that intercepts each invocation via the provided interceptors.
2022
+
2023
+ Raises:
2024
+ TypeError: If interceptor does not derive from any of
2025
+ UnaryUnaryClientInterceptor,
2026
+ UnaryStreamClientInterceptor,
2027
+ StreamUnaryClientInterceptor, or
2028
+ StreamStreamClientInterceptor.
2029
+ """
2030
+ from grpc import _interceptor # pylint: disable=cyclic-import
2031
+ return _interceptor.intercept_channel(channel, *interceptors)
2032
+
2033
+
2034
+ def server(thread_pool,
2035
+ handlers=None,
2036
+ interceptors=None,
2037
+ options=None,
2038
+ maximum_concurrent_rpcs=None,
2039
+ compression=None,
2040
+ xds=False):
2041
+ """Creates a Server with which RPCs can be serviced.
2042
+
2043
+ Args:
2044
+ thread_pool: A futures.ThreadPoolExecutor to be used by the Server
2045
+ to execute RPC handlers.
2046
+ handlers: An optional list of GenericRpcHandlers used for executing RPCs.
2047
+ More handlers may be added by calling add_generic_rpc_handlers any time
2048
+ before the server is started.
2049
+ interceptors: An optional list of ServerInterceptor objects that observe
2050
+ and optionally manipulate the incoming RPCs before handing them over to
2051
+ handlers. The interceptors are given control in the order they are
2052
+ specified. This is an EXPERIMENTAL API.
2053
+ options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
2054
+ to configure the channel.
2055
+ maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
2056
+ will service before returning RESOURCE_EXHAUSTED status, or None to
2057
+ indicate no limit.
2058
+ compression: An element of grpc.compression, e.g.
2059
+ grpc.compression.Gzip. This compression algorithm will be used for the
2060
+ lifetime of the server unless overridden. This is an EXPERIMENTAL option.
2061
+ xds: If set to true, retrieves server configuration via xDS. This is an
2062
+ EXPERIMENTAL option.
2063
+
2064
+ Returns:
2065
+ A Server object.
2066
+ """
2067
+ from grpc import _server # pylint: disable=cyclic-import
2068
+ return _server.create_server(thread_pool,
2069
+ () if handlers is None else handlers,
2070
+ () if interceptors is None else interceptors,
2071
+ () if options is None else options,
2072
+ maximum_concurrent_rpcs, compression, xds)
2073
+
2074
+
2075
+ @contextlib.contextmanager
2076
+ def _create_servicer_context(rpc_event, state, request_deserializer):
2077
+ from grpc import _server # pylint: disable=cyclic-import
2078
+ context = _server._Context(rpc_event, state, request_deserializer)
2079
+ yield context
2080
+ context._finalize_state() # pylint: disable=protected-access
2081
+
2082
+
2083
+ @enum.unique
2084
+ class Compression(enum.IntEnum):
2085
+ """Indicates the compression method to be used for an RPC.
2086
+
2087
+ This enumeration is part of an EXPERIMENTAL API.
2088
+
2089
+ Attributes:
2090
+ NoCompression: Do not use compression algorithm.
2091
+ Deflate: Use "Deflate" compression algorithm.
2092
+ Gzip: Use "Gzip" compression algorithm.
2093
+ """
2094
+ NoCompression = _compression.NoCompression
2095
+ Deflate = _compression.Deflate
2096
+ Gzip = _compression.Gzip
2097
+
2098
+
2099
+ ################################### __all__ #################################
2100
+
2101
+ __all__ = (
2102
+ 'FutureTimeoutError',
2103
+ 'FutureCancelledError',
2104
+ 'Future',
2105
+ 'ChannelConnectivity',
2106
+ 'StatusCode',
2107
+ 'Status',
2108
+ 'RpcError',
2109
+ 'RpcContext',
2110
+ 'Call',
2111
+ 'ChannelCredentials',
2112
+ 'CallCredentials',
2113
+ 'AuthMetadataContext',
2114
+ 'AuthMetadataPluginCallback',
2115
+ 'AuthMetadataPlugin',
2116
+ 'Compression',
2117
+ 'ClientCallDetails',
2118
+ 'ServerCertificateConfiguration',
2119
+ 'ServerCredentials',
2120
+ 'LocalConnectionType',
2121
+ 'UnaryUnaryMultiCallable',
2122
+ 'UnaryStreamMultiCallable',
2123
+ 'StreamUnaryMultiCallable',
2124
+ 'StreamStreamMultiCallable',
2125
+ 'UnaryUnaryClientInterceptor',
2126
+ 'UnaryStreamClientInterceptor',
2127
+ 'StreamUnaryClientInterceptor',
2128
+ 'StreamStreamClientInterceptor',
2129
+ 'Channel',
2130
+ 'ServicerContext',
2131
+ 'RpcMethodHandler',
2132
+ 'HandlerCallDetails',
2133
+ 'GenericRpcHandler',
2134
+ 'ServiceRpcHandler',
2135
+ 'Server',
2136
+ 'ServerInterceptor',
2137
+ 'unary_unary_rpc_method_handler',
2138
+ 'unary_stream_rpc_method_handler',
2139
+ 'stream_unary_rpc_method_handler',
2140
+ 'stream_stream_rpc_method_handler',
2141
+ 'method_handlers_generic_handler',
2142
+ 'ssl_channel_credentials',
2143
+ 'metadata_call_credentials',
2144
+ 'access_token_call_credentials',
2145
+ 'composite_call_credentials',
2146
+ 'composite_channel_credentials',
2147
+ 'compute_engine_channel_credentials',
2148
+ 'local_channel_credentials',
2149
+ 'local_server_credentials',
2150
+ 'alts_channel_credentials',
2151
+ 'alts_server_credentials',
2152
+ 'ssl_server_credentials',
2153
+ 'ssl_server_certificate_configuration',
2154
+ 'dynamic_ssl_server_credentials',
2155
+ 'channel_ready_future',
2156
+ 'insecure_channel',
2157
+ 'secure_channel',
2158
+ 'intercept_channel',
2159
+ 'server',
2160
+ 'protos',
2161
+ 'services',
2162
+ 'protos_and_services',
2163
+ 'xds_channel_credentials',
2164
+ 'xds_server_credentials',
2165
+ 'insecure_server_credentials',
2166
+ )
2167
+
2168
+ ############################### Extension Shims ################################
2169
+
2170
+ # Here to maintain backwards compatibility; avoid using these in new code!
2171
+ try:
2172
+ import grpc_tools
2173
+ sys.modules.update({'grpc.tools': grpc_tools})
2174
+ except ImportError:
2175
+ pass
2176
+ try:
2177
+ import grpc_health
2178
+ sys.modules.update({'grpc.health': grpc_health})
2179
+ except ImportError:
2180
+ pass
2181
+ try:
2182
+ import grpc_reflection
2183
+ sys.modules.update({'grpc.reflection': grpc_reflection})
2184
+ except ImportError:
2185
+ pass
2186
+
2187
+ # Prevents import order issue in the case of renamed path.
2188
+ if sys.version_info >= (3, 6) and __name__ == "grpc":
2189
+ from grpc import aio # pylint: disable=ungrouped-imports
2190
+ sys.modules.update({'grpc.aio': aio})